diff options
Diffstat (limited to 'mso-api-handlers/mso-api-handler-infra')
102 files changed, 3353 insertions, 2272 deletions
diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index a3b9827d9f..84a80e6617 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -18,7 +18,7 @@ <camunda.bpm.assert.version>1.2</camunda.bpm.assert.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> - <swagger-version>1.3.0</swagger-version> + <swagger.version>2.0.8</swagger.version> <jax-rs-version>1.1.1</jax-rs-version> <json4s-jackson-version>3.6.0</json4s-jackson-version> <json4s-core-version>3.6.0</json4s-core-version> @@ -56,10 +56,16 @@ <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> + + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + <version>${swagger.version}</version> + </dependency> <dependency> - <groupId>io.swagger</groupId> - <artifactId>swagger-jersey2-jaxrs</artifactId> - <version>1.5.16</version> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-jaxrs2</artifactId> + <version>2.0.6</version> </dependency> <dependency> <groupId>com.h2database</groupId> @@ -219,6 +225,17 @@ <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> + <dependency> + <groupId>org.onap.aaf.authz</groupId> + <artifactId>aaf-cadi-aaf</artifactId> + <version>2.1.9</version> + <exclusions> + <exclusion> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </exclusion> + </exclusions> + </dependency> </dependencies> <build> @@ -271,6 +288,9 @@ <executions> <execution> <id>original</id> + <configuration> + <skip>false</skip> + </configuration> </execution> </executions> </plugin> 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 deleted file mode 100644 index a3ff1ab95d..0000000000 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============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.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; - } -} 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 d0302f2e59..88c4bc3b04 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 @@ -45,5 +45,6 @@ public enum Action implements Actions { scaleOut, recreateInstance, addMembers, - removeMembers + removeMembers, + forCustomWorkflow } 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 5beb4810ec..482fd8868a 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,7 @@ package org.onap.so.apihandlerinfra; import java.util.concurrent.Executor; -import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; +import org.onap.logging.filter.spring.MDCTaskDecorator; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index 451fa64585..e9f17c42d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -7,11 +7,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.DatatypeConverter; -import org.apache.http.HttpStatus; import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; -import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,6 +21,8 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.stereotype.Component; @@ -33,15 +34,16 @@ import org.springframework.web.client.RestTemplate; public class CamundaRequestHandler { private static Logger logger = LoggerFactory.getLogger(CamundaRequestHandler.class); - - @Autowired - private RestTemplate restTemplate; + private static final String TIMEOUT = "30000"; + private static final String RETRY_TIMEOUT = "15000"; + private static final String TIMEOUT_PROPERTY = "mso.camunda.request.timeout"; + private static final String RETRY_TIMEOUT_PROPERTY = "mso.camunda.request.timeout.retry"; @Autowired private Environment env; - public ResponseEntity<List<HistoricProcessInstanceEntity>> getCamundaProcessInstanceHistory(String requestId) { - RetryTemplate retryTemplate = setRetryTemplate(); + public ResponseEntity<List<HistoricProcessInstanceEntity>> getCamundaProcessInstanceHistory(String requestId, + boolean retry) { String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; String targetUrl = env.getProperty("mso.camundaURL") + path; HttpHeaders headers = @@ -49,86 +51,91 @@ public class CamundaRequestHandler { HttpEntity<?> requestEntity = new HttpEntity<>(headers); - return retryTemplate.execute(context -> { - if (context.getLastThrowable() != null) { - logger.error("Retrying: Last call resulted in exception: ", context.getLastThrowable()); - } - if (context.getRetryCount() == 0) { - logger.info("Querying Camunda for process-instance history for requestId: {}", requestId); - } else { - logger.info("Retry: {} of 3. Querying Camunda for process-instance history for requestId: {}", - context.getRetryCount(), requestId); - } - return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - }); - } - - protected ResponseEntity<List<HistoricActivityInstanceEntity>> getCamundaActivityHistory(String processInstanceId, - String requestId) throws ContactCamundaException { - RetryTemplate retryTemplate = setRetryTemplate(); - String path = env.getProperty("mso.camunda.rest.activity.uri") + processInstanceId; - String targetUrl = env.getProperty("mso.camundaURL") + path; - HttpHeaders headers = - setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - try { + if (retry) { + RestTemplate restTemplate = getRestTemplate(retry); + RetryTemplate retryTemplate = getRetryTemplate(); return retryTemplate.execute(context -> { if (context.getLastThrowable() != null) { logger.error("Retrying: Last call resulted in exception: ", context.getLastThrowable()); } if (context.getRetryCount() == 0) { - logger.info( - "Querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}", - processInstanceId, requestId); + logger.info("Querying Camunda for process-instance history for requestId: {}", requestId); } else { logger.info( - "Retry: {} of 3. Querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}", - context.getRetryCount(), processInstanceId, requestId); + "Retry: Querying Camunda for process-instance history for retryCount: {} and requestId: {}", + context.getRetryCount(), requestId); } - return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); }); - - } catch (RestClientException e) { - logger.error( - "Error querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}, exception: {}", - processInstanceId, requestId, e.getMessage()); - throw new ContactCamundaException.Builder("activity-instance", requestId, e.toString(), - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); + } else { + RestTemplate restTemplate = getRestTemplate(retry); + return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); } } - protected String getTaskName(String requestId) throws ContactCamundaException { + protected ResponseEntity<List<HistoricActivityInstanceEntity>> getCamundaActivityHistory(String processInstanceId) { + RestTemplate restTemplate = getRestTemplate(false); + String path = env.getProperty("mso.camunda.rest.activity.uri") + processInstanceId; + String targetUrl = env.getProperty("mso.camundaURL") + path; + HttpHeaders headers = + setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + + return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + } + + protected String getTaskName(String requestId) { ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; - ResponseEntity<List<HistoricActivityInstanceEntity>> activityResponse = null; - String processInstanceId = null; + + String taskInformation = null; try { - response = getCamundaProcessInstanceHistory(requestId); + response = getCamundaProcessInstanceHistory(requestId, false); } catch (RestClientException e) { - logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}", + logger.warn("Error querying Camunda for process-instance history for requestId: {}, exception: {}", requestId, e.getMessage()); - throw new ContactCamundaException.Builder("process-instance", requestId, e.toString(), - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); } + if (response != null) { + taskInformation = getTaskInformation(response, requestId); + } + return taskInformation; + } + + protected String getTaskInformation(ResponseEntity<List<HistoricProcessInstanceEntity>> response, + String requestId) { List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody(); + ResponseEntity<List<HistoricActivityInstanceEntity>> activityResponse = null; + String processInstanceId = null; + String taskInformation = null; - if (historicProcessInstanceList != null) { + if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) { Collections.reverse(historicProcessInstanceList); processInstanceId = historicProcessInstanceList.get(0).getId(); } else { - return "No processInstances returned for requestId: " + requestId; + logger.warn("No processInstances returned for requestId: {} to get TaskInformation", requestId); } if (processInstanceId != null) { - activityResponse = getCamundaActivityHistory(processInstanceId, requestId); + try { + activityResponse = getCamundaActivityHistory(processInstanceId); + } catch (RestClientException e) { + logger.warn( + "Error querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}, exception: {}", + processInstanceId, requestId, e.getMessage()); + } } else { - return "No processInstanceId returned for requestId: " + requestId; + logger.warn("No processInstanceId returned for requestId: {} to get TaskInformation", requestId); } - return getActivityName(activityResponse.getBody()); + if (activityResponse != null) { + taskInformation = getActivityName(activityResponse.getBody()); + } else { + logger.warn("No activity history information returned for requestId: {} to get TaskInformation", requestId); + } + return taskInformation; } protected String getActivityName(List<HistoricActivityInstanceEntity> activityInstanceList) { @@ -169,12 +176,31 @@ public class CamundaRequestHandler { return headers; } - protected RetryTemplate setRetryTemplate() { + protected RetryTemplate getRetryTemplate() { RetryTemplate retryTemplate = new RetryTemplate(); Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>(); retryableExceptions.put(ResourceAccessException.class, true); - SimpleRetryPolicy policy = new SimpleRetryPolicy(4, retryableExceptions); + SimpleRetryPolicy policy = new SimpleRetryPolicy(2, retryableExceptions); retryTemplate.setRetryPolicy(policy); return retryTemplate; } + + protected RestTemplate getRestTemplate(boolean retry) { + int timeout; + if (retry) { + timeout = Integer.parseInt(env.getProperty(RETRY_TIMEOUT_PROPERTY, RETRY_TIMEOUT)); + } else { + timeout = Integer.parseInt(env.getProperty(TIMEOUT_PROPERTY, TIMEOUT)); + } + + RestTemplate restTemplate = new RestTemplate(); + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setConnectionRequestTimeout(timeout); + factory.setReadTimeout(timeout); + factory.setConnectTimeout(timeout); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; + } } 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 d3a279fd8e..0bcb0f1c86 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 @@ -76,13 +76,19 @@ 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; - +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/e2eServiceInstances") -@Api(value = "/onap/so/infra/e2eServiceInstances", description = "API Requests for E2E Service Instances") +@OpenAPIDefinition(info = @Info(title = "/onap/so/infra/e2eServiceInstances", + description = "API Requests for E2E Service Instances")) + public class E2EServiceInstances { private HashMap<String, String> instanceIdMap = new HashMap<>(); @@ -119,7 +125,8 @@ public class E2EServiceInstances { @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) + @Operation(description = "Create an E2E Service Instance on a version provided", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response createE2EServiceInstance(String request, @PathParam("version") String version) throws ApiException { return processE2EserviceInstances(request, Action.createInstance, null, version); @@ -135,8 +142,9 @@ public class E2EServiceInstances { @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) + @Operation(description = "Update an E2E Service Instance on a version provided and serviceId", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response updateE2EServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceId") String serviceId) throws ApiException { @@ -155,7 +163,9 @@ public class E2EServiceInstances { @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) + @Operation(description = "Delete E2E Service Instance on a specified version and serviceId", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response deleteE2EServiceInstance(String request, @PathParam("version") String version, @PathParam(SERVICE_ID) String serviceId) throws ApiException { @@ -166,8 +176,9 @@ public class E2EServiceInstances { @GET @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}") - @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId", - response = Response.class) + @Operation(description = "Find e2eServiceInstances Requests for a given serviceId and operationId", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Produces(MediaType.APPLICATION_JSON) public Response getE2EServiceInstances(@PathParam(SERVICE_ID) String serviceId, @PathParam("version") String version, @PathParam("operationId") String operationId) { @@ -184,7 +195,8 @@ public class E2EServiceInstances { @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) + @Operation(description = "Scale E2E Service Instance on a specified version", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response scaleE2EServiceInstance(String request, @PathParam("version") String version, @PathParam(SERVICE_ID) String serviceId) throws ApiException { @@ -203,9 +215,10 @@ public class E2EServiceInstances { @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) + @Operation( + description = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response compareModelwithTargetVersion(String request, @PathParam("serviceId") String serviceId, @PathParam("version") String version) throws ApiException { @@ -282,7 +295,7 @@ public class E2EServiceInstances { msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); return resp; } @@ -320,7 +333,7 @@ public class E2EServiceInstances { MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB", ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from RequestDB when searching by serviceId"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; @@ -422,7 +435,7 @@ public class E2EServiceInstances { msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -536,7 +549,7 @@ public class E2EServiceInstances { msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); return getBPMNResp; } @@ -647,7 +660,7 @@ public class E2EServiceInstances { msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -747,7 +760,7 @@ public class E2EServiceInstances { msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), - MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcessError.getValue(), "Null response from BPEL"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } @@ -778,7 +791,7 @@ public class E2EServiceInstances { "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), - requestClient.getUrl(), ErrorCode.BusinessProcesssError.getValue(), + requestClient.getUrl(), ErrorCode.BusinessProcessError.getValue(), "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; @@ -787,7 +800,7 @@ public class E2EServiceInstances { "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"); + ErrorCode.BusinessProcessError.getValue(), "Response from BPEL engine is empty"); logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); return resp; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java new file mode 100644 index 0000000000..80144d8ca1 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java @@ -0,0 +1,33 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; +import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.GenericConverter; +import org.springframework.stereotype.Component; +import com.google.common.collect.ImmutableSet; + +@Component +@ConfigurationPropertiesBinding +public class GenericStringConverter implements GenericConverter { + + @Autowired + private HealthCheckConverter converter; + + @Override + public Set<ConvertiblePair> getConvertibleTypes() { + + ConvertiblePair[] pairs = new ConvertiblePair[] {new ConvertiblePair(String.class, Subsystem.class), + new ConvertiblePair(String.class, URI.class)}; + return ImmutableSet.copyOf(pairs); + } + + @Override + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + + return converter.convert(source, sourceType, targetType); + + } +} 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 3d4b2c76fb..5327211280 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,11 +25,8 @@ package org.onap.so.apihandlerinfra; import java.net.URI; import java.util.Collections; -import org.onap.so.logger.LoggingAnchor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; +import java.util.List; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.transaction.Transactional; import javax.ws.rs.DefaultValue; @@ -42,95 +39,96 @@ 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.apihandlerinfra.HealthCheckConfig.Endpoint; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; -import org.springframework.http.HttpMethod; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/globalhealthcheck") -@Api(value = "/globalhealthcheck", description = "APIH Infra Global Health Check") +@OpenAPIDefinition(info = @Info(title = "/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 = ""; + protected static final String CONTEXTPATH_PROPERTY = "management.endpoints.web.base-path"; + protected static final String PROPERTY_DOMAIN = "mso.health"; + protected static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".endpoints.catalogdb"; + protected static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".endpoints.requestdb"; + protected static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.sdnc"; + protected static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".endpoints.openstack"; + protected static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".endpoints.bpmn"; + protected static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.asdc"; + protected static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.requestdbattsvc"; + protected static final String MSO_AUTH_PROPERTY = PROPERTY_DOMAIN + ".auth"; + protected 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"; + @Autowired + private HealthCheckConfig config; + + private static final String HEALTH = "/health"; + + private String msoAuth; @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); + msoAuth = env.getProperty(MSO_AUTH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); } @GET @Produces("application/json") - @ApiOperation(value = "Performing global health check", response = Response.class) + @Operation(description = "Performing global health check", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional 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(); + HealthCheckResponse rsp = new HealthCheckResponse(); try { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); logger.info(LoggingAnchor.TWO, 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)); - // set ASDCController - rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC)); - // set CatalogDbAdapter - rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB)); - // set RequestDbAdapter - rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB)); - // set OpenStackAdapter - rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK)); - // set RequestDbAdapterAttSvc - rsp.setRequestdbAdapterAttsvc(querySubsystemHealth(MsoSubsystems.REQUESTDBATT)); + List<Endpoint> endpoints = config.getEndpoints().stream().filter(item -> { + if (!enableBpmn && SoSubsystems.BPMN.equals(item.getSubsystem())) { + return false; + } else { + return true; + } + }).collect(Collectors.toList()); + + for (Endpoint endpoint : endpoints) { + rsp.getSubsystems().add(querySubsystemHealth(endpoint)); + } + // set Message rsp.setMessage(String.format("HttpStatus: %s", HttpStatus.SC_OK)); logger.info(rsp.toString()); @@ -149,70 +147,51 @@ public class GlobalHealthcheckHandler { protected HttpEntity<String> buildHttpEntityForRequest() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - headers.set("Content-Type", "application/json"); + headers.set(HttpHeaders.CONTENT_TYPE, "application/json"); + headers.set(HttpHeaders.AUTHORIZATION, msoAuth); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); return entity; } - protected String querySubsystemHealth(MsoSubsystems subsystem) { + protected HealthCheckSubsystem querySubsystemHealth(Endpoint subsystem) { + HealthCheckStatus status = HealthCheckStatus.DOWN; + URI uri = subsystem.getUri(); 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()); + uri = UriBuilder.fromUri(subsystem.getUri()).path(actuatorContextPath).path(HEALTH).build(); + logger.info("Calculated URL: {}", uri); ResponseEntity<SubsystemHealthcheckResponse> result = restTemplate.exchange(uri, HttpMethod.GET, buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class); - return processResponseFromSubsystem(result, subsystem); + status = processResponseFromSubsystem(result, subsystem); + } catch (Exception ex) { logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex); - return HealthcheckStatus.DOWN.toString(); } + + return new HealthCheckSubsystem(subsystem.getSubsystem(), uri, status); } - protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, - MsoSubsystems subsystem) { + protected HealthCheckStatus processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, + Endpoint endpoint) { 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(); + endpoint.getSubsystem(), result == null ? "NULL" : result)); + return HealthCheckStatus.DOWN; } SubsystemHealthcheckResponse body = result.getBody(); String status = body.getStatus(); if ("UP".equalsIgnoreCase(status)) { - return HealthcheckStatus.UP.toString(); + return HealthCheckStatus.UP; } else { - logger.error("{}, query health endpoint did not return UP status!", subsystem); - return HealthcheckStatus.DOWN.toString(); + logger.error("{}, query health endpoint did not return UP status!", endpoint.getSubsystem()); + return HealthCheckStatus.DOWN; } } - - 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/HealthCheck.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java new file mode 100644 index 0000000000..1899cdd765 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java @@ -0,0 +1,84 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; +import javax.ws.rs.core.UriBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ConfigurationProperties(prefix = "mso.health.enpoints") +public class HealthCheck { + + private Subsystem subsystem; + private URI uri; + private HealthCheckStatus status = HealthCheckStatus.DOWN; + + public HealthCheck() { + + } + + public HealthCheck(String subsystem, String uri) { + this.subsystem = SoSubsystems.valueOf(subsystem.toUpperCase()); + this.uri = UriBuilder.fromUri(uri).build(); + } + + public HealthCheck(Subsystem subsystem, URI uri) { + this.subsystem = subsystem; + this.uri = uri; + } + + public HealthCheck(Subsystem subsystem, URI uri, HealthCheckStatus status) { + this.subsystem = subsystem; + this.uri = uri; + this.status = status; + } + + public Subsystem getSubsystem() { + return subsystem; + } + + public void setSubsystem(Subsystem component) { + this.subsystem = component; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + + public HealthCheckStatus getStatus() { + return status; + } + + public void setStatus(HealthCheckStatus status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("subsystem", subsystem).append("uri", uri).append("status", status) + .toString(); + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof HealthCheck)) { + return false; + } + HealthCheck castOther = (HealthCheck) other; + return new EqualsBuilder().append(subsystem, castOther.subsystem).append(uri, castOther.uri) + .append(status, castOther.status).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(subsystem).append(uri).append(status).toHashCode(); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java new file mode 100644 index 0000000000..11fd94bc91 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java @@ -0,0 +1,83 @@ +/*- + * ============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 java.net.URI; +import java.util.List; +import javax.validation.constraints.NotNull; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.validation.annotation.Validated; + +@Configuration +@ConfigurationProperties(prefix = "mso.health") +@Validated +public class HealthCheckConfig { + + @NotNull + private List<Endpoint> endpoints; + + public List<Endpoint> getEndpoints() { + return endpoints; + } + + public void setEndpoints(List<Endpoint> endpoints) { + this.endpoints = endpoints; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("endpoints", this.endpoints).toString(); + } + + @Validated + public static class Endpoint { + @NotNull + private Subsystem subsystem; + @NotNull + private URI uri; + + public Endpoint() { + + } + + public Endpoint(Subsystem subsystem, URI uri) { + this.subsystem = subsystem; + this.uri = uri; + } + + public Subsystem getSubsystem() { + return subsystem; + } + + public void setSubsystem(Subsystem subsystem) { + this.subsystem = subsystem; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java new file mode 100644 index 0000000000..ed06018e7b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java @@ -0,0 +1,22 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; +import javax.ws.rs.core.UriBuilder; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.stereotype.Component; + +@Component +public class HealthCheckConverter { + + + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + if (sourceType.getType() == String.class && targetType.getType() == Subsystem.class) { + return SoSubsystems.valueOf(((String) source).toUpperCase()); + } else if (sourceType.getType() == String.class && targetType.getType() == URI.class) { + return UriBuilder.fromUri((String) source).build(); + } else { + return source; + } + } + +} 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 new file mode 100644 index 0000000000..5400249c65 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckResponse.java @@ -0,0 +1,49 @@ +/*- + * ============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 java.util.ArrayList; +import java.util.List; + +public class HealthCheckResponse { + + + private List<HealthCheckSubsystem> subsystems = new ArrayList<>(); + private String message; + + + public List<HealthCheckSubsystem> getSubsystems() { + return subsystems; + } + + public void setSubsystems(List<HealthCheckSubsystem> subsystems) { + this.subsystems = subsystems; + } + + public String getMessage() { + return 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/HealthcheckStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckStatus.java index 077a3c2d60..6b31c1f1ed 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 @@ -19,12 +19,12 @@ */ package org.onap.so.apihandlerinfra; -public enum HealthcheckStatus { +public enum HealthCheckStatus { UP("UP"), DOWN("DOWN"); private String status; - private HealthcheckStatus(String status) { + private HealthCheckStatus(String status) { this.status = status; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java new file mode 100644 index 0000000000..e1335b952c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java @@ -0,0 +1,40 @@ +package org.onap.so.apihandlerinfra; + +import java.net.URI; + +public class HealthCheckSubsystem { + + private Subsystem subsystem; + private URI uri; + private HealthCheckStatus status; + + public HealthCheckSubsystem(Subsystem subsystem, URI uri, HealthCheckStatus status) { + this.subsystem = subsystem; + this.uri = uri; + this.status = status; + } + + public Subsystem getSubsystem() { + return subsystem; + } + + public void setSubsystem(Subsystem subsystem) { + this.subsystem = subsystem; + } + + public URI getUri() { + return uri; + } + + public void setUri(URI uri) { + this.uri = uri; + } + + public HealthCheckStatus getStatus() { + return status; + } + + public void setStatus(HealthCheckStatus status) { + this.status = status; + } +} 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 deleted file mode 100644 index fad3dd4055..0000000000 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============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 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(); - } -} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index 15572f2b39..dbdc274bc6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -23,8 +23,6 @@ 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; @@ -61,10 +59,18 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.HashMap; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/instanceManagement") -@Api(value = "/onap/so/infra/instanceManagement", description = "Infrastructure API Requests for Instance Management") +@OpenAPIDefinition(info = @Info(title = "/onap/so/infra/instanceManagement", + description = "Infrastructure API Requests for Instance Management")) public class InstanceManagement { private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class); @@ -87,9 +93,10 @@ public class InstanceManagement { @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) + @Operation(description = "Execute custom workflow", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional - public Response executeCustomWorkflow(String request, @PathParam("version") String version, + public Response executeVNFCustomWorkflow(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException { @@ -102,6 +109,26 @@ public class InstanceManagement { requestContext); } + @POST + @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/pnfs/{pnfId}/workflows/{workflowUuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(description = "Execute custom workflow", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Transactional + public Response executePNFCustomWorkflow(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("pnfId") String pnfId, + @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("pnfId", pnfId); + instanceIdMap.put("workflowUuid", workflowUuid); + return processPNFCustomWorkflowRequest(request, Action.forCustomWorkflow, instanceIdMap, version, requestId, + requestContext); + } + private Response processCustomWorkflowRequest(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException { @@ -210,6 +237,93 @@ public class InstanceManagement { recipeLookupResult.getOrchestrationURI(), requestScope); } + private Response processPNFCustomWorkflowRequest(String requestJSON, Actions action, + HashMap<String, String> instanceIdMap, String version, String requestId, + ContainerRequestContext requestContext) throws ApiException { + Boolean aLaCarte = false; + ServiceInstancesRequest sir; + String apiVersion = version.substring(1); + + String serviceInstanceId = ""; + String pnfId = ""; + String workflowUuid = ""; + if (instanceIdMap != null) { + serviceInstanceId = instanceIdMap.get("serviceInstanceId"); + pnfId = instanceIdMap.get("pnfId"); + workflowUuid = instanceIdMap.get("workflowUuid"); + } + + String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); + sir.setServiceInstanceId(serviceInstanceId); + sir.setPnfId(pnfId); + String requestScope = ModelType.pnf.name(); + 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); + + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); + + if (dup != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); + } + + RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid); + + try { + infraActiveRequestsClient.save(currentActiveReq); + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.toString()) + .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfId) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, null, aLaCarte, action)) + .setApiVersion(apiVersion).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; 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 00d36b3ff9..b7288e4c91 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 @@ -7,9 +7,9 @@ * 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. @@ -20,12 +20,16 @@ package org.onap.so.apihandlerinfra; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.annotation.PostConstruct; +import javax.servlet.ServletConfig; import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Context; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletProperties; +import org.onap.logging.filter.base.Constants; import org.onap.so.apihandler.filters.RequestIdFilter; -import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper; import org.onap.so.apihandlerinfra.infra.rest.Network; import org.onap.so.apihandlerinfra.infra.rest.ServiceInstance; @@ -40,12 +44,17 @@ import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.WorkflowEngineCon import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.ModelDistributionRequest; -import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; +import org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter; +import org.onap.so.utils.Components; 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; +import io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder; +import io.swagger.v3.jaxrs2.integration.resources.AcceptHeaderOpenApiResource; +import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource; +import io.swagger.v3.oas.integration.OpenApiConfigurationException; +import io.swagger.v3.oas.integration.SwaggerConfiguration; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; @Configuration @ApplicationPath("/") @@ -53,6 +62,7 @@ public class JerseyConfiguration extends ResourceConfig { @PostConstruct public void setUp() { + System.setProperty(Constants.Property.PARTNER_NAME, Components.APIH.toString()); register(GlobalHealthcheckHandler.class); register(NodeHealthcheckHandler.class); register(ServiceInstances.class); @@ -65,14 +75,13 @@ public class JerseyConfiguration extends ResourceConfig { register(Network.class); register(Volumes.class); register(ServiceInstance.class); - register(JaxRsFilterLogging.class); + register(SOAuditLogContainerFilter.class); register(ManualTasks.class); register(TasksHandler.class); - register(ApiListingResource.class); - register(SwaggerSerializers.class); + register(OpenApiResource.class); + register(AcceptHeaderOpenApiResource.class); register(ApiExceptionMapper.class); register(RuntimeExceptionMapper.class); - register(RequestUriFilter.class); register(RequestIdFilter.class); register(E2EServiceInstances.class); register(WorkflowSpecificationsHandler.class); @@ -88,12 +97,21 @@ public class JerseyConfiguration extends ResourceConfig { 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); + + OpenAPI oas = new OpenAPI(); + Info info = new Info(); + info.title("Swagger apihandlerinfra bootstrap code"); + info.setVersion("1.0.2"); + + SwaggerConfiguration oasConfig = new SwaggerConfiguration().openAPI(oas).prettyPrint(true) + .resourcePackages(Stream.of("org.onap.so.apihandlerinfra").collect(Collectors.toSet())); + + try { + new JaxrsOpenApiContextBuilder().application(this).openApiConfiguration(oasConfig).buildContext(true); + } catch (OpenApiConfigurationException e) { + throw new RuntimeException(e.getMessage(), e); + } + } } 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 b9b7fcc0d4..7e4452aeb3 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 @@ -34,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.onap.so.logger.LoggingAnchor; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; @@ -52,6 +51,7 @@ import org.onap.so.apihandlerinfra.tasksbeans.Value; import org.onap.so.apihandlerinfra.tasksbeans.Variables; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,8 +60,11 @@ 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; - +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Path("/tasks") @Component @@ -85,7 +88,8 @@ public class ManualTasks { @Path("/{version:[vV]1}/{taskId}/complete") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Complete specified task", response = Response.class) + @Operation(description = "Complete specified task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException { @@ -196,8 +200,9 @@ public class ManualTasks { } if (response == null) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, - ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); BPMNFailureException bpmnFailureException = @@ -225,7 +230,7 @@ public class ManualTasks { } catch (JsonProcessingException e) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, - ErrorCode.BusinessProcesssError).build(); + ErrorCode.BusinessProcessError).build(); ValidateException validateException = @@ -239,7 +244,7 @@ public class ManualTasks { return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion); } else { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) .build(); 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 4bcc0d4111..e3e840bbcd 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 @@ -140,18 +140,7 @@ public class MsoRequest { } 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("Exception in buildServiceErrorResponse writing exceptionType to string ", e); - } - - return builder.buildResponse(httpResponseCode, null, requestErrorStr, version); + return builder.buildResponse(httpResponseCode, null, re, version); } @@ -278,7 +267,6 @@ public class MsoRequest { String vnfType = ""; aq.setRequestId(requestId); aq.setRequestAction(action.toString()); - aq.setAction(action.toString()); aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); @@ -313,7 +301,7 @@ public class MsoRequest { if (servInsReq.getRequestDetails().getCloudConfiguration() != null) { CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration(); if (cloudConfiguration.getLcpCloudRegionId() != null) { - aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); + aq.setCloudRegion(cloudConfiguration.getLcpCloudRegionId()); } if (cloudConfiguration.getTenantId() != null) { @@ -330,9 +318,16 @@ public class MsoRequest { aq.setVnfId(servInsReq.getVnfInstanceId()); } + if (servInsReq.getPnfId() != null) { + aq.setRequestScope(requestScope); + aq.setPnfId(servInsReq.getPnfId()); + } + if (ModelType.service.name().equalsIgnoreCase(requestScope)) { - if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { - aq.setServiceInstanceName(requestInfo.getInstanceName()); + if (servInsReq.getRequestDetails().getRequestInfo() != null) { + if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { + aq.setServiceInstanceName(requestInfo.getInstanceName()); + } } } @@ -410,7 +405,6 @@ public class MsoRequest { 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()); 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 3337c62afd..e56ee24baf 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 @@ -22,7 +22,19 @@ package org.onap.so.apihandlerinfra; -import java.net.UnknownHostException; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import org.apache.http.HttpStatus; +import org.onap.so.logger.LoggingAnchor; +import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; import javax.transaction.Transactional; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -30,17 +42,10 @@ 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.onap.so.logger.LoggingAnchor; -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; +import java.net.UnknownHostException; @Path("/nodehealthcheck") -@Api(value = "/nodehealthcheck", description = "API Handler Infra Node Health Check") +@OpenAPIDefinition(info = @Info(title = "/nodehealthcheck", description = "API Handler Infra Node Health Check")) @Component public class NodeHealthcheckHandler { @@ -53,7 +58,8 @@ public class NodeHealthcheckHandler { @GET @Produces("text/html") - @ApiOperation(value = "Performing node health check", response = Response.class) + @Operation(description = "Performing node health check", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException { // Generated 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 6f36fb2aff..ae68cc6032 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 @@ -9,9 +9,9 @@ * 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. @@ -42,7 +42,9 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.EnumUtils; import org.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ApiException; @@ -69,19 +71,27 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; 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.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Path("onap/so/infra/orchestrationRequests") -@Api(value = "onap/so/infra/orchestrationRequests", description = "API Requests for Orchestration requests") +@OpenAPIDefinition(info = @Info(title = "onap/so/infra/orchestrationRequests", + description = "API Requests for Orchestration requests")) + @Component public class OrchestrationRequests { private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class); + private static final String ERROR_MESSAGE_PREFIX = "Error Source: %s, Error Message: %s"; @Autowired private RequestsDbClient requestsDbClient; @@ -97,7 +107,8 @@ public class OrchestrationRequests { @GET @Path("/{version:[vV][4-7]}/{requestId}") - @ApiOperation(value = "Find Orchestrated Requests for a given requestId", response = Response.class) + @Operation(description = "Find Orchestrated Requests for a given requestId", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@PathParam("requestId") String requestId, @@ -118,51 +129,45 @@ public class OrchestrationRequests { throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); } - 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(); - - 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; - - } - if (infraActiveRequest == null) { + infraActiveRequest = infraActiveRequestLookup(requestId); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, - ErrorCode.BusinessProcesssError).build(); + if (isRequestProcessingDataRequired(format)) { + try { + requestProcessingData = requestsDbClient.getExternalRequestProcessingDataBySoRequestId(requestId); + } catch (Exception e) { + logger.error( + "Exception occurred while communicating with RequestDb during requestProcessingData lookup ", + e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError) + .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( + "Exception occurred while communicating with RequestDb during requestProcessingData lookup", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw validateException; + } } Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest, format); - if (!requestProcessingData.isEmpty()) { + if (null != requestProcessingData && !requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } request.setRequestId(requestId); orchestrationResponse.setRequest(request); - return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion); + return builder.buildResponse(HttpStatus.SC_OK, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), orchestrationResponse, + apiVersion); } @GET @Path("/{version:[vV][4-7]}") - @ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class) + @Operation(description = "Find Orchestrated Requests for a URI Information", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Produces(MediaType.APPLICATION_JSON) @Transactional public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version, @@ -198,28 +203,34 @@ public class OrchestrationRequests { 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, includeCloudRequest, format); - if (!requestProcessingData.isEmpty()) { - request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + if (isRequestProcessingDataRequired(format)) { + List<RequestProcessingData> requestProcessingData = + requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); + if (null != requestProcessingData && !requestProcessingData.isEmpty()) { + request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + } } + requestList.setRequest(request); requestLists.add(requestList); } orchestrationList.setRequestList(requestLists); - return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); + return builder.buildResponse(HttpStatus.SC_OK, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), 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) + @Operation(description = "Unlock Orchestrated Requests for a given requestId", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException { @@ -227,8 +238,6 @@ public class OrchestrationRequests { logger.debug("requestId is: {}", requestId); ServiceInstancesRequest sir; - InfraActiveRequests infraActiveRequest; - try { ObjectMapper mapper = new ObjectMapper(); sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); @@ -258,41 +267,26 @@ public class OrchestrationRequests { 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; + InfraActiveRequests infraActiveRequest = infraActiveRequestLookup(requestId); + String status = infraActiveRequest.getRequestStatus(); + if (Status.IN_PROGRESS.toString().equalsIgnoreCase(status) || Status.PENDING.toString().equalsIgnoreCase(status) + || Status.PENDING_MANUAL_TASK.toString().equalsIgnoreCase(status)) { + infraActiveRequest.setRequestStatus(Status.UNLOCKED.toString()); + infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + infraActiveRequest.setRequestId(requestId); + requestsDbClient.save(infraActiveRequest); } else { - String status = infraActiveRequest.getRequestStatus(); - if (Status.IN_PROGRESS.toString().equalsIgnoreCase(status) - || Status.PENDING.toString().equalsIgnoreCase(status) - || Status.PENDING_MANUAL_TASK.toString().equalsIgnoreCase(status)) { - infraActiveRequest.setRequestStatus(Status.UNLOCKED.toString()); - 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(); + 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(); + 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; - } + throw validateException; } return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); } @@ -411,7 +405,11 @@ public class OrchestrationRequests { protected String mapRequestStatusToRequest(InfraActiveRequests iar, String format) { if (iar.getRequestStatus() != null) { - if (!StringUtils.isBlank(format) && OrchestrationRequestFormat.DETAIL.toString().equalsIgnoreCase(format)) { + boolean requestFormat = false; + if (format != null) { + requestFormat = EnumUtils.isValidEnum(OrchestrationRequestFormat.class, format.toUpperCase()); + } + if (requestFormat) { return iar.getRequestStatus(); } else { if (Status.ABORTED.toString().equalsIgnoreCase(iar.getRequestStatus()) @@ -428,7 +426,7 @@ public class OrchestrationRequests { } protected void mapRequestStatusAndExtSysErrSrcToRequest(InfraActiveRequests iar, RequestStatus status, - String format) throws ContactCamundaException { + String format) { String rollbackStatusMessage = iar.getRollbackStatusMessage(); String flowStatusMessage = iar.getFlowStatus(); String retryStatusMessage = iar.getRetryStatusMessage(); @@ -444,7 +442,12 @@ public class OrchestrationRequests { String statusMessages = null; if (iar.getStatusMessage() != null) { - statusMessages = "STATUS: " + iar.getStatusMessage(); + if (StringUtils.isNotBlank(iar.getExtSystemErrorSource())) { + statusMessages = "STATUS: " + + String.format(ERROR_MESSAGE_PREFIX, iar.getExtSystemErrorSource(), iar.getStatusMessage()); + } else { + statusMessages = "STATUS: " + iar.getStatusMessage(); + } } if (OrchestrationRequestFormat.STATUSDETAIL.toString().equalsIgnoreCase(format)) { @@ -532,4 +535,43 @@ public class OrchestrationRequests { addedRequestProcessingData.add(finalProcessingData); return addedRequestProcessingData; } + + protected boolean isRequestProcessingDataRequired(String format) { + if (StringUtils.isNotEmpty(format) && format.equalsIgnoreCase(OrchestrationRequestFormat.SIMPLE.name())) { + return false; + } else { + return true; + } + } + + protected InfraActiveRequests infraActiveRequestLookup(String requestId) throws ApiException { + InfraActiveRequests infraActiveRequest = null; + try { + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (Exception e) { + logger.error("Exception occurred while communicating with RequestDb during InfraActiveRequest lookup ", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + + ValidateException validateException = new ValidateException.Builder( + "Exception occurred while communicating with RequestDb during InfraActiveRequest lookup", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + + if (infraActiveRequest == null) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError) + .build(); + + ValidateException validateException = new ValidateException.Builder( + "Null response from RequestDB when searching by RequestId " + requestId, HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + return infraActiveRequest; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index 9ab95a2319..0c6ad0ba22 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * Modifications Copyright (C) 2019 IBM. * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ @@ -55,13 +56,22 @@ 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; import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException; import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.constants.Status; +import org.onap.so.db.catalog.beans.NetworkResource; +import org.onap.so.db.catalog.beans.NetworkResourceCustomization; +import org.onap.so.db.catalog.beans.Recipe; +import org.onap.so.db.catalog.beans.ServiceRecipe; import org.onap.so.db.catalog.beans.VfModule; +import org.onap.so.db.catalog.beans.VfModuleCustomization; +import org.onap.so.db.catalog.beans.VnfRecipe; +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -69,13 +79,19 @@ 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; import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.Networks; import org.onap.so.serviceinstancebeans.RelatedInstance; import org.onap.so.serviceinstancebeans.RelatedInstanceList; +import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestParameters; +import org.onap.so.serviceinstancebeans.Service; 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.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,7 +100,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; @@ -94,7 +109,9 @@ public class RequestHandlerUtils extends AbstractRestHandler { private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class); - private static final String SAVE_TO_DB = "save instance to db"; + protected static final String SAVE_TO_DB = "save instance to db"; + private static final String NAME = "name"; + private static final String VALUE = "value"; @Autowired private Environment env; @@ -103,9 +120,6 @@ public class RequestHandlerUtils extends AbstractRestHandler { private RequestClientFactory reqClientFactory; @Autowired - private RequestsDbClient infraActiveRequestsClient; - - @Autowired private ResponseBuilder builder; @Autowired @@ -119,13 +133,14 @@ public class RequestHandlerUtils extends AbstractRestHandler { public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, String orchestrationUri, String requestScope) throws ApiException { - RequestClient requestClient = null; HttpResponse response = null; + RequestClient requestClient = null; + try { requestClient = reqClientFactory.getRequestClient(orchestrationUri); response = requestClient.post(requestClientParameter); } catch (Exception e) { - + logger.error("Error posting request to BPMN", e); ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); @@ -134,19 +149,17 @@ public class RequestHandlerUtils extends AbstractRestHandler { 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(); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError) + .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; } @@ -208,7 +221,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) .errorSource(requestClient.getUrl()).build(); BPMNFailureException bpmnException = new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, @@ -220,7 +233,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { } else { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) .errorSource(requestClient.getUrl()).build(); @@ -232,6 +245,9 @@ public class RequestHandlerUtils extends AbstractRestHandler { } } + + + @Override public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException { if ((status == Status.FAILED) || (status == Status.COMPLETE)) { @@ -259,12 +275,18 @@ public class RequestHandlerUtils extends AbstractRestHandler { } else if (action == Action.addMembers || action == Action.removeMembers) { return (ModelType.instanceGroup.toString()); } else { - String requestScope; + String requestScope = requestScopeFromUri(requestUri);; + + if (sir.getRequestDetails() == null) { + return requestScope; + } + if (sir.getRequestDetails().getModelInfo() == null) { + return requestScope; + } if (sir.getRequestDetails().getModelInfo().getModelType() == null) { - requestScope = requestScopeFromUri(requestUri); - } else { - requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); + return requestScope; } + requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); return requestScope; } } @@ -291,11 +313,27 @@ public class RequestHandlerUtils extends AbstractRestHandler { return requestUri; } + public void checkForDuplicateRequests(Actions action, HashMap<String, String> instanceIdMap, String requestScope, + InfraActiveRequests currentActiveReq, String instanceName) throws ApiException { + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); + + if (dup != null) { + inProgress = camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { + buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, requestScope, dup); + } + } + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { - if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance + if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))) { dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope); } @@ -318,7 +356,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { String requestId = duplicateRecord.getRequestId(); ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; try { - response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId); + response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId, true); } catch (RestClientException e) { logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}", requestId, e.getMessage()); @@ -334,7 +372,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); } for (HistoricProcessInstance instance : response.getBody()) { - if (instance.getState().equals("ACTIVE")) { + if (("ACTIVE").equals(instance.getState())) { return true; } else { updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); @@ -412,6 +450,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { throw dupException; } + @Override public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { String requestId = null; if (requestContext.getProperty("requestId") != null) { @@ -472,6 +511,9 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); } + if (instanceIdMap.get("PnfId") != null) { + currentActiveReq.setPnfId(instanceIdMap.get("PnfId")); + } } } @@ -479,24 +521,11 @@ public class RequestHandlerUtils extends AbstractRestHandler { 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); + if (serviceInstRequest != null) { + return mapper.writeValueAsString(serviceInstRequest); + } else { + return msoRawRequest; } - return null; } public Optional<String> retrieveModelName(RequestParameters requestParams) { @@ -590,6 +619,8 @@ public class RequestHandlerUtils extends AbstractRestHandler { requestScope = ModelType.configuration.name(); } else if (requestUri.contains(ModelType.vnf.name())) { requestScope = ModelType.vnf.name(); + } else if (requestUri.contains(ModelType.pnf.name())) { + requestScope = ModelType.pnf.name(); } else { requestScope = ModelType.service.name(); } @@ -612,7 +643,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (infraActiveRequest != null) { request.setTenantId(infraActiveRequest.getTenantId()); request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId)); - request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); + request.setCloudRegion(infraActiveRequest.getCloudRegion()); request.setRequestScope(infraActiveRequest.getRequestScope()); request.setRequestAction(infraActiveRequest.getRequestAction()); setInstanceIdAndName(infraActiveRequest, request); @@ -699,4 +730,567 @@ public class RequestHandlerUtils extends AbstractRestHandler { "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))", "$1" + newRequestorId + "$3"); } + + public 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()); + + throw validateException; + } + } else if (modelInfo.getModelType().equals(ModelType.vfModule) + || modelInfo.getModelType().equals(ModelType.volumeGroup) + || modelInfo.getModelType().equals(ModelType.vnf)) { + try { + 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(); + + + 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; + } + } else if (modelInfo.getModelType().equals(ModelType.network)) { + try { + 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(); + + + 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; + } + } 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(); + + + 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()); + throw recipeNotFoundExceptionException; + } + return recipeLookupResult; + } + + protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, + boolean alaCarteFlag) throws IOException { + // SERVICE REQUEST + // Construct the default service name + // TODO need to make this a configurable property + 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); + } + } + + private Service serviceMapper(Map<String, Object> params) throws IOException { + 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>> 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); + } + + 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; + } + + 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 RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) { + String defaultSource = getDefaultModel(sir); + VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); + 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<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(); + } + + 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; + 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) { + vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId); + 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"); + } + for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) { + if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) { + vrc = vnfResourceCustom; + } + } + + 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) { + 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()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java index ed300d95c2..65537cbba0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -57,11 +57,17 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpClientErrorException; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Path("onap/so/infra/orchestrationRequests") -@Api(value = "onap/so/infra/orchestrationRequests") +@OpenAPIDefinition(info = @Info(title = "onap/so/infra/orchestrationRequests")) + @Component public class ResumeOrchestrationRequest { private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class); @@ -84,7 +90,8 @@ public class ResumeOrchestrationRequest { @Path("/{version:[vV][7]}/{requestId}/resume") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Resume request for a given requestId", response = Response.class) + @Operation(description = "Resume request for a given requestId", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { @@ -115,8 +122,9 @@ public class ResumeOrchestrationRequest { if (infraActiveRequest == null) { logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, - ErrorCode.BusinessProcesssError).build(); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcessError) + .build(); ValidateException validateException = new ValidateException.Builder( "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); @@ -144,7 +152,7 @@ public class ResumeOrchestrationRequest { Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir); - RecipeLookupResult recipeLookupResult = serviceInstances.getServiceInstanceOrchestrationURI(sir, action, + RecipeLookupResult recipeLookupResult = requestHandlerUtils.getServiceInstanceOrchestrationURI(sir, action, msoRequest.getAlacarteFlag(sir), currentActiveRequest); requestDbSave(currentActiveRequest); 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 5b827d9cf8..175b212c86 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 @@ -24,10 +24,7 @@ package org.onap.so.apihandlerinfra; import java.io.IOException; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.Optional; import javax.transaction.Transactional; import javax.ws.rs.Consumes; @@ -47,21 +44,14 @@ import org.onap.so.apihandler.common.CommonConstants; 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.infra.rest.BpmnRequestBuilder; +import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; +import org.onap.so.apihandlerinfra.infra.rest.validators.RequestValidatorListenerRunner; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.constants.Status; -import org.onap.so.db.catalog.beans.NetworkResource; -import org.onap.so.db.catalog.beans.NetworkResourceCustomization; -import org.onap.so.db.catalog.beans.Recipe; -import org.onap.so.db.catalog.beans.ServiceRecipe; -import org.onap.so.db.catalog.beans.VfModule; -import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.VnfRecipe; -import org.onap.so.db.catalog.beans.VnfResource; -import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -71,38 +61,31 @@ import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; -import org.onap.so.serviceinstancebeans.Networks; -import org.onap.so.serviceinstancebeans.RelatedInstance; -import org.onap.so.serviceinstancebeans.RelatedInstanceList; import org.onap.so.serviceinstancebeans.RequestDetails; -import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.RequestReferences; -import org.onap.so.serviceinstancebeans.Service; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/serviceInstantiation") -@Api(value = "/onap/so/infra/serviceInstantiation", description = "Infrastructure API Requests for Service Instances") +@OpenAPIDefinition(info = @Info(title = "/onap/so/infra/serviceInstantiation", + description = "Infrastructure API Requests for Service Instances")) public class ServiceInstances extends AbstractRestHandler { 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"; @@ -124,11 +107,18 @@ public class ServiceInstances extends AbstractRestHandler { @Autowired private RequestHandlerUtils requestHandlerUtils; + @Autowired + private RequestValidatorListenerRunner requestValidatorListenerRunner; + + @Autowired + private BpmnRequestBuilder bpmnRequestBuilder; + @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) + @Operation(description = "Create a Service Instance on a version provided", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { @@ -141,7 +131,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Activate provided Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response activateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -157,7 +148,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Deactivate provided Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deactivateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -173,7 +165,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete provided Service Instance", response = Response.class) + @Operation(description = "Delete provided Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -189,7 +182,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][7]}/serviceInstances/assign") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Assign Service Instance", response = Response.class) + @Operation(description = "Assign Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response assignServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { @@ -202,7 +196,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/unassign") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Unassign Service Instance", response = Response.class) + @Operation(description = "Unassign Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response unassignServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -218,7 +213,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Create Port Mirroring Configuration", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createPortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -234,7 +230,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Delete provided Port", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deletePortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -252,7 +249,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Enable Port Mirroring", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response enablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -270,7 +268,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Disable Port Mirroring", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response disablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -288,7 +287,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Activate Port Mirroring", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response activatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -306,7 +306,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Deactivate Port Mirroring", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deactivatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -324,7 +325,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Add Relationships to a Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response addRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -340,7 +342,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Remove Relationships from Service Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response removeRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -356,7 +359,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Create VNF on a specified version and serviceInstance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -377,7 +381,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Replace provided VNF instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response replaceVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -394,8 +399,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Update VNF on a specified version, serviceInstance and vnfInstance", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response updateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -412,7 +418,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Apply updated configuration", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response applyUpdatedConfig(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { @@ -428,7 +435,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Recreate VNF Instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) public Response recreateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { @@ -440,12 +448,12 @@ public class ServiceInstances extends AbstractRestHandler { 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) + @Operation(description = "Delete provided VNF instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -462,8 +470,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Create VfModule on a specified version, serviceInstance and vnfInstance", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -480,8 +489,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Create VfModule on a specified version, serviceInstance and vnfInstance", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response replaceVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -500,8 +510,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Update VfModule on a specified version, serviceInstance, vnfInstance and vfModule", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -520,7 +531,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Perform VNF software update", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response inPlaceSoftwareUpdate(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -537,7 +549,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Delete provided VfModule instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -556,7 +569,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Deactivate and Cloud Delete VfModule instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deactivateAndCloudDeleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -576,7 +590,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "VF Auto Scale Out", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response scaleOutVfModule(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -589,13 +604,13 @@ public class ServiceInstances extends AbstractRestHandler { 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) + @Operation(description = "Create VolumeGroup on a specified version, serviceInstance, vnfInstance", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -612,8 +627,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Update VolumeGroup on a specified version, serviceInstance, vnfInstance and volumeGroup", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -632,7 +648,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Delete provided VolumeGroup instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @@ -651,8 +668,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Create NetworkInstance on a specified version and serviceInstance ", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) @@ -668,8 +686,9 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Update VolumeGroup on a specified version, serviceInstance, networkInstance", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -687,7 +706,8 @@ public class ServiceInstances extends AbstractRestHandler { @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) + @Operation(description = "Delete provided Network instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @@ -705,7 +725,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][7]}/instanceGroups") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create instanceGroups", response = Response.class) + @Operation(description = "Create instanceGroups", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createInstanceGroups(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { @@ -718,7 +739,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete instanceGroup", response = Response.class) + @Operation(description = "Delete instanceGroup", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteInstanceGroups(@PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) @@ -734,7 +756,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/addMembers") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Add instanceGroup members", response = Response.class) + @Operation(description = "Add instanceGroup members", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response addInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) @@ -750,7 +773,8 @@ public class ServiceInstances extends AbstractRestHandler { @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/removeMembers") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Remove instanceGroup members", response = Response.class) + @Operation(description = "Remove instanceGroup members", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response removeInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) @@ -762,8 +786,36 @@ public class ServiceInstances extends AbstractRestHandler { requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } + /** + * This method is used for POST a request to the BPEL client (BPMN). + * + * Convert the requestJson to ServiceInstanceRequest(sir), create the msoRequest object, check whether this request + * is already being processed in requestdb for duplicate check. + * + * Based on the alacarte flag, sir and msoRequest will do the recipe lookup from the service and servicerecipe table + * of catalogdb, and get the OrchestrationURI. + * + * If the present request is not the duplicate request then this request will be saved in the requestdb. and will + * POST a request to the BPMN engine at the OrchestrationURI fetched. + * + * @param requestJSON Json fetched as body in the API call + * @param action Type of action to be performed + * @param instanceIdMap Map of instance ids of service/vnf/vf/configuration etc.. + * @param version Supported version of API + * @param requestId Unique id for the request + * @param requestUri + * @return response object + * @throws ApiException + */ public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { + return serviceInstances(requestJSON, action, instanceIdMap, version, requestId, requestUri, null); + + } + + public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, + String version, String requestId, String requestUri, HashMap<String, String> queryParams) + throws ApiException { String serviceInstanceId; Boolean aLaCarte = null; ServiceInstancesRequest sir; @@ -771,16 +823,28 @@ public class ServiceInstances extends AbstractRestHandler { sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); action = handleReplaceInstance(action, sir); + requestValidatorListenerRunner.runValidations(requestUri, instanceIdMap, sir, queryParams); + 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); + if ((action == Action.replaceInstance || action == Action.replaceInstanceRetainAssignments) + && (requestScope.equals(ModelType.vnf.toString()) || requestScope.equals(ModelType.vfModule.toString())) + && sir.getRequestDetails().getCloudConfiguration() == null) { + CloudConfiguration cloudConfiguration = + getCloudConfigurationOnReplace(requestScope, instanceIdMap, currentActiveReq); + sir.getRequestDetails().setCloudConfiguration(cloudConfiguration); + setCloudConfigurationCurrentActiveRequest(cloudConfiguration, currentActiveReq); + } requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + int requestVersion = Integer.parseInt(version.substring(1)); String instanceName = null; if (sir.getRequestDetails().getRequestInfo() != null) { @@ -798,19 +862,9 @@ public class ServiceInstances extends AbstractRestHandler { currentActiveReq.setNetworkType(networkType); } - InfraActiveRequests dup = null; - boolean inProgress = false; + requestHandlerUtils.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, + instanceName); - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } - - if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, - requestScope, dup); - } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); RequestReferences referencesResponse = new RequestReferences(); @@ -819,7 +873,7 @@ public class ServiceInstances extends AbstractRestHandler { serviceResponse.setRequestReferences(referencesResponse); RecipeLookupResult recipeLookupResult = - getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); + requestHandlerUtils.getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag); ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); @@ -864,6 +918,7 @@ public class ServiceInstances extends AbstractRestHandler { try { infraActiveRequestsClient.save(currentActiveReq); } catch (Exception e) { + logger.error("Exception occurred", e); ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); @@ -871,12 +926,15 @@ public class ServiceInstances extends AbstractRestHandler { ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); } - if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) { + if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance + && !(requestScope.equalsIgnoreCase(ModelType.vnf.name()) + && (action == Action.replaceInstance || action == Action.replaceInstanceRetainAssignments))) { aLaCarte = true; } else if (aLaCarte == null) { aLaCarte = false; } + RequestClientParameter requestClientParameter = null; try { requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) @@ -889,6 +947,7 @@ public class ServiceInstances extends AbstractRestHandler { .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri) .setInstanceGroupId(instanceGroupId).build(); } 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(); @@ -914,6 +973,21 @@ public class ServiceInstances extends AbstractRestHandler { return action; } + /** + * This method deletes the Instance Groups. + * + * This method will check whether the request is not duplicate in requestdb. if its not then will save as a new + * request. And will send a POST request to BEPL client to delete the Insatnce Groups. + * + * @param action + * @param instanceIdMap + * @param version + * @param requestId + * @param requestUri + * @param requestContext + * @return + * @throws ApiException + */ 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); @@ -940,18 +1014,7 @@ public class ServiceInstances extends AbstractRestHandler { throw validateException; } - InfraActiveRequests dup = - requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); - boolean inProgress = false; - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } - - if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, - dup); - } + requestHandlerUtils.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, null); ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -967,6 +1030,7 @@ public class ServiceInstances extends AbstractRestHandler { try { infraActiveRequestsClient.save(currentActiveReq); } catch (Exception e) { + logger.error("Exception occurred", e); ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); @@ -979,6 +1043,7 @@ public class ServiceInstances extends AbstractRestHandler { .setRequestAction(action.toString()).setApiVersion(apiVersion).setALaCarte(aLaCarte) .setRequestUri(requestUri).setInstanceGroupId(instanceGroupId).build(); + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); } @@ -989,582 +1054,11 @@ public class ServiceInstances extends AbstractRestHandler { .orElse(""); } - protected 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(); - - 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)) { - try { - 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(); - - - 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.network)) { - try { - 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(); - - - 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); - } - - 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; - } - - protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, - boolean alaCarteFlag) throws IOException { - // SERVICE REQUEST - // Construct the default service name - // TODO need to make this a configurable property - 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 IOException { - 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; - 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(); - } - } 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; - } - } - - 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) { - 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()); - } - - private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) { - - String defaultSource = requestHandlerUtils.getDefaultModel(sir); - - VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); - - if (vnfRecipe == null) { - return null; - } - - return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout()); - } - - - private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException { - - 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; Boolean aLaCarte = null; String apiVersion = version.substring(1); - boolean inProgress = false; ServiceInstancesRequest sir; sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); @@ -1574,30 +1068,20 @@ public class ServiceInstances extends AbstractRestHandler { 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, instanceName, requestScope, currentActiveReq); - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } - - if (instanceIdMap != null && dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, - requestScope, dup); - } + requestHandlerUtils.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, + instanceName); 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); @@ -1609,7 +1093,6 @@ public class ServiceInstances extends AbstractRestHandler { 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(); @@ -1669,4 +1152,35 @@ public class ServiceInstances extends AbstractRestHandler { requestScope); } + protected CloudConfiguration getCloudConfigurationOnReplace(String requestScope, + HashMap<String, String> instanceIdMap, InfraActiveRequests currentActiveReq) throws ApiException { + logger.debug("Replace request is missing cloudConfiguration, autofilling from create."); + CloudConfiguration cloudConfiguration = null; + if (requestScope.equals(ModelType.vfModule.toString())) { + cloudConfiguration = bpmnRequestBuilder.getCloudConfigurationVfModuleReplace( + instanceIdMap.get("vnfInstanceId"), instanceIdMap.get("vfModuleInstanceId")); + } else { + cloudConfiguration = bpmnRequestBuilder.mapCloudConfigurationVnf(instanceIdMap.get("vnfInstanceId")); + } + + if (cloudConfiguration == null) { + String errorMessage = "CloudConfiguration not found during autofill for replace request."; + logger.error(errorMessage); + updateStatus(currentActiveReq, Status.FAILED, errorMessage); + throw new CloudConfigurationNotFoundException( + "CloudConfiguration not found during autofill for replace request."); + } + return cloudConfiguration; + } + + protected void setCloudConfigurationCurrentActiveRequest(CloudConfiguration cloudConfiguration, + InfraActiveRequests currentActiveRequest) { + if (cloudConfiguration.getLcpCloudRegionId() != null) { + currentActiveRequest.setCloudRegion(cloudConfiguration.getLcpCloudRegionId()); + } + + if (cloudConfiguration.getTenantId() != null) { + currentActiveRequest.setTenantId(cloudConfiguration.getTenantId()); + } + } } 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/SoSubsystems.java index 13f1e52068..b76cd42bb3 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/SoSubsystems.java @@ -19,18 +19,19 @@ */ package org.onap.so.apihandlerinfra; -public enum MsoSubsystems { +public enum SoSubsystems implements 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"); + SDNC("SDNC Adapter"), + SOAPPCORCHESTRATOR("SO APPC Orchestrator"); + private String subsystem; - private MsoSubsystems(String subsystem) { + private SoSubsystems(String subsystem) { this.subsystem = subsystem; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java new file mode 100644 index 0000000000..88626f3168 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java @@ -0,0 +1,5 @@ +package org.onap.so.apihandlerinfra; + +public interface Subsystem { + +} 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 3c4c90cc37..edc287ce0a 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 @@ -36,7 +36,6 @@ import javax.ws.rs.core.UriBuilder; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.RequestClient; @@ -60,11 +59,16 @@ 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; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Path("onap/so/infra/tasks") -@Api(value = "onap/so/infra/tasks", description = "Queries of Manual Tasks") +@OpenAPIDefinition(info = @Info(title = "onap/so/infra/tasks", description = "Queries of Manual Tasks")) @Component public class TasksHandler { @@ -82,7 +86,8 @@ public class TasksHandler { @Path("/{version:[vV]1}") @GET - @ApiOperation(value = "Finds Manual Tasks", response = Response.class) + @Operation(description = "Finds Manual Tasks", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response queryFilters(@QueryParam("taskId") String taskId, @QueryParam("originalRequestId") String originalRequestId, @@ -198,7 +203,7 @@ public class TasksHandler { } else { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError) .build(); throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); 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 deleted file mode 100644 index 632f371af5..0000000000 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. 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 org.onap.so.security.MSOSpringFirewall; -import org.onap.so.security.WebSecurityConfig; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.web.firewall.StrictHttpFirewall; -import org.springframework.util.StringUtils; - -@EnableWebSecurity -@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(), ",")).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 index b57bb5d1d8..925d10179f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java @@ -59,11 +59,17 @@ 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; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Path("onap/so/infra/workflowSpecifications") -@Api(value = "onap/so/infra/workflowSpecifications", description = "Queries of Workflow Specifications") +@OpenAPIDefinition(info = @Info(title = "onap/so/infra/workflowSpecifications", + description = "Queries of Workflow Specifications")) @Component public class WorkflowSpecificationsHandler { @@ -79,7 +85,8 @@ public class WorkflowSpecificationsHandler { @Path("/{version:[vV]1}/workflows") @GET - @ApiOperation(value = "Finds Workflow Specifications", response = Response.class) + @Operation(description = "Finds Workflow Specifications", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response queryWorkflowSpecifications(@QueryParam("vnfModelVersionId") String vnfModelVersionId, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java new file mode 100644 index 0000000000..344e5438c9 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java @@ -0,0 +1,85 @@ +package org.onap.so.apihandlerinfra.infra.rest; + +import java.util.Optional; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class AAIDataRetrieval { + + private static final String VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID = "VF Module Not Found In Inventory, VnfId: "; + + private AAIResourcesClient aaiResourcesClient; + + private static final Logger logger = LoggerFactory.getLogger(AAIDataRetrieval.class); + + public ServiceInstance getServiceInstance(String serviceInstanceId) { + return this.getAaiResourcesClient() + .get(ServiceInstance.class, + AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) + .orElseGet(() -> { + logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); + return null; + }); + } + + + public VfModule getAAIVfModule(String vnfId, String vfModuleId) { + return this.getAaiResourcesClient() + .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) + .orElseGet(() -> { + logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); + return null; + }); + } + + public GenericVnf getGenericVnf(String vnfId) { + return this.getAaiResourcesClient() + .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) + .orElseGet(() -> { + logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); + return null; + }); + } + + public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { + AAIResultWrapper wrapper = + this.getAaiResourcesClient().get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + .relatedTo(AAIObjectType.VOLUME_GROUP, volumeGroupId)); + Optional<VolumeGroup> volume = wrapper.asBean(VolumeGroup.class); + if (volume.isPresent()) { + return volume.get(); + } else { + logger.debug("No VolumeGroup in A&AI found: {}", vnfId); + return null; + } + } + + public L3Network getNetwork(String networkId) { + return this.getAaiResourcesClient() + .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) + .orElseGet(() -> { + logger.debug("No Network found in A&AI NetworkId: {}", networkId); + return null; + }); + } + + protected AAIResourcesClient getAaiResourcesClient() { + if (aaiResourcesClient == null) { + aaiResourcesClient = new AAIResourcesClient(); + } + return aaiResourcesClient; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java index bb5b4edfe4..f37713d5b2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java @@ -33,10 +33,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.constants.Status; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -75,30 +72,42 @@ public class BpmnRequestBuilder { @Autowired private RequestsDbClient infraActiveRequestsClient; + @Autowired + private AAIDataRetrieval aaiDataRet; + private ObjectMapper mapper = new ObjectMapper(); - private AAIResourcesClient aaiResourcesClient; public ServiceInstancesRequest buildVFModuleDeleteRequest(String vnfId, String vfModuleId, ModelType modelType) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } - VfModule vfModule = getAAIVfModule(vnfId, vfModuleId); + VfModule vfModule = aaiDataRet.getAAIVfModule(vnfId, vfModuleId); if (vfModule == null) { throw new AAIEntityNotFound(VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " vfModuleId: " + vfModuleId); } return createServiceInstancesRequest(vnf, vfModule, modelType); } + public CloudConfiguration getCloudConfigurationVfModuleReplace(String vnfId, String vfModuleId) + throws AAIEntityNotFound { + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); + if (vnf == null) { + throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); + } + + return mapCloudConfiguration(vnf, vfModuleId); + } + public ServiceInstancesRequest buildVolumeGroupDeleteRequest(String vnfId, String volumeGroupId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } - VolumeGroup volumeGroup = getVolumeGroup(vnfId, volumeGroupId); + VolumeGroup volumeGroup = aaiDataRet.getVolumeGroup(vnfId, volumeGroupId); if (volumeGroup == null) { throw new AAIEntityNotFound( VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); @@ -107,7 +116,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildServiceDeleteRequest(String serviceInstanceId) throws AAIEntityNotFound { - ServiceInstance serviceInstance = getServiceInstance(serviceInstanceId); + ServiceInstance serviceInstance = aaiDataRet.getServiceInstance(serviceInstanceId); if (serviceInstance == null) { throw new AAIEntityNotFound( "ServiceInstance Not Found In Inventory, ServiceInstanceId: " + serviceInstanceId); @@ -116,7 +125,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildVnfDeleteRequest(String vnfId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } @@ -124,7 +133,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildNetworkDeleteRequest(String networkId) throws AAIEntityNotFound { - L3Network network = getNetwork(networkId); + L3Network network = aaiDataRet.getNetwork(networkId); if (network == null) { throw new AAIEntityNotFound("Network Not Found In Inventory, NetworkId: " + networkId); } @@ -175,7 +184,7 @@ public class BpmnRequestBuilder { } requestDetails.setModelInfo(mapVfModuleModelInformation(vfModule, modelType)); - requestDetails.setCloudConfiguration(mapCloudConfiguration(vnf, vfModule)); + requestDetails.setCloudConfiguration(mapCloudConfiguration(vnf, vfModule.getVfModuleId())); requestDetails.setRequestParameters(createRequestParameters()); return requestDetails; } @@ -265,7 +274,7 @@ public class BpmnRequestBuilder { return modelInfo; } - public CloudConfiguration mapCloudConfiguration(GenericVnf vnf, VfModule vfModule) { + public CloudConfiguration mapCloudConfiguration(GenericVnf vnf, String vfModuleId) { CloudConfiguration cloudConfig = new CloudConfiguration(); AAIResultWrapper wrapper = new AAIResultWrapper(vnf); Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships(); @@ -282,7 +291,7 @@ public class BpmnRequestBuilder { } if (tenantId == null || cloudOwner == null || lcpRegionId == null) { - Map<String, String[]> filters = createQueryRequest("vfModuleId", vfModule.getVfModuleId()); + Map<String, String[]> filters = createQueryRequest("vfModuleId", vfModuleId); Optional<ServiceInstancesRequest> request = findServiceInstanceRequest(filters); if (request.isPresent()) { if (request.get().getRequestDetails() != null @@ -371,6 +380,36 @@ public class BpmnRequestBuilder { return cloudConfig; } + public CloudConfiguration mapCloudConfigurationVnf(String vnfId) { + CloudConfiguration cloudConfig = new CloudConfiguration(); + String tenantId = null; + String cloudOwner = null; + String lcpRegionId = null; + + Map<String, String[]> filters = createQueryRequest("vnfId", vnfId); + Optional<ServiceInstancesRequest> request = findServiceInstanceRequest(filters); + if (request.isPresent()) { + if (request.get().getRequestDetails() != null + && request.get().getRequestDetails().getCloudConfiguration() != null) { + if (request.get().getRequestDetails().getCloudConfiguration().getTenantId() != null) { + tenantId = request.get().getRequestDetails().getCloudConfiguration().getTenantId(); + } + if (request.get().getRequestDetails().getCloudConfiguration().getCloudOwner() != null) { + cloudOwner = request.get().getRequestDetails().getCloudConfiguration().getCloudOwner(); + } + if (request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId() != null) { + lcpRegionId = request.get().getRequestDetails().getCloudConfiguration().getLcpCloudRegionId(); + } + } + } else { + throw new CloudConfigurationNotFoundException(CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND); + } + cloudConfig.setTenantId(tenantId); + cloudConfig.setCloudOwner(cloudOwner); + cloudConfig.setLcpCloudRegionId(lcpRegionId); + return cloudConfig; + } + public Optional<ServiceInstancesRequest> findServiceInstanceRequest(Map<String, String[]> filters) { List<InfraActiveRequests> completeRequests = infraActiveRequestsClient.getRequest(filters); InfraActiveRequests foundRequest = completeRequests.get(0); @@ -407,72 +446,5 @@ public class BpmnRequestBuilder { return requestParams; } - public VfModule getAAIVfModule(String vnfId, String vfModuleId) { - return this.getAaiResourcesClient() - .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) - .orElseGet(() -> { - logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); - return null; - }); - } - - public GenericVnf getGenericVnf(String vnfId) { - return this.getAaiResourcesClient() - .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) - .orElseGet(() -> { - logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); - return null; - }); - } - - public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); - AAIResultWrapper wrapper = new AAIResultWrapper(vnf); - List<AAIResourceUri> listVserverWrapper; - Optional<AAIResourceUri> volumeGroupURI; - if (wrapper.getRelationships().isPresent()) { - listVserverWrapper = wrapper.getRelationships().get().getRelatedUris(AAIObjectType.VOLUME_GROUP); - volumeGroupURI = listVserverWrapper.stream() - .filter(resourceURI -> resourceURI.getURIKeys().get("volume-group-id").equals(volumeGroupId)) - .findFirst(); - } else { - throw new AAIEntityNotFound( - VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); - } - return this.getAaiResourcesClient().get(VolumeGroup.class, volumeGroupURI.get()).orElseGet(() -> { - logger.debug("No VolumeGroup in A&AI found: {}", vnfId); - return null; - }); - } - - public ServiceInstance getServiceInstance(String serviceInstanceId) { - return this.getAaiResourcesClient() - .get(ServiceInstance.class, - AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) - .orElseGet(() -> { - logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); - return null; - }); - } - - public L3Network getNetwork(String networkId) { - return this.getAaiResourcesClient() - .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) - .orElseGet(() -> { - logger.debug("No Network found in A&AI NetworkId: {}", networkId); - return null; - }); - } - - public AAIResourcesClient getAaiResourcesClient() { - if (aaiResourcesClient == null) { - aaiResourcesClient = new AAIResourcesClient(); - } - return aaiResourcesClient; - } - - public void setAaiResourcesClient(AAIResourcesClient aaiResourcesClient) { - this.aaiResourcesClient = aaiResourcesClient; - } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java index ec3df21fdb..483ac47235 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java @@ -44,7 +44,11 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/serviceInstantiation") @@ -61,7 +65,8 @@ public class Network { @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete provided Network instance", response = Response.class) + @Operation(description = "Delete provided Network instance", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deleteNetworkInstance(@PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java index 07e8092449..135667d3e4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java @@ -44,7 +44,11 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/serviceInstantiation") @@ -61,7 +65,8 @@ public class ServiceInstance { @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete a Service instance", response = ServiceInstancesResponse.class) + @Operation(description = "Delete a Service instance", responses = @ApiResponse(content = @Content( + array = @ArraySchema(schema = @Schema(implementation = ServiceInstancesResponse.class))))) @Transactional public Response deleteServiceInstance(@PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java index 1b9eb1f802..4a86d944cf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java @@ -45,7 +45,11 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/serviceInstantiation") @@ -62,7 +66,8 @@ public class VfModules { @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete a VfModule instance", response = ServiceInstancesResponse.class) + @Operation(description = "Delete a VfModule instance", responses = @ApiResponse(content = @Content( + array = @ArraySchema(schema = @Schema(implementation = ServiceInstancesResponse.class))))) @Transactional public Response deleteVfModuleInstance(@PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java index a8ccdeecac..edb09083d4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java @@ -43,7 +43,11 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/serviceInstantiation") @@ -60,7 +64,8 @@ public class Vnf { @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete a Vnf instance", response = ServiceInstancesResponse.class) + @Operation(description = "Delete a Vnf instance", responses = @ApiResponse(content = @Content( + array = @ArraySchema(schema = @Schema(implementation = ServiceInstancesResponse.class))))) @Transactional public Response deleteVnfInstance(@PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java index d3e394d6d8..3154c86046 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java @@ -46,7 +46,11 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component("VolumesV8") @Path("/onap/so/infra/serviceInstantiation") @@ -66,7 +70,8 @@ public class Volumes { @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete a VfModule instance", response = ServiceInstancesResponse.class) + @Operation(description = "Delete a VfModule instance", responses = @ApiResponse(content = @Content( + array = @ArraySchema(schema = @Schema(implementation = ServiceInstancesResponse.class))))) @Transactional public Response deleteVfModuleInstance(@PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java index 2153d9a628..e7753b2134 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java @@ -20,7 +20,9 @@ package org.onap.so.apihandlerinfra.infra.rest.exception; -public class AAIEntityNotFound extends Exception { +import org.onap.so.apihandlerinfra.exceptions.ApiException; + +public class AAIEntityNotFound extends ApiException { public AAIEntityNotFound(String errorMessage) { super(errorMessage); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java index e11732ddc4..20e27a5265 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java @@ -111,7 +111,7 @@ public abstract class AbstractRestHandler { String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { - if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance + if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))) { dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope); } @@ -175,7 +175,7 @@ public abstract class AbstractRestHandler { selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); } catch (Exception e) { selfLinkUrl = Optional.empty(); // ignore - logger.error(e.getMessage()); + logger.error("Exception in buildSelfLinkUrl", e); } return selfLinkUrl; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java index 7b095fc9d0..a6d2fa2e1b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java @@ -51,7 +51,6 @@ public class NetworkRestHandler extends AbstractRestHandler { Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); InfraActiveRequests deleteRequest = new InfraActiveRequests(); deleteRequest.setRequestAction(Action.deleteInstance.toString()); - deleteRequest.setAction(Action.deleteInstance.toString()); deleteRequest.setStartTime(startTimeStamp); deleteRequest.setServiceInstanceId(serviceInstanceId); deleteRequest.setNetworkId(networkId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java index afadf36157..36e7b7ced6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java @@ -54,7 +54,6 @@ public class ServiceInstanceRestHandler extends AbstractRestHandler { Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); InfraActiveRequests deleteRequest = new InfraActiveRequests(); deleteRequest.setRequestAction(Action.deleteInstance.toString()); - deleteRequest.setAction(Action.deleteInstance.toString()); deleteRequest.setStartTime(startTimeStamp); deleteRequest.setServiceInstanceId(serviceInstanceId); deleteRequest.setRequestId(requestId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java index 0762803488..380649a3ca 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java @@ -51,7 +51,6 @@ public class VFModuleRestHandler extends AbstractRestHandler { Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); InfraActiveRequests deleteRequest = new InfraActiveRequests(); deleteRequest.setRequestAction(Action.deleteInstance.toString()); - deleteRequest.setAction(Action.deleteInstance.toString()); deleteRequest.setStartTime(startTimeStamp); deleteRequest.setServiceInstanceId(serviceInstanceId); deleteRequest.setVnfId(vnfId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java index e157d926f3..c11ae56b0d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java @@ -3,6 +3,7 @@ * ONAP - SO * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 IBM. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +27,6 @@ import java.util.HashMap; import org.onap.so.apihandler.common.RequestClientParameter; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Constants; -import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException; import org.onap.so.constants.Status; import org.onap.so.db.catalog.beans.Recipe; import org.onap.so.db.catalog.beans.VnfRecipe; @@ -51,7 +51,6 @@ public class VnfRestHandler extends AbstractRestHandler { Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); InfraActiveRequests deleteRequest = new InfraActiveRequests(); deleteRequest.setRequestAction(Action.deleteInstance.toString()); - deleteRequest.setAction(Action.deleteInstance.toString()); deleteRequest.setStartTime(startTimeStamp); deleteRequest.setServiceInstanceId(serviceInstanceId); deleteRequest.setVnfId(vnfId); @@ -100,8 +99,7 @@ public class VnfRestHandler extends AbstractRestHandler { checkDuplicateRequest(instanceIdMap, ModelType.vnf, instanceName, requestId); } - public Recipe findVnfModuleRecipe(String modelCustomizationId, String modelType, String action) - throws NoRecipeException { + public Recipe findVnfModuleRecipe(String modelCustomizationId, String modelType, String action) { VnfRecipe recipe = new VnfRecipe(); recipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); return recipe; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java index 48a8aa2cd8..15aa71f936 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java @@ -48,7 +48,6 @@ public class VolumeRestHandler extends AbstractRestHandler { Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); InfraActiveRequests deleteRequest = new InfraActiveRequests(); deleteRequest.setRequestAction(Action.deleteInstance.toString()); - deleteRequest.setAction(Action.deleteInstance.toString()); deleteRequest.setStartTime(startTimeStamp); deleteRequest.setServiceInstanceId(serviceInstanceId); deleteRequest.setVnfId(vnfId); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java new file mode 100644 index 0000000000..4aa60152dd --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 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.infra.rest.validators; + +import java.util.Map; +import java.util.Optional; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; + +public interface RequestValidator { + + + /** + * Should this validator run for given request + * + * @return + */ + public boolean shouldRunFor(String uri, ServiceInstancesRequest request); + + + public Optional<String> validate(Map<String, String> instanceIdMap, ServiceInstancesRequest request, + Map<String, String> queryParams); +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java new file mode 100644 index 0000000000..d689c6b7a5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 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.infra.rest.validators; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.javatuples.Pair; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.listener.ListenerRunner; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class RequestValidatorListenerRunner extends ListenerRunner { + + private static Logger logger = LoggerFactory.getLogger(RequestValidatorListenerRunner.class); + + protected List<RequestValidator> requestValidators; + + @PostConstruct + protected void init() { + requestValidators = new ArrayList<>( + Optional.ofNullable(context.getBeansOfType(RequestValidator.class)).orElse(new HashMap<>()).values()); + } + + public boolean runValidations(String requestURI, Map<String, String> instanceIdMap, ServiceInstancesRequest request, + Map<String, String> queryParams) throws ApiException { + logger.info("Running local validations"); + List<Pair<String, Optional<String>>> results = + runValidations(requestValidators, instanceIdMap, request, queryParams, requestURI); + if (!results.isEmpty()) { + throw new ValidateException("Failed Validations:\n" + + results.stream().map(item -> String.format("%s: %s", item.getValue0(), item.getValue1().get())) + .collect(Collectors.joining("\n")), + 400); + } + + return true; + } + + protected List<Pair<String, Optional<String>>> runValidations(List<? extends RequestValidator> validators, + Map<String, String> instanceIdMap, ServiceInstancesRequest request, Map<String, String> queryParams, + String requestURI) { + + List<? extends RequestValidator> filtered = + filterListeners(validators, (item -> item.shouldRunFor(requestURI, request))); + + List<Pair<String, Optional<String>>> results = new ArrayList<>(); + filtered.forEach(item -> results + .add(new Pair<>(item.getClass().getName(), item.validate(instanceIdMap, request, queryParams)))); + + return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList()); + } +} 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 d3fb7986ce..877376cc79 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 @@ -61,12 +61,18 @@ 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; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/cloudResources") -@Api(value = "/onap/so/infra/cloudResources", description = "API Requests for cloud resources - Tenant Isolation") +@OpenAPIDefinition(info = @Info(title = "/onap/so/infra/cloudResources", + description = "API Requests for cloud resources - Tenant Isolation")) public class CloudOrchestration { private static Logger logger = LoggerFactory.getLogger(CloudOrchestration.class); @@ -85,7 +91,8 @@ public class CloudOrchestration { @Path("/{version:[vV][1]}/operationalEnvironments") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create an Operational Environment", response = Response.class) + @Operation(description = "Create an Operational Environment", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response createOperationEnvironment(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { @@ -97,7 +104,8 @@ public class CloudOrchestration { @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/activate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Activate an Operational Environment", response = Response.class) + @Operation(description = "Activate an Operational Environment", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response activateOperationEnvironment(String request, @PathParam("version") String version, @PathParam("operationalEnvironmentId") String operationalEnvironmentId, @@ -112,7 +120,8 @@ public class CloudOrchestration { @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/deactivate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Deactivate an Operational Environment", response = Response.class) + @Operation(description = "Deactivate an Operational Environment", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response deactivateOperationEnvironment(String request, @PathParam("version") String version, @PathParam("operationalEnvironmentId") String operationalEnvironmentId, 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 e9cd303c0b..43f957174c 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 @@ -62,13 +62,18 @@ 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; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("onap/so/infra/cloudResourcesRequests") -@Api(value = "onap/so/infra/cloudResourcesRequests", - description = "API GET Requests for cloud resources - Tenant Isolation") +@OpenAPIDefinition(info = @Info(title = "onap/so/infra/cloudResourcesRequests", + description = "API GET Requests for cloud resources - Tenant Isolation")) public class CloudResourcesOrchestration { private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class); @@ -83,7 +88,7 @@ public class CloudResourcesOrchestration { @Path("/{version: [vV][1]}/{requestId}/unlock") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Unlock CloudOrchestration requests for a specified requestId") + @Operation(description = "Unlock CloudOrchestration requests for a specified requestId") @Transactional public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException { @@ -129,8 +134,9 @@ public class CloudResourcesOrchestration { } if (infraActiveRequest == null) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, - ErrorCode.BusinessProcesssError).build(); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcessError) + .build(); ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) @@ -167,8 +173,9 @@ public class CloudResourcesOrchestration { @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) + @Operation(description = "Get status of an Operational Environment based on filter criteria", + responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version) throws ApiException { @@ -197,7 +204,7 @@ public class CloudResourcesOrchestration { if (requestDB == null) { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, - ErrorCode.BusinessProcesssError).build(); + ErrorCode.BusinessProcessError).build(); ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) @@ -221,7 +228,7 @@ public class CloudResourcesOrchestration { orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams); } catch (ValidationException ex) { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); ValidateException validateException = new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, 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 216588432b..2f922220c9 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 @@ -55,12 +55,18 @@ 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; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; @Component @Path("/onap/so/infra/modelDistributions") -@Api(value = "/onap/so/infra/modelDistributions", description = "API Requests for Model Distributions") +@OpenAPIDefinition( + info = @Info(title = "/onap/so/infra/modelDistributions", description = "API Requests for Model Distributions")) public class ModelDistributionRequest { private static Logger logger = LoggerFactory.getLogger(ModelDistributionRequest.class); @@ -71,7 +77,8 @@ public class ModelDistributionRequest { @Path("/{version:[vV][1]}/distributions/{distributionId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update model distribution status", response = Response.class) + @Operation(description = "Update model distribution status", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version, @PathParam("distributionId") String distributionId) throws ApiException { @@ -137,10 +144,8 @@ public class ModelDistributionRequest { se.setMessageId(messageId); se.setText(text); if (variables != null) { - if (variables != null) { - for (String variable : variables) { - se.getVariables().add(variable); - } + for (String variable : variables) { + se.getVariables().add(variable); } } re.setServiceException(se); 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 efdc52b837..b1eb71ea04 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 @@ -92,6 +92,7 @@ public class TenantIsolationRequest { requestJSON = mapper.writeValueAsString(request.getRequestDetails()); } catch (JsonProcessingException e) { + logger.error("Exception in JSON processing", e); throw new ValidationException("Parse ServiceInstanceRequest to JSON string", true); } @@ -267,7 +268,6 @@ public class TenantIsolationRequest { aq.setRequestId(requestId); aq.setRequestAction(action.name()); - aq.setAction(action.name()); Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); @@ -325,6 +325,7 @@ public class TenantIsolationRequest { orchestrationFilterParams.put(queryParam, value); } } catch (Exception e) { + logger.error("Exception in getOrchestrationFilters", e); throw new ValidationException(e.getMessage(), true); } } 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 340d143b42..e9ce0bf99a 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 @@ -72,7 +72,7 @@ public class DmaapOperationalEnvClient { public void dmaapPublishOperationalEnvRequest(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType, String tenantContext, String workloadContext, String action) - throws ApiException, IOException, InterruptedException { + throws ApiException { String request = this.buildRequest(operationalEnvironmentId, operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext, action); 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 b5ba9281a6..65d3109445 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 @@ -38,7 +38,7 @@ import org.onap.so.client.HttpClientFactory; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.utils.CryptoUtils; -import org.onap.so.utils.TargetEntity; +import org.onap.logging.filter.base.ONAPComponents; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -50,12 +50,19 @@ 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 final 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 static final String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!"; + private static final String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC."; private final HttpClientFactory httpClientFactory = new HttpClientFactory(); + private static final String STATUS_CODE = "statusCode"; + private static final String MESSAGE = "message"; + private static final String MESSAGE_ID = "messageId"; + private static final String REQUEST_ERROR = "requestError"; + private static final String SERVICE_EXCEPTION = "serviceException"; + private static final String POLICY_EXCEPTION = "policyException"; + @Value("${mso.sdc.endpoint}") private String sdcEndpoint; @Value("${mso.sdc.activate.userid}") @@ -87,19 +94,18 @@ public class SDCClientHelper { if (basicAuthCred == null || "".equals(basicAuthCred)) { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); - ValidateException validateException = new ValidateException.Builder( + + throw 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 httpClient = httpClientFactory.newJsonClient(url, ONAPComponents.SDC); httpClient.addBasicAuthHeader(sdcClientAuth, msoKey); httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId); httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString()); @@ -114,12 +120,12 @@ public class SDCClientHelper { sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode); } catch (Exception ex) { - logger.debug("calling SDC Exception message: {}", ex.getMessage()); + logger.debug("calling SDC Exception message:", ex); 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); + sdcResponseJsonObj.put(STATUS_CODE, String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + sdcResponseJsonObj.put(MESSAGE_ID, ""); + sdcResponseJsonObj.put(MESSAGE, errorMessage); } return sdcResponseJsonObj; @@ -137,13 +143,11 @@ public class SDCClientHelper { return client.post(jsonPayload); } catch (Exception ex) { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .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; + throw new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); } } @@ -154,7 +158,7 @@ public class SDCClientHelper { * @param statusCode - int * @return enhancedAsdcResponseJsonObj - JSONObject object */ - public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException { + public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) { JSONObject enhancedAsdcResponseJsonObj = new JSONObject(); @@ -163,31 +167,31 @@ public class SDCClientHelper { 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"); + enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode)); + enhancedAsdcResponseJsonObj.put(MESSAGE_ID, ""); + 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.has(REQUEST_ERROR)) { + JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject(REQUEST_ERROR); + if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(SERVICE_EXCEPTION)) { + message = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString("text"); + messageId = requestErrorObj.getJSONObject(SERVICE_EXCEPTION).getString(MESSAGE_ID); } - if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException")) { - message = requestErrorObj.getJSONObject("policyException").getString("text"); - messageId = requestErrorObj.getJSONObject("policyException").getString("messageId"); + if (sdcResponseJsonObj.getJSONObject(REQUEST_ERROR).has(POLICY_EXCEPTION)) { + message = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString("text"); + messageId = requestErrorObj.getJSONObject(POLICY_EXCEPTION).getString(MESSAGE_ID); } - enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); - enhancedAsdcResponseJsonObj.put("messageId", messageId); - enhancedAsdcResponseJsonObj.put("message", message); + enhancedAsdcResponseJsonObj.put(STATUS_CODE, Integer.toString(statusCode)); + enhancedAsdcResponseJsonObj.put(MESSAGE_ID, messageId); + enhancedAsdcResponseJsonObj.put(MESSAGE, message); } else { // unexpected format - enhancedAsdcResponseJsonObj.put("statusCode", + enhancedAsdcResponseJsonObj.put(STATUS_CODE, String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); - enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR); - enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT); + enhancedAsdcResponseJsonObj.put(MESSAGE_ID, MESSAGE_UNDEFINED_ERROR); + enhancedAsdcResponseJsonObj.put(MESSAGE, MESSAGE_UNEXPECTED_FORMAT); } } return enhancedAsdcResponseJsonObj; @@ -214,7 +218,7 @@ public class SDCClientHelper { * @return String json * @throws JSONException */ - public String buildJsonWorkloadContext(String workloadContext) throws JSONException { + public String buildJsonWorkloadContext(String workloadContext) { return new JSONObject().put("workloadContext", workloadContext).toString(); } 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 3957f86bab..0005d26016 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 @@ -109,7 +109,7 @@ public class ActivateVnfOperationalEnvironment { logger.debug(" aai workloadContext: {}", workloadContext); if (!vidWorkloadContext.equals(workloadContext)) { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); throw new ValidateException.Builder( " The vid workloadContext did not match from aai record. " + " vid workloadContext:" @@ -119,7 +119,7 @@ public class ActivateVnfOperationalEnvironment { } if (ecompOperationalEnvironmentId == null) { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); throw new ValidateException.Builder( " The ECOMP OE was not in aai record; the value of relationship.relationship-data key: " @@ -183,7 +183,7 @@ public class ActivateVnfOperationalEnvironment { } else { ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); String dbErrorMessage = " Failure calling SDC: statusCode: " + statusCode + "; messageId: " + jsonResponse.get("messageId") + "; message: " + jsonResponse.get("message"); 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 3005abaf9b..624a7f6945 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 @@ -61,16 +61,14 @@ public class ActivateVnfStatusOperationalEnvironment { 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!"; + private static final int RETRY_COUNT_ZERO = 0; + private static final String ERROR_REASON_ABORTED = "ABORTED"; + private static final String RECOVERY_ACTION_RETRY = "RETRY"; + private static final String RECOVERY_ACTION_ABORT = "ABORT"; + private static final String RECOVERY_ACTION_SKIP = "SKIP"; + private static final String DISTRIBUTION_STATUS_OK = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); + private static final String DISTRIBUTION_STATUS_ERROR = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); + private static final String DISTRIBUTION_STATUS_SENT = "SENT"; @Autowired private ActivateVnfDBHelper dbHelper; @@ -130,6 +128,7 @@ public class ActivateVnfStatusOperationalEnvironment { } } catch (Exception e) { + logger.error("Exception in execute", e); requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId()); } @@ -251,7 +250,7 @@ public class ActivateVnfStatusOperationalEnvironment { 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) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); ValidateException validateException = new ValidateException.Builder(dbErrorMessage, HttpStatus.SC_BAD_REQUEST, @@ -305,7 +304,7 @@ public class ActivateVnfStatusOperationalEnvironment { 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) + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError) .build(); ValidateException validateException = new ValidateException.Builder(this.errorMessage, HttpStatus.SC_BAD_REQUEST, 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 2207c52048..a89032f50c 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 @@ -48,11 +48,6 @@ public class CloudConfigurationValidation implements ValidationRule { || 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)) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java index 01e3de99ec..c05ef98fbb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -35,13 +35,13 @@ public class CustomWorkflowValidation implements ValidationRule { CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); if (cloudConfiguration == null) { - throw new ValidationException("cloudConfiguration"); + // throw new ValidationException("cloudConfiguration"); } else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner()))) { - throw new ValidationException("cloudOwner"); + // throw new ValidationException("cloudOwner"); } else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId()))) { - throw new ValidationException("lcpCloudRegionId"); + // throw new ValidationException("lcpCloudRegionId"); } else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId()))) { - throw new ValidationException("tenantId"); + // throw new ValidationException("tenantId"); } if (requestParameters == null) { throw new ValidationException("requestParameters"); 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 71405b0f63..20be2b5a8b 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 @@ -43,7 +43,8 @@ public class PlatformLOBValidation implements ValidationRule { platform = info.getSir().getRequestDetails().getPlatform(); lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness(); - if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) { + if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance + && !info.getReqParameters().getEnforceValidNfValues()) { if (reqVersion > 5 && platform == null) { throw new ValidationException("platform"); } 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 584269715a..cebbd6389c 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 @@ -41,10 +41,12 @@ public class ProjectOwningEntityValidation implements ValidationRule { 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) { + && !info.getReqParameters().getEnforceValidNfValues() && action == Action.createInstance + || action == Action.assignInstance) { if (reqVersion > 5 && owningEntity == null) { throw new ValidationException("owningEntity"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-aaf.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-aaf.yaml diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-basic.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-basic.yaml 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 deleted file mode 100644 index 276b438529..0000000000 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 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 - * - * 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.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()); - } -} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java index e6b5163f59..4dc281b3fc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java @@ -17,311 +17,39 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.onap.so.apihandlerinfra; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; -import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; -import org.junit.Before; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import javax.ws.rs.core.MediaType; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; -import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(MockitoJUnitRunner.class) -public class CamundaRequestHandlerTest { - - @Mock - private RestTemplate restTemplate; - @Mock - private Environment env; +public class CamundaRequestHandlerTest extends BaseTest { - @InjectMocks - @Spy + @Autowired private CamundaRequestHandler camundaRequestHandler; + @Value("${wiremock.server.port}") + private String wiremockPort; + @Rule public ExpectedException thrown = ExpectedException.none(); - private static final String REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; - private ResponseEntity<List<HistoricActivityInstanceEntity>> activityInstanceResponse = null; - private ResponseEntity<List<HistoricProcessInstanceEntity>> processInstanceResponse = null; - private List<HistoricActivityInstanceEntity> activityInstanceList = null; - private List<HistoricProcessInstanceEntity> processInstanceList = null; - - - - @Before - public void setup() throws IOException { - ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - activityInstanceList = mapper.readValue( - new String(Files.readAllBytes( - Paths.get("src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json"))), - new TypeReference<List<HistoricActivityInstanceEntity>>() {}); - processInstanceList = mapper.readValue( - new String(Files.readAllBytes( - Paths.get("src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json"))), - new TypeReference<List<HistoricProcessInstanceEntity>>() {}); - processInstanceResponse = - new ResponseEntity<List<HistoricProcessInstanceEntity>>(processInstanceList, HttpStatus.ACCEPTED); - activityInstanceResponse = - new ResponseEntity<List<HistoricActivityInstanceEntity>>(activityInstanceList, HttpStatus.ACCEPTED); - - doReturn("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_").when(env) - .getProperty("mso.camunda.rest.history.uri"); - doReturn("/sobpmnengine/history/activity-instance?processInstanceId=").when(env) - .getProperty("mso.camunda.rest.activity.uri"); - doReturn("auth").when(env).getRequiredProperty("mso.camundaAuth"); - doReturn("key").when(env).getRequiredProperty("mso.msoKey"); - doReturn("http://localhost:8089").when(env).getProperty("mso.camundaURL"); - } - - public HttpHeaders setHeaders() { - HttpHeaders headers = new HttpHeaders(); - List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); - acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); - headers.setAccept(acceptableMediaTypes); - headers.add(HttpHeaders.AUTHORIZATION, "auth"); - - return headers; - } - - @Test - public void getActivityNameTest() throws IOException { - String expectedActivityName = "Last task executed: BB to Execute"; - String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); - - assertEquals(expectedActivityName, actualActivityName); - } - - @Test - public void getActivityNameNullActivityNameTest() throws IOException { - String expectedActivityName = "Task name is null."; - HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity(); - List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); - activityInstanceList.add(activityInstance); - - String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); - - assertEquals(expectedActivityName, actualActivityName); - } - - @Test - public void getActivityNameNullListTest() throws IOException { - String expectedActivityName = "No results returned on activityInstance history lookup."; - List<HistoricActivityInstanceEntity> activityInstanceList = null; - String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); - - assertEquals(expectedActivityName, actualActivityName); - } - @Test - public void getActivityNameEmptyListTest() throws IOException { - String expectedActivityName = "No results returned on activityInstance history lookup."; - List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); - String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); - - assertEquals(expectedActivityName, actualActivityName); - } - - @Test - public void getTaskNameTest() throws IOException, ContactCamundaException { - doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); - doReturn(activityInstanceResponse).when(camundaRequestHandler) - .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID); - doReturn("Last task executed: BB to Execute").when(camundaRequestHandler).getActivityName(activityInstanceList); - String expectedTaskName = "Last task executed: BB to Execute"; - - String actualTaskName = camundaRequestHandler.getTaskName(REQUEST_ID); - - assertEquals(expectedTaskName, actualTaskName); - } - - @Test - public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException { - ResponseEntity<List<HistoricProcessInstanceEntity>> response = new ResponseEntity<>(null, HttpStatus.OK); - doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); - String expected = "No processInstances returned for requestId: " + REQUEST_ID; - - String actual = camundaRequestHandler.getTaskName(REQUEST_ID); - - assertEquals(expected, actual); - } - - @Test - public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException { - HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); - List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); - processInstanceList.add(processInstance); - ResponseEntity<List<HistoricProcessInstanceEntity>> response = - new ResponseEntity<>(processInstanceList, HttpStatus.OK); - doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); - String expected = "No processInstanceId returned for requestId: " + REQUEST_ID; - - String actual = camundaRequestHandler.getTaskName(REQUEST_ID); - - assertEquals(expected, actual); - } - - @Test - public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException { - doThrow(HttpClientErrorException.class).when(camundaRequestHandler) - .getCamundaProcessInstanceHistory(REQUEST_ID); - - thrown.expect(ContactCamundaException.class); - camundaRequestHandler.getTaskName(REQUEST_ID); - } - - @Test - public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException { - HttpHeaders headers = setHeaders(); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" - + "c4c6b647-a26e-11e9-b144-0242ac14000b"; - doReturn(activityInstanceResponse).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); - doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); - ResponseEntity<List<HistoricActivityInstanceEntity>> actualResponse = - camundaRequestHandler.getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID); - assertEquals(activityInstanceResponse, actualResponse); - } - - @Test - public void getCamundaActivityHistoryErrorTest() { - HttpHeaders headers = setHeaders(); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" - + "c4c6b647-a26e-11e9-b144-0242ac14000b"; - doThrow(new ResourceAccessException("IOException")).when(restTemplate).exchange(targetUrl, HttpMethod.GET, - requestEntity, new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); - doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); - - try { - camundaRequestHandler.getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID); - } catch (ContactCamundaException e) { - // Exception thrown after retries are completed - } - - verify(restTemplate, times(4)).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); - } - - @Test - public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException { - HttpHeaders headers = setHeaders(); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - String targetUrl = - "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; - doReturn(processInstanceResponse).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); - - ResponseEntity<List<HistoricProcessInstanceEntity>> actualResponse = - camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID); - assertEquals(processInstanceResponse, actualResponse); - } - - @Test - public void getCamundaProccesInstanceHistoryRetryTest() { - HttpHeaders headers = setHeaders(); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - String targetUrl = - "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; - doThrow(new ResourceAccessException("I/O error")).when(restTemplate).exchange(targetUrl, HttpMethod.GET, - requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); - - try { - camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID); - } catch (ResourceAccessException e) { - // Exception thrown after retries are completed - } - verify(restTemplate, times(4)).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - } - - @Test - public void getCamundaProccesInstanceHistoryNoRetryTest() { - HttpHeaders headers = setHeaders(); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - String targetUrl = - "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; - doThrow(HttpClientErrorException.class).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); - - try { - camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID); - } catch (HttpStatusCodeException e) { - // Exception thrown, no retries - } - verify(restTemplate, times(1)).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - } - - @Test - public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException { - HttpHeaders headers = setHeaders(); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - String targetUrl = - "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; - when(restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {})) - .thenThrow(new ResourceAccessException("I/O Exception")).thenReturn(processInstanceResponse); - doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); - - ResponseEntity<List<HistoricProcessInstanceEntity>> actualResponse = - camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID); - assertEquals(processInstanceResponse, actualResponse); - verify(restTemplate, times(2)).exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - } - - @Test - public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { - String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password - String key = "07a7159d3bf51a0e53be7a8f89699be7"; - - HttpHeaders headers = camundaRequestHandler.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=="; + public void timeoutTest() { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_6718de35-b9a5-4670-b19f-a0f4ac22bfaf")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK).withFixedDelay(40000))); - assertEquals(expectedBasicAuth, basicAuth); + thrown.expect(ResourceAccessException.class); + camundaRequestHandler.getCamundaProcessInstanceHistory("6718de35-b9a5-4670-b19f-a0f4ac22bfaf", false); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerUnitTest.java new file mode 100644 index 0000000000..261b64f2e6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerUnitTest.java @@ -0,0 +1,378 @@ +/*- + * ============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 org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +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.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class CamundaRequestHandlerUnitTest { + + @Mock + private RestTemplate restTemplate; + + @Mock + private RestTemplate restTemplateRetry; + + @Mock + private Environment env; + + @InjectMocks + @Spy + private CamundaRequestHandler camundaRequestHandler; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private ResponseEntity<List<HistoricActivityInstanceEntity>> activityInstanceResponse = null; + private ResponseEntity<List<HistoricProcessInstanceEntity>> processInstanceResponse = null; + private List<HistoricActivityInstanceEntity> activityInstanceList = null; + private List<HistoricProcessInstanceEntity> processInstanceList = null; + + + + @Before + public void setup() throws IOException { + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + activityInstanceList = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json"))), + new TypeReference<List<HistoricActivityInstanceEntity>>() {}); + processInstanceList = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json"))), + new TypeReference<List<HistoricProcessInstanceEntity>>() {}); + processInstanceResponse = + new ResponseEntity<List<HistoricProcessInstanceEntity>>(processInstanceList, HttpStatus.ACCEPTED); + activityInstanceResponse = + new ResponseEntity<List<HistoricActivityInstanceEntity>>(activityInstanceList, HttpStatus.ACCEPTED); + + doReturn("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_").when(env) + .getProperty("mso.camunda.rest.history.uri"); + doReturn("/sobpmnengine/history/activity-instance?processInstanceId=").when(env) + .getProperty("mso.camunda.rest.activity.uri"); + doReturn("auth").when(env).getRequiredProperty("mso.camundaAuth"); + doReturn("key").when(env).getRequiredProperty("mso.msoKey"); + doReturn("http://localhost:8089").when(env).getProperty("mso.camundaURL"); + + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setReadTimeout(30000); + factory.setConnectTimeout(30000); + restTemplate.setRequestFactory(factory); + doReturn(restTemplate).when(camundaRequestHandler).getRestTemplate(false); + + HttpComponentsClientHttpRequestFactory factoryRetry = new HttpComponentsClientHttpRequestFactory(); + factoryRetry.setReadTimeout(15000); + factoryRetry.setConnectTimeout(15000); + restTemplate.setRequestFactory(factoryRetry); + doReturn(restTemplateRetry).when(camundaRequestHandler).getRestTemplate(true); + } + + public HttpHeaders setHeaders() { + HttpHeaders headers = new HttpHeaders(); + List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + headers.add(HttpHeaders.AUTHORIZATION, "auth"); + + return headers; + } + + @Test + public void getActivityNameTest() throws IOException { + String expectedActivityName = "Last task executed: BB to Execute"; + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getActivityNameNullActivityNameTest() throws IOException { + String expectedActivityName = "Task name is null."; + HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity(); + List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); + activityInstanceList.add(activityInstance); + + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getActivityNameNullListTest() throws IOException { + String expectedActivityName = "No results returned on activityInstance history lookup."; + List<HistoricActivityInstanceEntity> activityInstanceList = null; + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getActivityNameEmptyListTest() throws IOException { + String expectedActivityName = "No results returned on activityInstance history lookup."; + List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getCamundActivityHistoryNullTest() throws IOException, ContactCamundaException { + HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); + processInstance.setId("c4c6b647-a26e-11e9-b144-0242ac14000b"); + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + processInstanceList.add(processInstance); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + doReturn(null).when(camundaRequestHandler).getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + + String actualTaskName = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actualTaskName); + } + + @Test + public void getCamundActivityHistoryErrorTest() throws IOException, ContactCamundaException { + HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); + processInstance.setId("c4c6b647-a26e-11e9-b144-0242ac14000b"); + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + processInstanceList.add(processInstance); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + doThrow(RestClientException.class).when(camundaRequestHandler) + .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + + String actualTaskName = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actualTaskName); + } + + @Test + public void getTaskName() throws IOException, ContactCamundaException { + doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID, + false); + doReturn(activityInstanceResponse).when(camundaRequestHandler) + .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + doReturn("Last task executed: BB to Execute").when(camundaRequestHandler).getActivityName(activityInstanceList); + String expectedTaskName = "Last task executed: BB to Execute"; + + String actualTaskName = camundaRequestHandler.getTaskName(REQUEST_ID); + + assertEquals(expectedTaskName, actualTaskName); + } + + @Test + public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException { + ResponseEntity<List<HistoricProcessInstanceEntity>> response = new ResponseEntity<>(null, HttpStatus.OK); + + String actual = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actual); + } + + @Test + public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException { + HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + processInstanceList.add(processInstance); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + + String actual = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actual); + } + + @Test + public void getTaskNameEmptyProcessInstanceListTest() throws IOException, ContactCamundaException { + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + + String actual = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actual); + } + + @Test + public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException { + doThrow(HttpClientErrorException.class).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID, + false); + + String result = camundaRequestHandler.getTaskName(REQUEST_ID); + assertNull(result); + } + + @Test + public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" + + "c4c6b647-a26e-11e9-b144-0242ac14000b"; + doReturn(activityInstanceResponse).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + ResponseEntity<List<HistoricActivityInstanceEntity>> actualResponse = + camundaRequestHandler.getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + assertEquals(activityInstanceResponse, actualResponse); + } + + @Test + public void getCamundaActivityHistoryErrorTest() { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" + + "c4c6b647-a26e-11e9-b144-0242ac14000b"; + doThrow(new ResourceAccessException("IOException")).when(restTemplate).exchange(targetUrl, HttpMethod.GET, + requestEntity, new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + thrown.expect(ResourceAccessException.class); + camundaRequestHandler.getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + + verify(restTemplate, times(1)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + } + + @Test + public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + doReturn(processInstanceResponse).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + ResponseEntity<List<HistoricProcessInstanceEntity>> actualResponse = + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, false); + assertEquals(processInstanceResponse, actualResponse); + } + + @Test + public void getCamundaProccesInstanceHistoryRetryTest() { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + doThrow(new ResourceAccessException("I/O error")).when(restTemplateRetry).exchange(targetUrl, HttpMethod.GET, + requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + thrown.expect(ResourceAccessException.class); + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, true); + + verify(restTemplateRetry, times(2)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } + + @Test + public void getCamundaProccesInstanceHistoryNoRetryTest() { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + doThrow(HttpClientErrorException.class).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + thrown.expect(HttpStatusCodeException.class); + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, false); + + verify(restTemplate, times(1)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } + + @Test + public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + when(restTemplateRetry.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {})) + .thenThrow(new ResourceAccessException("I/O Exception")).thenReturn(processInstanceResponse); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + ResponseEntity<List<HistoricProcessInstanceEntity>> actualResponse = + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, true); + + assertEquals(processInstanceResponse, actualResponse); + verify(restTemplateRetry, times(2)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } + + @Test + public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + + HttpHeaders headers = camundaRequestHandler.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/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java index 7ddab572e3..979aa8fbb1 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 @@ -62,14 +62,13 @@ public class E2EServiceInstancesTest extends BaseTest { 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\"}")) + "{\"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,\"tenantId\":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,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"cloudRegion\":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"); 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 928b488f6a..0291cfd2ea 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 @@ -20,70 +20,67 @@ package org.onap.so.apihandlerinfra; -import static org.junit.Assert.assertArrayEquals; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; 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.junit.Assert.assertThat; 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; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.json.JSONException; -import org.junit.Rule; import org.junit.Test; -import org.mockito.InjectMocks; +import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; -import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.onap.so.apihandlerinfra.HealthCheckConfig.Endpoint; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.JsonProcessingException; +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {GenericStringConverter.class, HealthCheckConverter.class}, + initializers = {ConfigFileApplicationContextInitializer.class}) +@ActiveProfiles("test") +@EnableConfigurationProperties({HealthCheckConfig.class}) public class GlobalHealthcheckHandlerTest { - @Mock - RestTemplate restTemplate; + @MockBean + private RestTemplate restTemplate; - @Mock - ContainerRequestContext requestContext; + @MockBean + private ContainerRequestContext requestContext; - @InjectMocks - @Spy - GlobalHealthcheckHandler globalhealth; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule(); + @SpyBean + private GlobalHealthcheckHandler globalhealth; @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); + HealthCheckSubsystem result = globalhealth + .querySubsystemHealth(new Endpoint(SoSubsystems.BPMN, UriBuilder.fromPath("http://localhost").build())); + assertEquals(HealthCheckStatus.DOWN, result.getStatus()); } @Test public void testQuerySubsystemHealthNotNullResult() { ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); subSystemResponse.setStatus("UP"); @@ -92,20 +89,13 @@ public class GlobalHealthcheckHandlerTest { 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); + HealthCheckSubsystem result = globalhealth + .querySubsystemHealth(new Endpoint(SoSubsystems.ASDC, UriBuilder.fromPath("http://localhost").build())); + assertEquals(HealthCheckStatus.UP, result.getStatus()); } 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(); @@ -116,70 +106,41 @@ public class GlobalHealthcheckHandlerTest { 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())); + public void globalHealthcheckAllUPTest() throws JSONException, JsonProcessingException { - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + HealthCheckResponse expected = new HealthCheckResponse(); - 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())); + for (Subsystem system : SoSubsystems.values()) { + expected.getSubsystems().add(new HealthCheckSubsystem(system, + UriBuilder.fromUri("http://localhost").build(), HealthCheckStatus.UP)); + } + expected.setMessage("HttpStatus: 200"); + Response response = globalHealthcheck("UP"); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + HealthCheckResponse root; + root = (HealthCheckResponse) response.getEntity(); + assertThat(root, sameBeanAs(expected).ignoring("subsystems.uri").ignoring("subsystems.subsystem")); - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); } @Test public void globalHealthcheckAllDOWNTest() throws JSONException { + HealthCheckResponse expected = new HealthCheckResponse(); + + for (Subsystem system : SoSubsystems.values()) { + expected.getSubsystems().add(new HealthCheckSubsystem(system, + UriBuilder.fromUri("http://localhost").build(), HealthCheckStatus.DOWN)); + } + expected.setMessage("HttpStatus: 200"); 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())); + HealthCheckResponse root; + root = (HealthCheckResponse) response.getEntity(); + assertThat(root, sameBeanAs(expected).ignoring("subsystems.uri").ignoring("subsystems.subsystem")); } @Test @@ -189,40 +150,15 @@ public class GlobalHealthcheckHandlerTest { 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); + Endpoint endpoint = new Endpoint(SoSubsystems.BPMN, UriBuilder.fromUri("http://localhost").build()); + HealthCheckStatus result = globalhealth.processResponseFromSubsystem(r, endpoint); + assertEquals(HealthCheckStatus.UP, result); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java index 9fc9e4a51b..5c78af3601 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -29,9 +29,10 @@ 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.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import static org.onap.so.logger.MdcConstants.CLIENT_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; +import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -81,10 +82,10 @@ public class InstanceManagementTest extends BaseTest { // 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(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(ONAP_PARTNER_NAME, "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)); @@ -171,4 +172,32 @@ public class InstanceManagementTest extends BaseTest { ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + + @Test + public void executePNFCustomWorkflow() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingPNFWorkflow")) + .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=81526781-e55c-4cb7-adb3-97e09d9c76bf")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("workflow_pnf_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/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testpnfcId/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf"; + ResponseEntity<String> response = + sendRequest(inputStream("/ExecutePNFCustomWorkflow.json"), uri, HttpMethod.POST, headers); + + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java index ad0a878931..b8d1e56cf7 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 @@ -26,24 +26,13 @@ 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; -import static org.onap.so.logger.MdcConstants.INVOCATION_ID; -import static org.onap.so.logger.MdcConstants.PARTNERNAME; -import static org.onap.so.logger.MdcConstants.RESPONSECODE; -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 static org.onap.logging.filter.base.Constants.HttpHeaders.ECOMP_REQUEST_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; 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; import org.onap.so.apihandlerinfra.tasksbeans.RequestDetails; import org.onap.so.apihandlerinfra.tasksbeans.RequestInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference; @@ -59,7 +48,6 @@ 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 { @@ -89,7 +77,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); UriComponentsBuilder builder = @@ -108,34 +96,6 @@ public class ManualTasksTest extends BaseTest { // 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(); - 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)); - assertNotNull(mdc.get(RESPONSEDESC)); - 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 @@ -152,7 +112,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<String> entity = new HttpEntity<String>(invalidRequest, headers); UriComponentsBuilder builder = @@ -161,7 +121,6 @@ public class ManualTasksTest extends BaseTest { 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); @@ -189,7 +148,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); UriComponentsBuilder builder = @@ -198,7 +157,6 @@ public class ManualTasksTest extends BaseTest { 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); @@ -230,7 +188,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); UriComponentsBuilder builder = @@ -240,7 +198,6 @@ public class ManualTasksTest extends BaseTest { 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); 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 86bf8060a7..f1d5a5487f 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 @@ -278,10 +278,6 @@ public class MsoRequestTest extends BaseTest { 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}, 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 12f0ffcc11..aa6a3836c1 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 @@ -45,6 +45,7 @@ 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.apihandler.common.ErrorNumbers; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -64,7 +65,6 @@ 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; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -107,6 +107,18 @@ public class OrchestrationRequestsTest extends BaseTest { .withBody(new String(Files.readAllBytes(Paths.get( "src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json")))) .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get( + ("/requestProcessingData/search/findBySoRequestIdAndIsDataInternalOrderByGroupingIdDesc?SO_REQUEST_ID=00032ab7-1a18-42e5-965d-8ea592502018&IS_INTERNAL_DATA=false")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths.get( + "src/test/resources/OrchestrationRequest/getRequestProcessingDataArray.json")))) + .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get( + ("/requestProcessingData/search/findBySoRequestIdAndIsDataInternalOrderByGroupingIdDesc?SO_REQUEST_ID=00032ab7-3fb3-42e5-965d-8ea592502017&IS_INTERNAL_DATA=false")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths.get( + "src/test/resources/OrchestrationRequest/getRequestProcessingDataArray.json")))) + .withStatus(HttpStatus.SC_OK))); } @Test @@ -117,10 +129,21 @@ public class OrchestrationRequestsTest extends BaseTest { Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); testResponse.setRequest(request); + testResponse.getRequest().setRequestProcessingData(new ArrayList<RequestProcessingData>()); + RequestProcessingData e = new RequestProcessingData(); + e.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); + e.setTag("pincFabricConfigRequest"); + List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); + HashMap<String, String> data1 = new HashMap<String, String>(); + data1.put("requestAction", "assign"); + data.add(data1); + e.setDataPairs(data); + testResponse.getRequest().getRequestProcessingData().add(e); String testRequestId = request.getRequestId(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "1e45215d-b7b3-4c5a-9316-65bdddaf649f"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); UriComponentsBuilder builder = UriComponentsBuilder @@ -136,7 +159,41 @@ public class OrchestrationRequestsTest extends BaseTest { 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)); - assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("1e45215d-b7b3-4c5a-9316-65bdddaf649f", response.getHeaders().get("X-TransactionID").get(0)); + assertNotNull(response.getBody().getRequest().getFinishTime()); + } + + @Test + public void getOrchestrationRequestSimpleTest() throws Exception { + setupTestGetOrchestrationRequest(); + // TEST VALID REQUEST + GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); + + Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); + request.setRequestProcessingData(null); + testResponse.setRequest(request); + + String testRequestId = request.getRequestId(); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "e5e3c007-9fe9-4a20-8691-bdd20e14504d"); + HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)) + .queryParam("format", "simple"); + + 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")); + 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)); + assertEquals("e5e3c007-9fe9-4a20-8691-bdd20e14504d", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } @@ -148,6 +205,16 @@ public class OrchestrationRequestsTest extends BaseTest { Request request = ORCHESTRATION_LIST.getRequestList().get(8).getRequest(); testResponse.setRequest(request); + testResponse.getRequest().setRequestProcessingData(new ArrayList<RequestProcessingData>()); + RequestProcessingData e = new RequestProcessingData(); + e.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); + e.setTag("pincFabricConfigRequest"); + List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); + HashMap<String, String> data1 = new HashMap<String, String>(); + data1.put("requestAction", "assign"); + data.add(data1); + e.setDataPairs(data); + testResponse.getRequest().getRequestProcessingData().add(e); String testRequestId = request.getRequestId(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); @@ -184,10 +251,21 @@ public class OrchestrationRequestsTest extends BaseTest { request.setCloudRequestData(cloudRequestData); testResponse.setRequest(request); String testRequestId = request.getRequestId(); + testResponse.getRequest().setRequestProcessingData(new ArrayList<RequestProcessingData>()); + RequestProcessingData e = new RequestProcessingData(); + e.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); + e.setTag("pincFabricConfigRequest"); + List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); + HashMap<String, String> data1 = new HashMap<String, String>(); + data1.put("requestAction", "assign"); + data.add(data1); + e.setDataPairs(data); + testResponse.getRequest().getRequestProcessingData().add(e); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "0321e28d-3dde-4b31-9b28-1e0f07231b93"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( @@ -204,7 +282,7 @@ public class OrchestrationRequestsTest extends BaseTest { 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)); - assertEquals("00032ab7-3fb3-42e5-965d-8ea592502017", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("0321e28d-3dde-4b31-9b28-1e0f07231b93", response.getHeaders().get("X-TransactionID").get(0)); } @Test @@ -281,7 +359,6 @@ public class OrchestrationRequestsTest extends BaseTest { public void testUnlockOrchestrationRequest() throws Exception { 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"))); HttpHeaders headers = new HttpHeaders(); @@ -317,7 +394,6 @@ public class OrchestrationRequestsTest extends BaseTest { public void testUnlockOrchestrationRequest_invalid_Json() throws Exception { 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"))); HttpHeaders headers = new HttpHeaders(); @@ -335,7 +411,7 @@ public class OrchestrationRequestsTest extends BaseTest { expectedRequestError = new RequestError(); se = new ServiceException(); se.setMessageId(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); - se.setText("Null response from RequestDB when searching by RequestId"); + se.setText("Null response from RequestDB when searching by RequestId " + INVALID_REQUEST_ID); expectedRequestError.setServiceException(se); builder = UriComponentsBuilder.fromHttpUrl( @@ -345,7 +421,7 @@ public class OrchestrationRequestsTest extends BaseTest { actualRequestError = mapper.readValue(response.getBody(), RequestError.class); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); - assertThat(actualRequestError, sameBeanAs(expectedRequestError)); + assertThat(expectedRequestError, sameBeanAs(actualRequestError)); } @Test @@ -408,6 +484,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertThat(actualProcessingData, sameBeanAs(expectedDataList)); } + public void setupTestGetOrchestrationRequest() throws Exception { // For testGetOrchestrationRequest wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java index 5023155768..47aa3cccb5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -21,10 +21,12 @@ package org.onap.so.apihandlerinfra; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; @@ -38,6 +40,7 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; 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.constants.OrchestrationRequestFormat; import org.onap.so.constants.Status; import org.onap.so.db.request.beans.InfraActiveRequests; @@ -232,6 +235,21 @@ public class OrchestrationRequestsUnitTest { } @Test + public void mapRequestStatusAndExtSysErrSrcToRequestErrorMessageTest() throws ApiException { + InstanceReferences instanceReferences = new InstanceReferences(); + instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); + iar.setExtSystemErrorSource(ROLLBACK_EXT_SYSTEM_ERROR_SOURCE); + iar.setFlowStatus(null); + iar.setStatusMessage("Error retrieving cloud region from AAI"); + + Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest, + OrchestrationRequestFormat.DETAIL.toString()); + + assertTrue(actual.getRequestStatus().getStatusMessage() + .contains("Error Source: " + ROLLBACK_EXT_SYSTEM_ERROR_SOURCE)); + } + + @Test public void mapRequestStatusAndExtSysErrSrcToRequestFlowStatusSuccessfulCompletionTest() throws ApiException { InstanceReferences instanceReferences = new InstanceReferences(); instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID); @@ -295,6 +313,14 @@ public class OrchestrationRequestsUnitTest { assertEquals(Status.ABORTED.toString(), result); } + @Test + public void mapRequestStatusToRequestForFormatStatusDetailTest() throws ApiException { + iar.setRequestStatus(Status.ABORTED.toString()); + String result = orchestrationRequests.mapRequestStatusToRequest(iar, "statusDetail"); + + assertEquals(Status.ABORTED.toString(), result); + } + @Test public void mapRequestStatusToRequestForFormatEmptyStringTest() throws ApiException { @@ -303,4 +329,13 @@ public class OrchestrationRequestsUnitTest { assertEquals(Status.FAILED.toString(), result); } + + @Test + public void infraActiveRequestNullValidationExceptionTest() throws ApiException { + iar.setRequestId(REQUEST_ID); + thrown.expect(ValidateException.class); + thrown.expectMessage(containsString("Null response from RequestDB when searching by RequestId " + REQUEST_ID)); + orchestrationRequests.infraActiveRequestLookup(iar.getRequestId()); + } + } 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 index e4532cd8d7..abdf38dfa6 100644 --- 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 @@ -30,9 +30,10 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; 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.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import static org.onap.so.logger.MdcConstants.CLIENT_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; +import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -95,10 +96,10 @@ public class RequestHandlerUtilsTest extends BaseTest { // 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(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(ONAP_PARTNER_NAME, "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)); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java index d4b0c3aad1..557771d298 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -25,10 +25,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Timestamp; +import java.util.HashMap; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -102,7 +104,7 @@ public class RequestHandlerUtilsUnitTest { private void setInfraActiveRequest() throws IOException { infraActiveRequest.setTenantId("tenant-id"); infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); - infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setCloudRegion("cloudRegion"); infraActiveRequest.setRequestScope("service"); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); @@ -117,7 +119,7 @@ public class RequestHandlerUtilsUnitTest { currentActiveRequest.setStartTime(startTimeStamp); currentActiveRequest.setTenantId("tenant-id"); currentActiveRequest.setRequestBody(getRequestBody("/RequestBodyNewRequestorId.json")); - currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setCloudRegion("cloudRegion"); currentActiveRequest.setRequestScope("service"); currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); @@ -441,4 +443,28 @@ public class RequestHandlerUtilsUnitTest { assertEquals(expected, result); } + @Test + public void checkForDuplicateRequestsTest() throws ApiException { + InfraActiveRequests currentActiveReq = new InfraActiveRequests(); + currentActiveReq.setCloudRegion("testRegion"); + currentActiveReq.setRequestId("792a3158-d9a3-49fd-b3ac-ab09842d6a1a"); + Action action = Action.createInstance; + String requestScope = ModelType.service.toString(); + + InfraActiveRequests duplicate = new InfraActiveRequests(); + + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + String instanceName = "instanceName"; + + doReturn(duplicate).when(requestHandler).duplicateCheck(action, instanceIdMap, instanceName, requestScope, + currentActiveReq); + doReturn(true).when(requestHandler).camundaHistoryCheck(duplicate, currentActiveReq); + doNothing().when(requestHandler).buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, + instanceName, requestScope, duplicate); + + requestHandler.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, instanceName); + verify(requestHandler).buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, duplicate); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java index 1e755419be..7191e297ec 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -21,6 +21,7 @@ package org.onap.so.apihandlerinfra; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -30,7 +31,6 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -56,10 +56,10 @@ import org.onap.so.constants.Status; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.web.client.HttpClientErrorException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.so.serviceinstancebeans.ModelType; @RunWith(MockitoJUnitRunner.class) public class ResumeOrchestrationRequestTest { @@ -149,7 +149,7 @@ public class ResumeOrchestrationRequestTest { private void setInfraActiveRequest() throws IOException { infraActiveRequest.setTenantId("tenant-id"); infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); - infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setCloudRegion("cloudRegion"); infraActiveRequest.setRequestScope(SERVICE); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); @@ -173,7 +173,7 @@ public class ResumeOrchestrationRequestTest { currentActiveRequest.setStartTime(startTimeStamp); currentActiveRequest.setTenantId("tenant-id"); currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); - currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setCloudRegion("cloudRegion"); currentActiveRequest.setRequestScope(SERVICE); currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); @@ -258,7 +258,7 @@ public class ResumeOrchestrationRequestTest { when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), anyString())).thenReturn(sir); when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); - doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sir, action, aLaCarte, + doReturn(lookupResult).when(requestHandler).getServiceInstanceOrchestrationURI(sir, action, aLaCarte, currentActiveRequest); doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); @@ -311,7 +311,7 @@ public class ResumeOrchestrationRequestTest { anyString())).thenReturn(sirNullALaCarte); when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); doReturn(false).when(msoRequest).getAlacarteFlag(sirNullALaCarte); - doReturn(lookupResult).when(serviceInstances).getServiceInstanceOrchestrationURI(sirNullALaCarte, action, false, + doReturn(lookupResult).when(requestHandler).getServiceInstanceOrchestrationURI(sirNullALaCarte, action, false, currentActiveRequest); doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sirNullALaCarte); 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 e28e36d307..006b82ac58 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 @@ -7,9 +7,9 @@ * 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. @@ -29,21 +29,13 @@ 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; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; -import static org.onap.so.logger.MdcConstants.CLIENT_ID; -import static org.onap.so.logger.MdcConstants.ENDTIME; -import static org.onap.so.logger.MdcConstants.INVOCATION_ID; -import static org.onap.so.logger.MdcConstants.PARTNERNAME; -import static org.onap.so.logger.MdcConstants.RESPONSECODE; -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 java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -64,7 +56,6 @@ 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.ModelType; @@ -89,12 +80,10 @@ 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 { private final ObjectMapper mapper = new ObjectMapper(); - private ObjectMapper errorMapper = new ObjectMapper(); @Autowired private ServiceInstances servInstances; @@ -116,15 +105,13 @@ public class ServiceInstancesTest extends BaseTest { @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(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(ONAP_PARTNER_NAME, "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)); @@ -132,7 +119,7 @@ public class ServiceInstancesTest extends BaseTest { } catch (MalformedURLException e) { e.printStackTrace(); } - wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse() + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); Mockito.doReturn(null).when(requestsDbClient).getInfraActiveRequestbyRequestId(Mockito.any()); } @@ -225,35 +212,6 @@ public class ServiceInstancesTest extends BaseTest { 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(); - 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(); - 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)); - 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 @@ -285,14 +243,13 @@ public class ServiceInstancesTest extends BaseTest { requestReferences.setInstanceId("1882939"); requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceUriPrev7 + "v5"; + uri = servInstanceuri + "v5"; ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers); // then - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + assertEquals(404, response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test @@ -896,7 +853,7 @@ public class ServiceInstancesTest extends BaseTest { ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(404, response.getStatusCode().value()); } @Test @@ -905,7 +862,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals("No valid vnfResource is specified", realResponse.getServiceException().getText()); } @@ -948,6 +905,45 @@ public class ServiceInstancesTest extends BaseTest { } @Test + public void replaceVnfInstanceNoCloudConfig() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/v1/getInfraActiveRequests.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("infra/VnfLookup.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/TestResponse.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))); + 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))); + 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")); + expectedResponse.setRequestReferences(requestReferences); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + ResponseEntity<String> response = + sendRequest(inputStream("/ReplaceVnfNoCloudConfig.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 replaceVnfRecreateInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/RecreateInfraVce")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) @@ -1338,7 +1334,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals("No valid vfModuleCustomization is specified", realResponse.getServiceException().getText()); } @@ -1379,6 +1375,44 @@ public class ServiceInstancesTest extends BaseTest { } @Test + public void replaceVfModuleInstanceNoCloudConfigurationTest() throws IOException { + wireMockServer.stubFor( + get(urlPathEqualTo("/aai/v19/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("infra/Vnf.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/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + 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")); + 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("/ReplaceVfModuleNoCloudConfig.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 updateVfModuleInstance() throws IOException { wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) @@ -1429,7 +1463,6 @@ public class ServiceInstancesTest extends BaseTest { public void createVfModuleNoModelType() throws IOException { InfraActiveRequests expectedRecord = new InfraActiveRequests(); expectedRecord.setRequestStatus("FAILED"); - expectedRecord.setAction("createInstance"); expectedRecord.setStatusMessage("Error parsing request: No valid modelType is specified"); expectedRecord.setProgress(100L); expectedRecord.setSource("VID"); @@ -2142,7 +2175,7 @@ public class ServiceInstancesTest extends BaseTest { sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}", realResponse.getServiceException().getText()); } @@ -2177,7 +2210,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); } @@ -2210,7 +2243,7 @@ public class ServiceInstancesTest extends BaseTest { sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertTrue(realResponse.getServiceException().getText() .contains("<aetgt:ErrorMessage>Exception in create execution list 500")); } @@ -2248,14 +2281,12 @@ public class ServiceInstancesTest extends BaseTest { requestReferences.setInstanceId("1882939"); requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceUriPrev7 + "v5"; + uri = servInstanceuri + "v5"; ResponseEntity<String> response = sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, 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")); + assertEquals(404, response.getStatusCode().value()); } @Test @@ -2266,7 +2297,7 @@ public class ServiceInstancesTest extends BaseTest { RequestParameters requestParameters = request.getRequestDetails().getRequestParameters(); String userParamsTxt = inputStream("/userParams.txt"); - List<Map<String, Object>> userParams = servInstances.configureUserParams(requestParameters); + List<Map<String, Object>> userParams = requestHandlerUtils.configureUserParams(requestParameters); System.out.println(userParams); assertTrue(userParams.size() > 0); assertTrue(userParams.get(0).containsKey("name")); @@ -2280,7 +2311,7 @@ public class ServiceInstancesTest extends BaseTest { ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); CloudConfiguration cloudConfig = - servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters()); + requestHandlerUtils.configureCloudConfig(request.getRequestDetails().getRequestParameters()); assertEquals("mdt25b", cloudConfig.getLcpCloudRegionId()); assertEquals("aefb697db6524ddebfe4915591b0a347", cloudConfig.getTenantId()); @@ -2293,7 +2324,7 @@ public class ServiceInstancesTest extends BaseTest { mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); ServiceInstancesRequest expected = mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class); - servInstances.mapToLegacyRequest(request.getRequestDetails()); + requestHandlerUtils.mapToLegacyRequest(request.getRequestDetails()); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request)); assertThat(request, sameBeanAs(expected)); } @@ -2380,7 +2411,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); } @@ -2396,7 +2427,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals( "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error", realResponse.getServiceException().getText()); @@ -2419,7 +2450,7 @@ public class ServiceInstancesTest extends BaseTest { sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + RequestError realResponse = mapper.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()); @@ -2441,7 +2472,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.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$InternalServerError: 500 Server Error", realResponse.getServiceException().getText()); @@ -2458,7 +2489,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals( "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error", realResponse.getServiceException().getText()); @@ -2490,7 +2521,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals( "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error", realResponse.getServiceException().getText()); @@ -2510,7 +2541,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals( "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error", realResponse.getServiceException().getText()); @@ -2527,7 +2558,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals( "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error", realResponse.getServiceException().getText()); @@ -2572,15 +2603,6 @@ public class ServiceInstancesTest extends BaseTest { ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); 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)); - } - } } @Test @@ -2632,7 +2654,7 @@ public class ServiceInstancesTest extends BaseTest { ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE); // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified"); } @@ -2645,7 +2667,7 @@ public class ServiceInstancesTest extends BaseTest { ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noPartnerHeaders); // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified"); } @@ -2664,7 +2686,7 @@ public class ServiceInstancesTest extends BaseTest { // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified"); } @@ -2752,7 +2774,7 @@ public class ServiceInstancesTest extends BaseTest { 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); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); assertEquals(realResponse.getServiceException().getText(), "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); } @@ -2934,15 +2956,20 @@ public class ServiceInstancesTest extends BaseTest { Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); assertEquals(Action.replaceInstanceRetainAssignments, action); } - /* - * @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"; Optional<URL> actualSelfLinkUrl = 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 = buildSelfLinkUrl(incomingUrlV, requestId); assertEquals(expectedSelfLinkV, - * actualSelfLinkUrlV.get().toString()); } - */ + + @Test + public void getCloudConfigurationAAIEntityNotFoundTest() throws IOException { + RequestError expectedResponse = + mapper.readValue(inputStream("/AAIEntityNotFoundResponse.json"), RequestError.class); + 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("/ReplaceVfModuleNoCloudConfig.json"), uri, HttpMethod.POST, headers); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertThat(expectedResponse, sameBeanAs(realResponse)); + } + } + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java new file mode 100644 index 0000000000..d399de0b7a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java @@ -0,0 +1,100 @@ +package org.onap.so.apihandlerinfra; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import java.util.HashMap; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.infra.rest.BpmnRequestBuilder; +import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; +import org.onap.so.apihandlerinfra.vnfbeans.ModelType; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.serviceinstancebeans.CloudConfiguration; + +@RunWith(MockitoJUnitRunner.class) +public class ServiceInstancesUnitTest { + + @Mock + private BpmnRequestBuilder bpmnRequestBuilder; + + @Spy + @InjectMocks + private ServiceInstances serviceInstances; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @Test + public void getCloudConfigurationOnReplaceVnfTest() throws ApiException { + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setTenantId("tenantId"); + cloudConfiguration.setLcpCloudRegionId("lcpCloudRegionId"); + String requestScope = ModelType.vnf.toString(); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("vnfInstanceId", "17c10d8e-48f4-4ee6-b162-a801943df6d6"); + InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + + doReturn(cloudConfiguration).when(bpmnRequestBuilder) + .mapCloudConfigurationVnf("17c10d8e-48f4-4ee6-b162-a801943df6d6"); + CloudConfiguration result = + serviceInstances.getCloudConfigurationOnReplace(requestScope, instanceIdMap, currentActiveRequest); + + assertEquals(cloudConfiguration, result); + } + + @Test + public void getCloudConfigurationOnReplaceVfModuleTest() throws ApiException { + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setTenantId("tenantId"); + cloudConfiguration.setLcpCloudRegionId("lcpCloudRegionId"); + String requestScope = ModelType.vfModule.toString(); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("vnfInstanceId", "17c10d8e-48f4-4ee6-b162-a801943df6d6"); + instanceIdMap.put("vfModuleInstanceId", "17c10d8e-48f4-4ee6-b162-a801943df6d8"); + InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + + doReturn(cloudConfiguration).when(bpmnRequestBuilder).getCloudConfigurationVfModuleReplace( + "17c10d8e-48f4-4ee6-b162-a801943df6d6", "17c10d8e-48f4-4ee6-b162-a801943df6d8"); + CloudConfiguration result = + serviceInstances.getCloudConfigurationOnReplace(requestScope, instanceIdMap, currentActiveRequest); + + assertEquals(cloudConfiguration, result); + } + + @Test + public void getCloudConfigurationReturnsNullTest() throws ApiException { + String requestScope = ModelType.vfModule.toString(); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("vnfInstanceId", "17c10d8e-48f4-4ee6-b162-a801943df6d6"); + instanceIdMap.put("vfModuleInstanceId", "17c10d8e-48f4-4ee6-b162-a801943df6d8"); + InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + + doReturn(null).when(bpmnRequestBuilder).getCloudConfigurationVfModuleReplace( + "17c10d8e-48f4-4ee6-b162-a801943df6d6", "17c10d8e-48f4-4ee6-b162-a801943df6d8"); + thrown.expect(CloudConfigurationNotFoundException.class); + thrown.expectMessage("CloudConfiguration not found during autofill for replace request."); + + serviceInstances.getCloudConfigurationOnReplace(requestScope, instanceIdMap, currentActiveRequest); + } + + @Test + public void setCloudConfigurationCurrentActiveRequestTest() { + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setTenantId("tenantId"); + cloudConfiguration.setLcpCloudRegionId("lcpCloudRegionId"); + + InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + serviceInstances.setCloudConfigurationCurrentActiveRequest(cloudConfiguration, currentActiveRequest); + + assertEquals("tenantId", currentActiveRequest.getTenantId()); + assertEquals("lcpCloudRegionId", currentActiveRequest.getCloudRegion()); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java index 3644dd8e7f..faac11715a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java @@ -22,8 +22,12 @@ package org.onap.so.apihandlerinfra.infra.rest; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import java.io.File; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Rule; @@ -32,7 +36,6 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.ServiceInstance; @@ -40,10 +43,14 @@ import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.constants.Status; import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import com.fasterxml.jackson.databind.ObjectMapper; @@ -55,15 +62,19 @@ public class BpmnRequestBuilderTest { @Rule public ExpectedException exceptionRule = ExpectedException.none(); + + @Mock + private AAIResourcesClient aaiResourcesClient; + @InjectMocks - @Spy - BpmnRequestBuilder reqBuilder; + private AAIDataRetrieval aaiData = spy(AAIDataRetrieval.class); @Mock private RequestsDbClient requestDBClient; - @Mock - private AAIResourcesClient aaiResourcesClient; + @InjectMocks + private BpmnRequestBuilder reqBuilder = spy(BpmnRequestBuilder.class); + private ObjectMapper mapper = new ObjectMapper(); @@ -71,8 +82,7 @@ public class BpmnRequestBuilderTest { @Before public void setup() { - reqBuilder.setAaiResourcesClient(aaiResourcesClient); - + // aaiData.setAaiResourcesClient(aaiResourcesClient); } @Test @@ -80,11 +90,11 @@ public class BpmnRequestBuilderTest { ServiceInstance service = provider.getMapper().readValue(new File(RESOURCE_PATH + "ServiceInstance.json"), ServiceInstance.class); - doReturn(service).when(reqBuilder).getServiceInstance("serviceId"); + doReturn(service).when(aaiData).getServiceInstance("serviceId"); ServiceInstancesRequest expectedRequest = mapper .readValue(new File(RESOURCE_PATH + "ExpectedServiceRequest.json"), ServiceInstancesRequest.class); - expectedRequest.getRequestDetails().getModelInfo().setModelId(null); - // bad getter/setter setting multiple fields + expectedRequest.getRequestDetails().getModelInfo().setModelId(null); // bad getter/setter setting multiple + // fields ServiceInstancesRequest actualRequest = reqBuilder.buildServiceDeleteRequest("serviceId"); assertThat(actualRequest, sameBeanAs(expectedRequest)); } @@ -128,13 +138,59 @@ public class BpmnRequestBuilderTest { AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")); VolumeGroup volumeGroup = provider.getMapper().readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class); - - doReturn(Optional.of(volumeGroup)).when(aaiResourcesClient).get(VolumeGroup.class, AAIUriFactory - .createResourceUri(AAIObjectType.VOLUME_GROUP, "cloudOwner", "regionOne", "volumeGroupId")); + AAIResultWrapper wrapper = new AAIResultWrapper(volumeGroup); + doReturn(wrapper).when(aaiResourcesClient) + .get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId") + .relatedTo(AAIObjectType.VOLUME_GROUP, "volumeGroupId")); ServiceInstancesRequest expectedRequest = mapper .readValue(new File(RESOURCE_PATH + "ExpectedVolumeGroupRequest.json"), ServiceInstancesRequest.class); ServiceInstancesRequest actualRequest = reqBuilder.buildVolumeGroupDeleteRequest("vnfId", "volumeGroupId"); assertThat(actualRequest, sameBeanAs(expectedRequest)); } + + @Test + public void test_getCloudConfigurationVfModuleReplace() throws Exception { + String vnfId = "vnfId"; + String vfModuleId = "vfModuleId"; + + GenericVnf vnf = provider.getMapper().readValue(new File(RESOURCE_PATH + "Vnf.json"), GenericVnf.class); + + doReturn(Optional.of(vnf)).when(aaiResourcesClient).get(GenericVnf.class, + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)); + + CloudConfiguration result = reqBuilder.getCloudConfigurationVfModuleReplace(vnfId, vfModuleId); + assertEquals("0422ffb57ba042c0800a29dc85ca70f8", result.getTenantId()); + assertEquals("cloudOwner", result.getCloudOwner()); + assertEquals("regionOne", result.getLcpCloudRegionId()); + } + + @Test + public void test_mapCloudConfigurationVnf() throws Exception { + String vnfId = "6fb01019-c3c4-41fe-b307-d1c56850b687"; + Map<String, String[]> filters = new HashMap<>(); + filters.put("vnfId", new String[] {"EQ", vnfId}); + filters.put("requestStatus", new String[] {"EQ", Status.COMPLETE.toString()}); + filters.put("action", new String[] {"EQ", "createInstance"}); + + ServiceInstancesRequest serviceRequest = new ServiceInstancesRequest(); + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + RequestDetails requestDetails = new RequestDetails(); + cloudConfiguration.setCloudOwner("cloudOwner"); + cloudConfiguration.setTenantId("tenantId"); + cloudConfiguration.setLcpCloudRegionId("lcpCloudRegionId"); + requestDetails.setCloudConfiguration(cloudConfiguration); + serviceRequest.setRequestDetails(requestDetails); + + doReturn(filters).when(reqBuilder).createQueryRequest("vnfId", vnfId); + doReturn(Optional.of(serviceRequest)).when(reqBuilder).findServiceInstanceRequest(filters); + + + CloudConfiguration result = reqBuilder.mapCloudConfigurationVnf(vnfId); + assertEquals("tenantId", result.getTenantId()); + assertEquals("cloudOwner", result.getCloudOwner()); + assertEquals("lcpCloudRegionId", result.getLcpCloudRegionId()); + } + } + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java index 59308215ac..0ae963ab15 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java @@ -108,7 +108,6 @@ public class NetworkRestHandlerTest { public void test_createInfraActiveRequestForDelete() throws Exception { InfraActiveRequests expected = new InfraActiveRequests(); expected.setRequestAction(Action.deleteInstance.toString()); - expected.setAction(Action.deleteInstance.toString()); expected.setServiceInstanceId("serviceInstanceId"); expected.setNetworkId("networkId"); expected.setRequestId("requestId"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java index c1e6347943..602eb51f41 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java @@ -154,7 +154,6 @@ public class ServiceInstanceRestHandlerTest { public void test_createInfraActiveRequestForDelete() throws Exception { InfraActiveRequests expected = new InfraActiveRequests(); expected.setRequestAction(Action.deleteInstance.toString()); - expected.setAction(Action.deleteInstance.toString()); expected.setServiceInstanceId("serviceInstanceId"); expected.setRequestId("requestId"); expected.setRequestorId("userId"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java index 7d146791fe..ca81124833 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java @@ -154,7 +154,6 @@ public class VfModuleRestHandlerTest { public void test_createInfraActiveRequestForDelete() throws Exception { InfraActiveRequests expected = new InfraActiveRequests(); expected.setRequestAction(Action.deleteInstance.toString()); - expected.setAction(Action.deleteInstance.toString()); expected.setServiceInstanceId("serviceInstanceId"); expected.setVnfId("vnfId"); expected.setVfModuleId("vfModuleId"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java index 03725ec85b..3ae3abb16d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java @@ -119,7 +119,6 @@ public class VnfRestHandlerTest { public void test_createInfraActiveRequestForDelete() throws Exception { InfraActiveRequests expected = new InfraActiveRequests(); expected.setRequestAction(Action.deleteInstance.toString()); - expected.setAction(Action.deleteInstance.toString()); expected.setServiceInstanceId("serviceInstanceId"); expected.setVnfId("vnfId"); expected.setRequestId("requestId"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java index efa27743ef..1315f13892 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java @@ -109,7 +109,6 @@ public class VolumeRestHandlerTest { public void test_createInfraActiveRequestForDelete() throws Exception { InfraActiveRequests expected = new InfraActiveRequests(); expected.setRequestAction(Action.deleteInstance.toString()); - expected.setAction(Action.deleteInstance.toString()); expected.setServiceInstanceId("serviceInstanceId"); expected.setVnfId("vnfId"); expected.setVolumeGroupId("volumeGroupId"); 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 a74c11c08b..71784fa286 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 @@ -262,7 +262,6 @@ public class CloudOrchestrationTest extends BaseTest { 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); 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 5f12060059..1917ee592f 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 @@ -271,7 +271,6 @@ public class CloudResourcesOrchestrationTest extends BaseTest { InfraActiveRequests iar = new InfraActiveRequests(); iar.setRequestId("requestId-getOpEnvFilterEx1"); iar.setRequestScope("requestScope"); - iar.setRequestType("requestType"); iar.setOperationalEnvId("operationalEnvironmentId"); iar.setOperationalEnvName("operationalEnvName"); iar.setRequestorId("xxxxxx"); @@ -296,7 +295,6 @@ public class CloudResourcesOrchestrationTest extends BaseTest { InfraActiveRequests iar = new InfraActiveRequests(); iar.setRequestId("requestIdFilterException2"); iar.setRequestScope("requestScope"); - iar.setRequestType("requestType"); iar.setOperationalEnvId("operationalEnvId"); iar.setOperationalEnvName("operationalEnvName"); iar.setRequestorId("xxxxxx"); 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 3114f91096..8d8f4969d7 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 @@ -95,7 +95,7 @@ public class CreateEcompOperationalEnvironmentTest extends BaseTest { .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")) + "{\"requestId\":\"123\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"progress\":100")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); @@ -127,7 +127,7 @@ public class CreateEcompOperationalEnvironmentTest extends BaseTest { .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:")) + + "\",\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); 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 ebed4fa16b..6c00f8db27 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 @@ -151,7 +151,7 @@ public class CreateVnfOperationalEnvironmentTest extends BaseTest { ObjectMapper mapper = new ObjectMapper(); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + + "\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); @@ -188,7 +188,7 @@ public class CreateVnfOperationalEnvironmentTest extends BaseTest { ObjectMapper mapper = new ObjectMapper(); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + + "\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); 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 16738e9799..9911bb8cb8 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 @@ -64,7 +64,7 @@ public class DeactivateVnfOperationalEnvironmentTest extends BaseTest { public void init() { wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + + "\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); } @@ -129,7 +129,7 @@ public class DeactivateVnfOperationalEnvironmentTest extends BaseTest { .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")) + + "\",\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); 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 f178a3c0cb..2e9576cf7c 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 @@ -28,12 +28,9 @@ import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; 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; @@ -48,7 +45,6 @@ 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 { @@ -79,36 +75,10 @@ public class GRMClientTest extends BaseTest { 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(); - 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; - } - - if (!foundInvoke) - fail("INVOKE Marker not found"); - - if (!foundInvokeReturn) - fail("INVOKE RETURN Marker not found"); - 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"))); - TestAppender.events.clear(); + .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO.APIH"))); } @Test diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/InfraActiveRequestsReset.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/InfraActiveRequestsReset.sql index 6d8e2e8b09..f5373a1f15 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/InfraActiveRequestsReset.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/InfraActiveRequestsReset.sql @@ -1,16 +1,17 @@ -INSERT INTO requestdb.infra_active_requests(REQUEST_ID, CLIENT_REQUEST_ID, ACTION, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, AIC_NODE_CLLI, TENANT_ID, PROV_STATUS, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, REQUEST_TYPE, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, AAI_SERVICE_ID, AIC_CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES -('00032ab7-3fb3-42e5-965d-8ea592502017', '00032ab7-3fb3-42e5-965d-8ea592502016', 'deleteInstance', 'COMPLETE', 'Vf Module has been deleted successfully.', '100', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', null, 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('00032ab7-na18-42e5-965d-8ea592502018', '00032ab7-fake-42e5-965d-8ea592502018', 'deleteInstance', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', null, 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('00093944-bf16-4373-ab9a-3adfe730ff2d', null, 'createInstance', 'FAILED', 'Error: Locked instance - This service (MSODEV_1707_SI_v10_011-4) already has a request being worked with a status of IN_PROGRESS (RequestId - 278e83b1-4f9f-450e-9e7d-3700a6ed22f4). The existing request must finish or be cleaned up before proceeding.', '100', '2017-07-11 18:33:26', '2017-07-11 18:33:26', 'VID', null, null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, null, '{"modelInfo":{"modelInvariantId":"9647dfc4-2083-11e7-93ae-92361f002671","modelType":"service","modelName":"Infra_v10_Service","modelVersion":"1.0","modelVersionId":"5df8b6de-2083-11e7-93ae-92361f002671"},"requestInfo":{"source":"VID","instanceName":"MSODEV_1707_SI_v10_011-4","suppressRollback":false,"requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true}}', null, 'APIH', null, null, null, null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', null, 'MSODEV_1707_SI_v10_011-4', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('001619d2-a297-4a4b-a9f5-e2823c88458f', '001619d2-a297-4a4b-a9f5-e2823c88458f', 'CREATE_VF_MODULE', 'COMPLETE', 'COMPLETED', '100', '2016-07-01 14:11:42', '2017-05-02 16:03:34', 'PORTAL', null, 'test-vscp', 'elena_test21', null, null, '381b9ff6c75e4625b7a4182f90fc68d3', null, null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', 'NONE', 'RDBTEST', '2016-07-01 14:11:42', 'VNF', null, null, null, 'MODULENAME1', 'moduleModelName', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb', 'mtn9', null, null, null, null, null, 'vfModule', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('5ffbabd6-b793-4377-a1ab-082670fbc7ac', '5ffbabd6-b793-4377-a1ab-082670fbc7ac', 'deleteInstance', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"requestDetails": {"modelInfo": {"modelType": "vfModule","modelName": "test::base::module-0","modelVersionId": "20c4431c-246d-11e7-93ae-92361f002671","modelInvariantId": "78ca26d0-246d-11e7-93ae-92361f002671","modelVersion": "2","modelCustomizationId": "cb82ffd8-252a-11e7-93ae-92361f002671"},"cloudConfiguration": {"lcpCloudRegionId": "n6","tenantId": "0422ffb57ba042c0800a29dc85ca70f8"},"requestInfo": {"instanceName": "MSO-DEV-VF-1806BB-v10-base-it2-1","source": "VID","suppressRollback": false,"requestorId": "xxxxxx"},"relatedInstanceList": [{"relatedInstance": {"instanceId": "76fa8849-4c98-473f-b431-2590b192a653","modelInfo": {"modelType": "service","modelName": "Infra_v10_Service","modelVersionId": "5df8b6de-2083-11e7-93ae-92361f002671","modelInvariantId": "9647dfc4-2083-11e7-93ae-92361f002671","modelVersion": "1.0"}}},{"relatedInstance": {"instanceId": "d57970e1-5075-48a5-ac5e-75f2d6e10f4c","modelInfo": {"modelType": "vnf","modelName": "v10","modelVersionId": "ff2ae348-214a-11e7-93ae-92361f002671","modelInvariantId": "2fff5b20-214b-11e7-93ae-92361f002671","modelVersion": "1.0","modelCustomizationId": "68dc9a92-214c-11e7-93ae-92361f002671","modelCustomizationName": "v10 1"}}}],"requestParameters": {"usePreload": true,"userParams": []}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', null, 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); -INSERT INTO requestdb.infra_active_requests(REQUEST_ID, CLIENT_REQUEST_ID, ACTION, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, AIC_NODE_CLLI, TENANT_ID, PROV_STATUS, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, REQUEST_TYPE, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, AAI_SERVICE_ID, AIC_CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES -('00164b9e-784d-48a8-8973-bbad6ef818ed', null, 'createInstance', 'COMPLETE', 'Service Instance was created successfully.', '100', '2017-09-28 12:45:51', '2017-09-28 12:45:53', 'VID', null, null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"52b49b5d-3086-4ffd-b5e6-1b1e5e7e062f","modelType":"service","modelNameVersionId":null,"modelName":"MSO Test Network","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"aed5a5b7-20d3-44f7-90a3-ddbd16f14d1e","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":"DEV-n6-3100-0927-1","suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":null,"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"aicNodeClli":null,"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'CreateGenericALaCarteServiceInstance', '2017-09-28 12:45:52', null, null, null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', 'b2f59173-b7e5-4e0f-8440-232fd601b865', 'DEV-n6-3100-0927-1', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('00173cc9-5ce2-4673-a810-f87fefb2829e', null, 'createInstance', 'FAILED', 'Error parsing request. No valid instanceName is specified', '100', '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', null, null, null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, null, '{"modelInfo":{"modelInvariantId":"ff6163d4-7214-459e-9f76-507b4eb00f51","modelType":"service","modelName":"ConstraintsSrvcVID","modelVersion":"2.0","modelVersionId":"722d256c-a374-4fba-a14f-a59b76bb7656"},"requestInfo":{"productFamilyId":"LRSI-OSPF","source":"VID","requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"},"cloudConfiguration":{"tenantId":"a259ae7b7c3f493cb3d91f95a7c18149","lcpCloudRegionId":"mtn16"},"requestParameters":{"subscriptionServiceType":"Mobility","userParams":[{"name":"neutronport6_name","value":"8"},{"name":"neutronnet5_network_name","value":"8"},{"name":"contrailv2vlansubinterface3_name","value":"false"}]}}', null, 'APIH', null, null, null, null, null, null, null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('0017f68c-eb2d-45bb-b7c7-ec31b37dc349', null, 'activateInstance', 'UNLOCKED', null, '20', '2017-09-26 16:09:29', null, 'VID', null, null, null, null, null, null, null, null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"1587cf0e-f12f-478d-8530-5c55ac578c39","modelType":"configuration","modelNameVersionId":null,"modelName":null,"modelVersion":null,"modelCustomizationUuid":null,"modelVersionId":"36a3a8ea-49a6-4ac8-b06c-89a545444455","modelCustomizationId":"68dc9a92-214c-11e7-93ae-92361f002671","modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":null,"suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":[{"relatedInstance":{"instanceName":null,"instanceId":"9e15a443-af65-4f05-9000-47ae495e937d","modelInfo":{"modelCustomizationName":null,"modelInvariantId":"de19ae10-9a25-11e7-abc4-cec278b6b50a","modelType":"service","modelNameVersionId":null,"modelName":"Infra_Configuration_Service","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"ee938612-9a25-11e7-abc4-cec278b6b50a","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"instanceDirection":null}}],"subscriberInfo":null,"cloudConfiguration":{"aicNodeClli":null,"tenantId":null,"lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":null,"userParams":[],"aLaCarte":false,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'APIH', '2017-09-26 16:09:29', null, null, null, null, null, null, null, 'n6', null, null, null, null, null, 'configuration', 'activateInstance', '9e15a443-af65-4f05-9000-47ae495e937d', null, 'xxxxxx', '26ef7f15-57bb-48df-8170-e59edc26234c', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('0017f68c-eb2d-45bb-b7c7-ec31b37dc350', null, 'createInstance', 'IN_PROGRESS', 'Error parsing request. - No valid instanceName is specified', null, '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', - '1882938', null, null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, null, - '{"serviceInstanceId":"1882939","vnfInstanceId":"1882938","networkInstanceId":"1882937","volumeGroupInstanceId":"1882935","vfModuleInstanceId":"1882934","requestDetails":{"requestInfo":{"source":"VID","requestorId":"xxxxxx","instanceName":"testService9"},"requestParameters":{"aLaCarte":true,"autoBuildVfModules":false,"subscriptionServiceType":"test"},"modelInfo":{"modelInvariantId":"f7ce78bb-423b-11e7-93f8-0050569a7965","modelVersion":"1","modelVersionId":"10","modelType":"service","modelName":"serviceModel","modelInstanceName":"modelInstanceName","modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"}}}', - null, 'APIH', null, null, '1882935', null, '1882934', null, null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', '1882939', 'testService10', 'xxxxxx', 'test', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); +INSERT INTO requestdb.infra_active_requests(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES +('00032ab7-3fb3-42e5-965d-8ea592502017', 'COMPLETE', 'Vf Module has been deleted successfully.', '100', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, '{"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('00032ab7-na18-42e5-965d-8ea592502018', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('00093944-bf16-4373-ab9a-3adfe730ff2d', 'FAILED', 'Error: Locked instance - This service (MSODEV_1707_SI_v10_011-4) already has a request being worked with a status of IN_PROGRESS (RequestId - 278e83b1-4f9f-450e-9e7d-3700a6ed22f4). The existing request must finish or be cleaned up before proceeding.', '100', '2017-07-11 18:33:26', '2017-07-11 18:33:26', 'VID', null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, '{"modelInfo":{"modelInvariantId":"9647dfc4-2083-11e7-93ae-92361f002671","modelType":"service","modelName":"Infra_v10_Service","modelVersion":"1.0","modelVersionId":"5df8b6de-2083-11e7-93ae-92361f002671"},"requestInfo":{"source":"VID","instanceName":"MSODEV_1707_SI_v10_011-4","suppressRollback":false,"requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true}}', null, 'APIH', null, null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', null, 'MSODEV_1707_SI_v10_011-4', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('001619d2-a297-4a4b-a9f5-e2823c88458f', 'COMPLETE', 'COMPLETED', '100', '2016-07-01 14:11:42', '2017-05-02 16:03:34', 'PORTAL', null, 'test-vscp', 'elena_test21', null, '381b9ff6c75e4625b7a4182f90fc68d3', null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', 'NONE', 'RDBTEST', '2016-07-01 14:11:42', null, null, null, 'MODULENAME1', 'moduleModelName', 'mtn9', null, null, null, null, null, 'vfModule', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('5ffbabd6-b793-4377-a1ab-082670fbc7ac', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, '{"requestDetails": {"modelInfo": {"modelType": "vfModule","modelName": "test::base::module-0","modelVersionId": "20c4431c-246d-11e7-93ae-92361f002671","modelInvariantId": "78ca26d0-246d-11e7-93ae-92361f002671","modelVersion": "2","modelCustomizationId": "cb82ffd8-252a-11e7-93ae-92361f002671"},"cloudConfiguration": {"lcpCloudRegionId": "n6","tenantId": "0422ffb57ba042c0800a29dc85ca70f8"},"requestInfo": {"instanceName": "MSO-DEV-VF-1806BB-v10-base-it2-1","source": "VID","suppressRollback": false,"requestorId": "xxxxxx"},"relatedInstanceList": [{"relatedInstance": {"instanceId": "76fa8849-4c98-473f-b431-2590b192a653","modelInfo": {"modelType": "service","modelName": "Infra_v10_Service","modelVersionId": "5df8b6de-2083-11e7-93ae-92361f002671","modelInvariantId": "9647dfc4-2083-11e7-93ae-92361f002671","modelVersion": "1.0"}}},{"relatedInstance": {"instanceId": "d57970e1-5075-48a5-ac5e-75f2d6e10f4c","modelInfo": {"modelType": "vnf","modelName": "v10","modelVersionId": "ff2ae348-214a-11e7-93ae-92361f002671","modelInvariantId": "2fff5b20-214b-11e7-93ae-92361f002671","modelVersion": "1.0","modelCustomizationId": "68dc9a92-214c-11e7-93ae-92361f002671","modelCustomizationName": "v10 1"}}}],"requestParameters": {"usePreload": true,"userParams": []}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); + + +INSERT INTO requestdb.infra_active_requests(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES +('00164b9e-784d-48a8-8973-bbad6ef818ed', 'COMPLETE', 'Service Instance was created successfully.', '100', '2017-09-28 12:45:51', '2017-09-28 12:45:53', 'VID', null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"52b49b5d-3086-4ffd-b5e6-1b1e5e7e062f","modelType":"service","modelNameVersionId":null,"modelName":"MSO Test Network","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"aed5a5b7-20d3-44f7-90a3-ddbd16f14d1e","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":"DEV-n6-3100-0927-1","suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":null,"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"aicNodeClli":null,"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'CreateGenericALaCarteServiceInstance', '2017-09-28 12:45:52', null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', 'b2f59173-b7e5-4e0f-8440-232fd601b865', 'DEV-n6-3100-0927-1', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('00173cc9-5ce2-4673-a810-f87fefb2829e', 'FAILED', 'Error parsing request. No valid instanceName is specified', '100', '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', null, null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, '{"modelInfo":{"modelInvariantId":"ff6163d4-7214-459e-9f76-507b4eb00f51","modelType":"service","modelName":"ConstraintsSrvcVID","modelVersion":"2.0","modelVersionId":"722d256c-a374-4fba-a14f-a59b76bb7656"},"requestInfo":{"productFamilyId":"LRSI-OSPF","source":"VID","requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"},"cloudConfiguration":{"tenantId":"a259ae7b7c3f493cb3d91f95a7c18149","lcpCloudRegionId":"mtn16"},"requestParameters":{"subscriptionServiceType":"Mobility","userParams":[{"name":"neutronport6_name","value":"8"},{"name":"neutronnet5_network_name","value":"8"},{"name":"contrailv2vlansubinterface3_name","value":"false"}]}}', null, 'APIH', null, null, null, null, null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('0017f68c-eb2d-45bb-b7c7-ec31b37dc349', 'UNLOCKED', null, '20', '2017-09-26 16:09:29', null, 'VID', null, null, null, null, null, null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"1587cf0e-f12f-478d-8530-5c55ac578c39","modelType":"configuration","modelNameVersionId":null,"modelName":null,"modelVersion":null,"modelCustomizationUuid":null,"modelVersionId":"36a3a8ea-49a6-4ac8-b06c-89a545444455","modelCustomizationId":"68dc9a92-214c-11e7-93ae-92361f002671","modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":null,"suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":[{"relatedInstance":{"instanceName":null,"instanceId":"9e15a443-af65-4f05-9000-47ae495e937d","modelInfo":{"modelCustomizationName":null,"modelInvariantId":"de19ae10-9a25-11e7-abc4-cec278b6b50a","modelType":"service","modelNameVersionId":null,"modelName":"Infra_Configuration_Service","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"ee938612-9a25-11e7-abc4-cec278b6b50a","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"instanceDirection":null}}],"subscriberInfo":null,"cloudConfiguration":{"aicNodeClli":null,"tenantId":null,"lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":null,"userParams":[],"aLaCarte":false,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'APIH', '2017-09-26 16:09:29', null, null, null, null, null, 'n6', null, null, null, null, null, 'configuration', 'activateInstance', '9e15a443-af65-4f05-9000-47ae495e937d', null, 'xxxxxx', '26ef7f15-57bb-48df-8170-e59edc26234c', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('0017f68c-eb2d-45bb-b7c7-ec31b37dc350', 'IN_PROGRESS', 'Error parsing request. + No valid instanceName is specified', null, '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', '1882938', null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, + '{"serviceInstanceId":"1882939","vnfInstanceId":"1882938","networkInstanceId":"1882937","volumeGroupInstanceId":"1882935","vfModuleInstanceId":"1882934","requestDetails":{"requestInfo":{"source":"VID","requestorId":"xxxxxx","instanceName":"testService9"},"requestParameters":{"aLaCarte":true,"autoBuildVfModules":false,"subscriptionServiceType":"test"},"modelInfo":{"modelInvariantId":"f7ce78bb-423b-11e7-93f8-0050569a7965","modelVersion":"1","modelVersionId":"10","modelType":"service","modelName":"serviceModel","modelInstanceName":"modelInstanceName","modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"}}}', null, 'APIH', null, '1882935', null, '1882934', null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', '1882939', 'testService10', 'xxxxxx', 'test', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); + COMMIT;
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getRequestProcessingDataArray.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getRequestProcessingDataArray.json new file mode 100644 index 0000000000..c746020e7f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getRequestProcessingDataArray.json @@ -0,0 +1,8 @@ +[{ + "id": 1, + "soRequestId": "00032ab7-na18-42e5-965d-8ea592502018", + "groupingId": "7d2e8c07-4d10-456d-bddc-37abf38ca714", + "name": "requestAction", + "value": "assign", + "tag": "pincFabricConfigRequest" +}] diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/AAIEntityNotFoundResponse.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/AAIEntityNotFoundResponse.json new file mode 100644 index 0000000000..2004a82ed7 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/AAIEntityNotFoundResponse.json @@ -0,0 +1,8 @@ +{ + "requestError": { + "serviceException": { + "messageId": "SVC0001", + "text": "Generic Vnf Not Found In Inventory, VnfId: ff305d54-75b4-431b-adb2-eb6b9e5ff000" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json new file mode 100644 index 0000000000..63021b611f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json @@ -0,0 +1,20 @@ +{ + "requestDetails": { + "requestParameters": { + "userParams": [{ + "nrmObj": { + "EUtranGenericCell" : [ + {"cellLocalId":1, "pci":5}, + {"cellLocalId":2, "pci":6} + ], + "ExternalEUtranCell" : [ + {"cellLocalId":3, "eNBId": "x"}, + {"cellLocalId":4, "eNBId": "y"} + ], + "EUtranRelation": [{"scellLocalId":5, "tcellLocalId":6}] + } + }], + "payload": "[{\"GNBDUFunction\":{\"gNBId\":1,\"gNBDUId\":5}}]" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleNoCloudConfig.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleNoCloudConfig.json new file mode 100644 index 0000000000..766d49bee8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleNoCloudConfig.json @@ -0,0 +1,28 @@ +{ + "requestDetails": { + "requestInfo": { + "source": "VID", + "requestorId": "xxxxxx", + "instanceName": "testService60" + }, + "requestParameters": { + "aLaCarte": true, + "autoBuildVfModules": false, + "subscriptionServiceType": "test" + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7968", + "modelVersion":"2", + "modelVersionId":"78ca26d0-246d-11e7-93ae-92361f002671", + "modelType":"vfModule", + "modelName":"serviceModel", + "modelCustomizationId": "a7f1d08e-b02d-11e6-80f5-76304dec7eb7" + }, + "subscriberInfo": { + "globalSubscriberId": "MSO_1610_dev", + "subscriberName": "MSO_1610_dev" + } + } +} + + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVnfNoCloudConfig.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVnfNoCloudConfig.json new file mode 100644 index 0000000000..46873588c0 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVnfNoCloudConfig.json @@ -0,0 +1,58 @@ +{ + "vnfInstanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "requestDetails": { + "modelInfo": { + "modelType": "vnf", + "modelInvariantId": "ff5256d2-5a33-55df-13ab-12abad84e7ff", + "modelName": "vSAMP12..base..module-0", + "modelVersion": "1", + "modelVersionId": "1", + "modelCustomizationId": "68dc9a92-214c-11e7-93ae-92361f002671" + }, + "requestInfo": { + "instanceName": "VNFTEST-10", + "source": "VID", + "suppressRollback": true, + "requestorId": "xxxxxx", + "productFamilyId": "FamilyID" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f7ce78bb-423b-11e7-93f8-0050569a7968", + "modelInfo": { + "modelType": "service", + "modelInvariantId": "ff3514e3-5a33-55df-13ab-12abad84e7ff", + "modelVersionId": "fe6985cd-ea33-3346-ac12-ab121484a3fe", + "modelName": "vSAMP12", + "modelVersion": "1.0" + } + } + }, + { + "relatedInstance": { + "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000", + "instanceDirection": "source", + "modelInfo": { + "modelType": "vnf", + "modelInvariantId": "ff5256d1-5a33-55df-13ab-12abad84e7ff", + "modelVersionId": "fe6478e4-ea33-3346-ac12-ab121484a3fe", + "modelName": "vSAMP12", + "modelVersion": "1.0", + "modelCustomizationId": "b0ed83ec-b7b4-4c70-91c2-63feeaf8609b" + } + } + } + ], + "requestParameters": { + "aLaCarte": true, + "userParams": [] + }, + "platform": { + "platformName": "platformName" + }, + "lineOfBusiness": { + "lineOfBusinessName": "lobName" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json new file mode 100644 index 0000000000..a6aa3e1c25 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json @@ -0,0 +1,33 @@ +{ + "serviceInstanceId":"1882939", + "vnfInstanceId":"1882938", + "networkInstanceId":"1882937", + "volumeGroupInstanceId":"1882935", + "vfModuleInstanceId":"1882934", + "requestDetails": { + "requestInfo": { + "source": "VID", + "requestorId": "xxxxxx", + "instanceName": "testService9" + }, + "requestParameters": { + "aLaCarte": true, + "autoBuildVfModules": false, + "subscriptionServiceType": "test", + "disableOwningEntityProject": true + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion":"1", + "modelVersionId":"10", + "modelType":"service", + "modelName":"serviceModel", + "modelInstanceName":"modelInstanceName", + "modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796" + }, + "subscriberInfo": { + "globalSubscriberId": "someTestId", + "subscriberName": "someTestId" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json index 6be015694c..c79900a15d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json @@ -1,7 +1,5 @@ { "requestId":"f0a35706-efc4-4e27-80ea-a995d7a2a40f", - "clientRequestId":null, - "action":"activateInstance", "requestStatus":"UNLOCKED", "statusMessage":null, "progress":20, @@ -12,23 +10,19 @@ "vnfName":null, "vnfType":null, "serviceType":null, - "aicNodeClli":null, "tenantId":null, - "provStatus":null, "vnfParams":null, "vnfOutputs":null, "requestBody":"{\"modelInfo\":{\"modelCustomizationName\":null,\"modelInvariantId\":\"1587cf0e-f12f-478d-8530-5c55ac578c39\",\"modelType\":\"configuration\",\"modelNameVersionId\":null,\"modelName\":null,\"modelVersion\":null,\"modelCustomizationUuid\":null,\"modelVersionId\":\"36a3a8ea-49a6-4ac8-b06c-89a545444455\",\"modelCustomizationId\":\"68dc9a92-214c-11e7-93ae-92361f002671\",\"modelUuid\":null,\"modelInvariantUuid\":null,\"modelInstanceName\":null},\"requestInfo\":{\"billingAccountNumber\":null,\"callbackUrl\":null,\"correlator\":null,\"orderNumber\":null,\"productFamilyId\":null,\"orderVersion\":null,\"source\":\"VID\",\"instanceName\":null,\"suppressRollback\":false,\"requestorId\":\"xxxxxx\"},\"relatedInstanceList\":[{\"relatedInstance\":{\"instanceName\":null,\"instanceId\":\"9e15a443-af65-4f05-9000-47ae495e937d\",\"modelInfo\":{\"modelCustomizationName\":null,\"modelInvariantId\":\"de19ae10-9a25-11e7-abc4-cec278b6b50a\",\"modelType\":\"service\",\"modelNameVersionId\":null,\"modelName\":\"Infra_Configuration_Service\",\"modelVersion\":\"1.0\",\"modelCustomizationUuid\":null,\"modelVersionId\":\"ee938612-9a25-11e7-abc4-cec278b6b50a\",\"modelCustomizationId\":null,\"modelUuid\":null,\"modelInvariantUuid\":null,\"modelInstanceName\":null},\"instanceDirection\":null}}],\"subscriberInfo\":null,\"cloudConfiguration\":{\"aicNodeClli\":null,\"tenantId\":null,\"lcpCloudRegionId\":\"n6\"},\"requestParameters\":{\"subscriptionServiceType\":null,\"userParams\":[],\"aLaCarte\":false,\"autoBuildVfModules\":false,\"cascadeDelete\":false,\"usePreload\":true},\"project\":null,\"owningEntity\":null,\"platform\":null,\"lineOfBusiness\":null}", "responseBody":null, "lastModifiedBy":"APIH", "modifyTime":1532945172000, - "requestType":null, "volumeGroupId":null, "volumeGroupName":null, "vfModuleId":null, "vfModuleName":null, "vfModuleModelName":null, - "aaiServiceId":null, - "aicCloudRegion":"n6", + "cloudRegion":"n6", "callBackUrl":null, "correlator":null, "serviceInstanceId":"9e15a443-af65-4f05-9000-47ae495e937d", @@ -47,4 +41,4 @@ }, "requestURI":"http://localhost:8087/infraActiveRequests/%1$s" -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json index d63525b297..db33df4d76 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json @@ -1,6 +1,4 @@ { - "clientRequestId": null, - "action": "deleteInstance", "requestStatus": "%2$s", "statusMessage": null, "progress": 20, @@ -11,23 +9,19 @@ "vnfName": null, "vnfType": null, "serviceType": null, - "aicNodeClli": null, "tenantId": null, - "provStatus": null, "vnfParams": null, "vnfOutputs": null, "requestBody": "{\"modelInfo\":{\"modelCustomizationName\":null,\"modelInvariantId\":\"1587cf0e-f12f-478d-8530-5c55ac578c39\",\"modelType\":\"configuration\",\"modelNameVersionId\":null,\"modelName\":null,\"modelVersion\":null,\"modelCustomizationUuid\":null,\"modelVersionId\":\"36a3a8ea-49a6-4ac8-b06c-89a545444455\",\"modelCustomizationId\":\"68dc9a92-214c-11e7-93ae-92361f002671\",\"modelUuid\":null,\"modelInvariantUuid\":null,\"modelInstanceName\":null},\"requestInfo\":{\"billingAccountNumber\":null,\"callbackUrl\":null,\"correlator\":null,\"orderNumber\":null,\"productFamilyId\":null,\"orderVersion\":null,\"source\":\"VID\",\"instanceName\":null,\"suppressRollback\":false,\"requestorId\":\"xxxxxx\"},\"relatedInstanceList\":[{\"relatedInstance\":{\"instanceName\":null,\"instanceId\":\"9e15a443-af65-4f05-9000-47ae495e937d\",\"modelInfo\":{\"modelCustomizationName\":null,\"modelInvariantId\":\"de19ae10-9a25-11e7-abc4-cec278b6b50a\",\"modelType\":\"service\",\"modelNameVersionId\":null,\"modelName\":\"Infra_Configuration_Service\",\"modelVersion\":\"1.0\",\"modelCustomizationUuid\":null,\"modelVersionId\":\"ee938612-9a25-11e7-abc4-cec278b6b50a\",\"modelCustomizationId\":null,\"modelUuid\":null,\"modelInvariantUuid\":null,\"modelInstanceName\":null},\"instanceDirection\":null}}],\"subscriberInfo\":null,\"cloudConfiguration\":{\"aicNodeClli\":null,\"tenantId\":null,\"lcpCloudRegionId\":\"n6\"},\"requestParameters\":{\"subscriptionServiceType\":null,\"userParams\":[],\"aLaCarte\":false,\"autoBuildVfModules\":false,\"cascadeDelete\":false,\"usePreload\":true},\"project\":null,\"owningEntity\":null,\"platform\":null,\"lineOfBusiness\":null}", "responseBody": null, "lastModifiedBy": "APIH", "modifyTime": "2018-07-30T10:06:12.000+0000", - "requestType": null, "volumeGroupId": null, "volumeGroupName": null, "vfModuleId": null, "vfModuleName": null, "vfModuleModelName": null, - "aaiServiceId": null, - "aicCloudRegion": "n6", + "cloudRegion": "n6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "9e15a443-af65-4f05-9000-47ae495e937d", @@ -51,4 +45,4 @@ "href": "http://localhost:8087/infraActiveRequests/%1$s" } } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json index 21568e5273..f36ae0f9da 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json @@ -1,5 +1,4 @@ { - "clientRequestId": null, "action": "deleteInstance", "requestStatus": "%2$s", "statusMessage": null, @@ -11,23 +10,19 @@ "vnfName": null, "vnfType": null, "serviceType": null, - "aicNodeClli": null, "tenantId": null, - "provStatus": null, "vnfParams": null, "vnfOutputs": null, "requestBody": null, "responseBody": null, "lastModifiedBy": "APIH", "modifyTime": "2018-07-30T10:06:12.000+0000", - "requestType": null, "volumeGroupId": null, "volumeGroupName": null, "vfModuleId": null, "vfModuleName": null, "vfModuleModelName": null, - "aaiServiceId": null, - "aicCloudRegion": "n6", + "cloudRegion": "n6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "9e15a443-af65-4f05-9000-47ae495e937d", @@ -51,4 +46,4 @@ "href": "http://localhost:8087/infraActiveRequests/%1$s" } } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json new file mode 100644 index 0000000000..133d8bed9b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json @@ -0,0 +1,5 @@ +{ + "artifactUUID": "81526781-e55c-4cb7-adb3-97e09d9c76bf", + "artifactName": "testingPNFWorkflow.bpmn", + "name": "testingPNFWorkflow" +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json index 09f6d81da3..0b03f56caa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json @@ -101,7 +101,7 @@ }, { "relationship-key": "volume-group.volume-group-id", - "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6" + "relationship-value": "volumeGroupId" } ] }, diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json new file mode 100644 index 0000000000..eef0776f5d --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json @@ -0,0 +1,30 @@ +[ + { + "requestId":"b15f30dc-56b1-4a1a-aaf1-156c0d685142", + "action":"createInstance", + "requestStatus":"COMPLETE", + "statusMessage":"ALaCarte-Vnf-createInstance request was executed correctly.", + "flowStatus":"Successfully completed all Building Blocks", + "progress":100, + "startTime":"2019-11-11T19:28:56.000+0000", + "endTime":"2019-11-11T19:29:15.000+0000", + "source":"VID", + "vnfId":"5b20c24e-cabb-4725-8f88-57ca99a8ffe1", + "vnfName":"Robot_VNF_For_Volume_Group", + "vnfType":"Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0", + "tenantId":"0422ffb57ba042c0800a29dc85ca70f8", + "requestBody":"{\"requestDetails\": {\"relatedInstanceList\": [{\"relatedInstance\": {\"instanceId\": \"f5435110-b276-4920-9261-a18a5582d357\", \"modelInfo\": {\"modelVersionId\": \"bad955c3-29b2-4a27-932e-28e942cc6480\", \"modelVersion\": \"1\", \"modelName\": \"Vf zrdm5bpxmc02092017-Service\", \"modelInvariantId\": \"b16a9398-ffa3-4041-b78c-2956b8ad9c7b\", \"modelType\": \"service\"}}}], \"requestParameters\": {\"userParams\": [], \"enforceValidNfValues\": false, \"testApi\": \"GR_API\"}, \"lineOfBusiness\": {\"lineOfBusinessName\": \"vSAMP12_14-2XXX-Aug18-9001 - LOB\"}, \"requestInfo\": {\"source\": \"VID\", \"requestorId\": \"az2016\", \"instanceName\": \"Robot_VNF_For_Volume_Group\", \"suppressRollback\": false, \"productFamilyId\": \"06f76284-8710-11e6-ae22-56b6b6499611\"}, \"platform\": {\"platformName\": \"vSAMP12_14-2XXX-Aug18-9001 - Platform\"}, \"modelInfo\": {\"modelName\": \"Vf zrdm5bpxmc02092017-VF\", \"modelVersion\": \"1\", \"modelInvariantId\": \"23122c9b-dd7f-483f-bf0a-e069303db2f7\", \"modelType\": \"vnf\", \"modelCustomizationName\": \"Vf zrdm5bpxmc02092017-VF 0\", \"modelVersionId\": \"d326f424-2312-4dd6-b7fe-364fadbd1ef5\", \"modelCustomizationId\": \"96c23a4a-6887-4b2c-9cce-1e4ea35eaade\"}, \"cloudConfiguration\": {\"cloudOwner\": \"cloudOwner\", \"tenantId\": \"0422ffb57ba042c0800a29dc85ca70f8\", \"lcpCloudRegionId\": \"regionOne\"}}}", + "lastModifiedBy":"CamundaBPMN", + "modifyTime":"2019-11-11T19:29:15.000+0000", + "cloudRegion":"regionOne", + "serviceInstanceId":"f5435110-b276-4920-9261-a18a5582d357", + "requestScope":"vnf", + "requestAction":"createInstance", + "requestorId":"az2016", + "requestUrl":"http://192.168.99.100:9100/onap/so/infra/serviceInstantiation/v7/serviceInstances/f5435110-b276-4920-9261-a18a5582d357/vnfs", + "cloudApiRequests":[ + + ], + "requestURI":"b15f30dc-56b1-4a1a-aaf1-156c0d685142" + } +] diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml index 2e1c6a9bdc..1d6722278c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml @@ -9,14 +9,22 @@ server: mso: health: endpoints: - catalogdb: http://localhost:${wiremock.server.port} - requestdb: http://localhost:${wiremock.server.port} - sdnc: http://localhost:${wiremock.server.port} - openstack: http://localhost:${wiremock.server.port} - bpmn: http://localhost:${wiremock.server.port} - asdc: http://localhost:${wiremock.server.port} - requestdbattsvc: http://localhost:${wiremock.server.port} - + - subsystem: apih + uri: http://localhost:${wiremock.server.port} + - subsystem: asdc + uri: http://localhost:${wiremock.server.port} + - subsystem: bpmn + uri: http://localhost:${wiremock.server.port} + - subsystem: catalogdb + uri: http://localhost:${wiremock.server.port} + - subsystem: openstack + uri: http://localhost:${wiremock.server.port} + - subsystem: requestdb + uri: http://localhost:${wiremock.server.port} + - subsystem: sdnc + uri: http://localhost:${wiremock.server.port} + - subsystem: soappcorchestrator + uri: http://localhost:${wiremock.server.port} infra-requests: archived: period: 180 @@ -118,7 +126,13 @@ mariaDB4j: port: 3307 databaseName: catalogdb databaseName2: requestdb - +#Actuator +management: + endpoints: + web: + base-path: /manage + exposure: + include: "*" org: onap: 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 22f68e0579..5a1c532d0e 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 @@ -1,27 +1,22 @@ --Changes here should also be made in InfraActiveRequestsReset.sql to be re-inserted after tests -INSERT INTO requestdb.infra_active_requests(REQUEST_ID, CLIENT_REQUEST_ID, ACTION, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, AIC_NODE_CLLI, TENANT_ID, PROV_STATUS, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, REQUEST_TYPE, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, AAI_SERVICE_ID, AIC_CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES -('00032ab7-3fb3-42e5-965d-8ea592502017', '00032ab7-3fb3-42e5-965d-8ea592502016', 'deleteInstance', 'COMPLETE', 'Vf Module has been deleted successfully.', '100', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', null, 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('00032ab7-na18-42e5-965d-8ea592502018', '00032ab7-fake-42e5-965d-8ea592502018', 'deleteInstance', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', null, 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, null), -('00093944-bf16-4373-ab9a-3adfe730ff2d', null, 'createInstance', 'FAILED', 'Error: Locked instance - This service (MSODEV_1707_SI_v10_011-4) already has a request being worked with a status of IN_PROGRESS (RequestId - 278e83b1-4f9f-450e-9e7d-3700a6ed22f4). The existing request must finish or be cleaned up before proceeding.', '100', '2017-07-11 18:33:26', '2017-07-11 18:33:26', 'VID', null, null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, null, '{"modelInfo":{"modelInvariantId":"9647dfc4-2083-11e7-93ae-92361f002671","modelType":"service","modelName":"Infra_v10_Service","modelVersion":"1.0","modelVersionId":"5df8b6de-2083-11e7-93ae-92361f002671"},"requestInfo":{"source":"VID","instanceName":"MSODEV_1707_SI_v10_011-4","suppressRollback":false,"requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true}}', null, 'APIH', null, null, null, null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', null, 'MSODEV_1707_SI_v10_011-4', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('001619d2-a297-4a4b-a9f5-e2823c88458f', '001619d2-a297-4a4b-a9f5-e2823c88458f', 'CREATE_VF_MODULE', 'COMPLETE', 'COMPLETED', '100', '2016-07-01 14:11:42', '2017-05-02 16:03:34', 'PORTAL', null, 'test-vscp', 'elena_test21', null, null, '381b9ff6c75e4625b7a4182f90fc68d3', null, null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', 'NONE', 'RDBTEST', '2016-07-01 14:11:42', 'VNF', null, null, null, 'MODULENAME1', 'moduleModelName', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb', 'mtn9', null, null, null, null, null, 'vfModule', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('5ffbabd6-b793-4377-a1ab-082670fbc7ac', '5ffbabd6-b793-4377-a1ab-082670fbc7ac', 'deleteInstance', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"requestDetails": {"modelInfo": {"modelType": "vfModule","modelName": "test::base::module-0","modelVersionId": "20c4431c-246d-11e7-93ae-92361f002671","modelInvariantId": "78ca26d0-246d-11e7-93ae-92361f002671","modelVersion": "2","modelCustomizationId": "cb82ffd8-252a-11e7-93ae-92361f002671"},"cloudConfiguration": {"lcpCloudRegionId": "n6","tenantId": "0422ffb57ba042c0800a29dc85ca70f8"},"requestInfo": {"instanceName": "MSO-DEV-VF-1806BB-v10-base-it2-1","source": "VID","suppressRollback": false,"requestorId": "xxxxxx"},"relatedInstanceList": [{"relatedInstance": {"instanceId": "76fa8849-4c98-473f-b431-2590b192a653","modelInfo": {"modelType": "service","modelName": "Infra_v10_Service","modelVersionId": "5df8b6de-2083-11e7-93ae-92361f002671","modelInvariantId": "9647dfc4-2083-11e7-93ae-92361f002671","modelVersion": "1.0"}}},{"relatedInstance": {"instanceId": "d57970e1-5075-48a5-ac5e-75f2d6e10f4c","modelInfo": {"modelType": "vnf","modelName": "v10","modelVersionId": "ff2ae348-214a-11e7-93ae-92361f002671","modelInvariantId": "2fff5b20-214b-11e7-93ae-92361f002671","modelVersion": "1.0","modelCustomizationId": "68dc9a92-214c-11e7-93ae-92361f002671","modelCustomizationName": "v10 1"}}}],"requestParameters": {"usePreload": true,"userParams": []}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', null, 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); -INSERT INTO requestdb.infra_active_requests(REQUEST_ID, CLIENT_REQUEST_ID, ACTION, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, AIC_NODE_CLLI, TENANT_ID, PROV_STATUS, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, REQUEST_TYPE, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, AAI_SERVICE_ID, AIC_CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES -('00164b9e-784d-48a8-8973-bbad6ef818ed', null, 'createInstance', 'COMPLETE', 'Service Instance was created successfully.', '100', '2017-09-28 12:45:51', '2017-09-28 12:45:53', 'VID', null, null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"52b49b5d-3086-4ffd-b5e6-1b1e5e7e062f","modelType":"service","modelNameVersionId":null,"modelName":"MSO Test Network","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"aed5a5b7-20d3-44f7-90a3-ddbd16f14d1e","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":"DEV-n6-3100-0927-1","suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":null,"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"aicNodeClli":null,"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'CreateGenericALaCarteServiceInstance', '2017-09-28 12:45:52', null, null, null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', 'b2f59173-b7e5-4e0f-8440-232fd601b865', 'DEV-n6-3100-0927-1', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('00173cc9-5ce2-4673-a810-f87fefb2829e', null, 'createInstance', 'FAILED', 'Error parsing request. No valid instanceName is specified', '100', '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', null, null, null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, null, '{"modelInfo":{"modelInvariantId":"ff6163d4-7214-459e-9f76-507b4eb00f51","modelType":"service","modelName":"ConstraintsSrvcVID","modelVersion":"2.0","modelVersionId":"722d256c-a374-4fba-a14f-a59b76bb7656"},"requestInfo":{"productFamilyId":"LRSI-OSPF","source":"VID","requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"},"cloudConfiguration":{"tenantId":"a259ae7b7c3f493cb3d91f95a7c18149","lcpCloudRegionId":"mtn16"},"requestParameters":{"subscriptionServiceType":"Mobility","userParams":[{"name":"neutronport6_name","value":"8"},{"name":"neutronnet5_network_name","value":"8"},{"name":"contrailv2vlansubinterface3_name","value":"false"}]}}', null, 'APIH', null, null, null, null, null, null, null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', null, null, null, null, null, null, null, null), -('0017f68c-eb2d-45bb-b7c7-ec31b37dc349', null, 'activateInstance', 'UNLOCKED', null, '20', '2017-09-26 16:09:29', null, 'VID', null, null, null, null, null, null, null, null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"1587cf0e-f12f-478d-8530-5c55ac578c39","modelType":"configuration","modelNameVersionId":null,"modelName":null,"modelVersion":null,"modelCustomizationUuid":null,"modelVersionId":"36a3a8ea-49a6-4ac8-b06c-89a545444455","modelCustomizationId":"68dc9a92-214c-11e7-93ae-92361f002671","modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":null,"suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":[{"relatedInstance":{"instanceName":null,"instanceId":"9e15a443-af65-4f05-9000-47ae495e937d","modelInfo":{"modelCustomizationName":null,"modelInvariantId":"de19ae10-9a25-11e7-abc4-cec278b6b50a","modelType":"service","modelNameVersionId":null,"modelName":"Infra_Configuration_Service","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"ee938612-9a25-11e7-abc4-cec278b6b50a","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"instanceDirection":null}}],"subscriberInfo":null,"cloudConfiguration":{"aicNodeClli":null,"tenantId":null,"lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":null,"userParams":[],"aLaCarte":false,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'APIH', '2017-09-26 16:09:29', null, null, null, null, null, null, null, 'n6', null, null, null, null, null, 'configuration', 'activateInstance', '9e15a443-af65-4f05-9000-47ae495e937d', null, 'xxxxxx', '26ef7f15-57bb-48df-8170-e59edc26234c', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), -('0017f68c-eb2d-45bb-b7c7-ec31b37dc350', null, 'createInstance', 'IN_PROGRESS', 'Error parsing request. - No valid instanceName is specified', null, '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', - '1882938', null, null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, null, - '{"serviceInstanceId":"1882939","vnfInstanceId":"1882938","networkInstanceId":"1882937","volumeGroupInstanceId":"1882935","vfModuleInstanceId":"1882934","requestDetails":{"requestInfo":{"source":"VID","requestorId":"xxxxxx","instanceName":"testService9"},"requestParameters":{"aLaCarte":true,"autoBuildVfModules":false,"subscriptionServiceType":"test"},"modelInfo":{"modelInvariantId":"f7ce78bb-423b-11e7-93f8-0050569a7965","modelVersion":"1","modelVersionId":"10","modelType":"service","modelName":"serviceModel","modelInstanceName":"modelInstanceName","modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"}}}', - null, 'APIH', null, null, '1882935', null, '1882934', null, null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', '1882939', 'testService10', 'xxxxxx', 'test', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); - +INSERT INTO requestdb.infra_active_requests(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES +('00032ab7-3fb3-42e5-965d-8ea592502017', 'COMPLETE', 'Vf Module has been deleted successfully.', '100', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, '{"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('00032ab7-na18-42e5-965d-8ea592502018', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, null), +('00093944-bf16-4373-ab9a-3adfe730ff2d', 'FAILED', 'Error: Locked instance - This service (MSODEV_1707_SI_v10_011-4) already has a request being worked with a status of IN_PROGRESS (RequestId - 278e83b1-4f9f-450e-9e7d-3700a6ed22f4). The existing request must finish or be cleaned up before proceeding.', '100', '2017-07-11 18:33:26', '2017-07-11 18:33:26', 'VID', null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, '{"modelInfo":{"modelInvariantId":"9647dfc4-2083-11e7-93ae-92361f002671","modelType":"service","modelName":"Infra_v10_Service","modelVersion":"1.0","modelVersionId":"5df8b6de-2083-11e7-93ae-92361f002671"},"requestInfo":{"source":"VID","instanceName":"MSODEV_1707_SI_v10_011-4","suppressRollback":false,"requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true}}', null, 'APIH', null, null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', null, 'MSODEV_1707_SI_v10_011-4', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('001619d2-a297-4a4b-a9f5-e2823c88458f', 'COMPLETE', 'COMPLETED', '100', '2016-07-01 14:11:42', '2017-05-02 16:03:34', 'PORTAL', null, 'test-vscp', 'elena_test21', null, '381b9ff6c75e4625b7a4182f90fc68d3', null, null, '{"requestDetails": {"modelInfo":{"modelType":"vfModule","modelName":"test::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"n6"}}}', 'NONE', 'RDBTEST', '2016-07-01 14:11:42', null, null, null, 'MODULENAME1', 'moduleModelName', 'mtn9', null, null, null, null, null, 'vfModule', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('5ffbabd6-b793-4377-a1ab-082670fbc7ac', 'PENDING', 'Vf Module deletion pending.', '0', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, '{"requestDetails": {"modelInfo": {"modelType": "vfModule","modelName": "test::base::module-0","modelVersionId": "20c4431c-246d-11e7-93ae-92361f002671","modelInvariantId": "78ca26d0-246d-11e7-93ae-92361f002671","modelVersion": "2","modelCustomizationId": "cb82ffd8-252a-11e7-93ae-92361f002671"},"cloudConfiguration": {"lcpCloudRegionId": "n6","tenantId": "0422ffb57ba042c0800a29dc85ca70f8"},"requestInfo": {"instanceName": "MSO-DEV-VF-1806BB-v10-base-it2-1","source": "VID","suppressRollback": false,"requestorId": "xxxxxx"},"relatedInstanceList": [{"relatedInstance": {"instanceId": "76fa8849-4c98-473f-b431-2590b192a653","modelInfo": {"modelType": "service","modelName": "Infra_v10_Service","modelVersionId": "5df8b6de-2083-11e7-93ae-92361f002671","modelInvariantId": "9647dfc4-2083-11e7-93ae-92361f002671","modelVersion": "1.0"}}},{"relatedInstance": {"instanceId": "d57970e1-5075-48a5-ac5e-75f2d6e10f4c","modelInfo": {"modelType": "vnf","modelName": "v10","modelVersionId": "ff2ae348-214a-11e7-93ae-92361f002671","modelInvariantId": "2fff5b20-214b-11e7-93ae-92361f002671","modelVersion": "1.0","modelCustomizationId": "68dc9a92-214c-11e7-93ae-92361f002671","modelCustomizationName": "v10 1"}}}],"requestParameters": {"usePreload": true,"userParams": []}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'test::base::module-0', 'n6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); + +INSERT INTO requestdb.infra_active_requests(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES +('00164b9e-784d-48a8-8973-bbad6ef818ed', 'COMPLETE', 'Service Instance was created successfully.', '100', '2017-09-28 12:45:51', '2017-09-28 12:45:53', 'VID', null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"52b49b5d-3086-4ffd-b5e6-1b1e5e7e062f","modelType":"service","modelNameVersionId":null,"modelName":"MSO Test Network","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"aed5a5b7-20d3-44f7-90a3-ddbd16f14d1e","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":"DEV-n6-3100-0927-1","suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":null,"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"aicNodeClli":null,"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'CreateGenericALaCarteServiceInstance', '2017-09-28 12:45:52', null, null, null, null, null, 'n6', null, null, null, null, null, 'service', 'createInstance', 'b2f59173-b7e5-4e0f-8440-232fd601b865', 'DEV-n6-3100-0927-1', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('00173cc9-5ce2-4673-a810-f87fefb2829e', 'FAILED', 'Error parsing request. No valid instanceName is specified', '100', '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', null, null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, '{"modelInfo":{"modelInvariantId":"ff6163d4-7214-459e-9f76-507b4eb00f51","modelType":"service","modelName":"ConstraintsSrvcVID","modelVersion":"2.0","modelVersionId":"722d256c-a374-4fba-a14f-a59b76bb7656"},"requestInfo":{"productFamilyId":"LRSI-OSPF","source":"VID","requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"},"cloudConfiguration":{"tenantId":"a259ae7b7c3f493cb3d91f95a7c18149","lcpCloudRegionId":"mtn16"},"requestParameters":{"subscriptionServiceType":"Mobility","userParams":[{"name":"neutronport6_name","value":"8"},{"name":"neutronnet5_network_name","value":"8"},{"name":"contrailv2vlansubinterface3_name","value":"false"}]}}', null, 'APIH', null, null, null, null, null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', null, null, null, null, null, null, null, null), +('0017f68c-eb2d-45bb-b7c7-ec31b37dc349', 'UNLOCKED', null, '20', '2017-09-26 16:09:29', null, 'VID', null, null, null, null, null, null, null, '{"modelInfo":{"modelCustomizationName":null,"modelInvariantId":"1587cf0e-f12f-478d-8530-5c55ac578c39","modelType":"configuration","modelNameVersionId":null,"modelName":null,"modelVersion":null,"modelCustomizationUuid":null,"modelVersionId":"36a3a8ea-49a6-4ac8-b06c-89a545444455","modelCustomizationId":"68dc9a92-214c-11e7-93ae-92361f002671","modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"requestInfo":{"billingAccountNumber":null,"callbackUrl":null,"correlator":null,"orderNumber":null,"productFamilyId":null,"orderVersion":null,"source":"VID","instanceName":null,"suppressRollback":false,"requestorId":"xxxxxx"},"relatedInstanceList":[{"relatedInstance":{"instanceName":null,"instanceId":"9e15a443-af65-4f05-9000-47ae495e937d","modelInfo":{"modelCustomizationName":null,"modelInvariantId":"de19ae10-9a25-11e7-abc4-cec278b6b50a","modelType":"service","modelNameVersionId":null,"modelName":"Infra_Configuration_Service","modelVersion":"1.0","modelCustomizationUuid":null,"modelVersionId":"ee938612-9a25-11e7-abc4-cec278b6b50a","modelCustomizationId":null,"modelUuid":null,"modelInvariantUuid":null,"modelInstanceName":null},"instanceDirection":null}}],"subscriberInfo":null,"cloudConfiguration":{"aicNodeClli":null,"tenantId":null,"lcpCloudRegionId":"n6"},"requestParameters":{"subscriptionServiceType":null,"userParams":[],"aLaCarte":false,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true},"project":null,"owningEntity":null,"platform":null,"lineOfBusiness":null}', null, 'APIH', '2017-09-26 16:09:29', null, null, null, null, null, 'n6', null, null, null, null, null, 'configuration', 'activateInstance', '9e15a443-af65-4f05-9000-47ae495e937d', null, 'xxxxxx', '26ef7f15-57bb-48df-8170-e59edc26234c', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), +('0017f68c-eb2d-45bb-b7c7-ec31b37dc350', 'IN_PROGRESS', 'Error parsing request. + No valid instanceName is specified', null, '2017-04-14 21:08:46', '2017-04-14 21:08:46', 'VID', '1882938', null, null, null, 'a259ae7b7c3f493cb3d91f95a7c18149', null, null, '{"serviceInstanceId":"1882939","vnfInstanceId":"1882938","networkInstanceId":"1882937","volumeGroupInstanceId":"1882935","vfModuleInstanceId":"1882934","requestDetails":{"requestInfo":{"source":"VID","requestorId":"xxxxxx","instanceName":"testService9"},"requestParameters":{"aLaCarte":true,"autoBuildVfModules":false,"subscriptionServiceType":"test"},"modelInfo":{"modelInvariantId":"f7ce78bb-423b-11e7-93f8-0050569a7965","modelVersion":"1","modelVersionId":"10","modelType":"service","modelName":"serviceModel","modelInstanceName":"modelInstanceName","modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"}}}', null, 'APIH', null, '1882935', null, '1882934', null, null, 'mtn16', null, null, null, null, null, 'service', 'createInstance', '1882939', 'testService10', 'xxxxxx', 'test', null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'); INSERT INTO requestdb.site_status(SITE_NAME, STATUS, CREATION_TIMESTAMP) VALUES ('testSite', 0, '2017-11-30 15:48:09'); - - INSERT INTO requestdb.activate_operational_env_service_model_distribution_status(OPERATIONAL_ENV_ID, SERVICE_MODEL_VERSION_ID, REQUEST_ID, SERVICE_MOD_VER_FINAL_DISTR_STATUS, RECOVERY_ACTION, RETRY_COUNT_LEFT, WORKLOAD_CONTEXT, CREATE_TIME, MODIFY_TIME, VNF_OPERATIONAL_ENV_ID) VALUES ('1dfe7154-eae0-44f2-8e7a-8e5e7882e55d', '37305814-4949-45ce-ae24-c378c7ed07d1', '483646fe-36cc-4e90-895a-c472f6da3f74', 'DISTRIBUTION_COMPLETE_OK', 'RETRY', 0, 'VNF_D2D', '2018-02-02 18:44:27', '2018-02-02 18:45:06', 'vnf_1234'), ('1dfe7154-eae0-44f2-8e7a-8e5e7882e55d', '7bfa2197-8cbb-4080-b369-56c4d53c4573', '483646fe-36cc-4e90-895a-c472f6da3f74', 'DISTRIBUTION_COMPLETE_OK', 'SKIP', 0, 'VNF_D2D', '2018-02-02 18:44:27', '2018-02-02 18:44:56', 'vnf_1235'); 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 731d2bec4d..050780c9a2 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 @@ -809,6 +809,10 @@ CREATE TABLE `service` ( `OVERALL_DISTRIBUTION_STATUS` varchar(45), `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, `NAMING_POLICY` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, 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 @@ -963,6 +967,7 @@ CREATE TABLE `vf_module_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, 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`), @@ -1111,7 +1116,9 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT 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`), @@ -1192,6 +1199,7 @@ CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( `RESOURCE_INPUT` varchar(2000) DEFAULT NULL, `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) 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 @@ -1247,8 +1255,6 @@ USE requestdb; CREATE TABLE `infra_active_requests` ( `REQUEST_ID` varchar(45) NOT NULL, - `CLIENT_REQUEST_ID` varchar(45) DEFAULT NULL, - `ACTION` varchar(45) DEFAULT NULL, `REQUEST_STATUS` varchar(20) DEFAULT NULL, `STATUS_MESSAGE` longtext DEFAULT NULL, `PROGRESS` bigint(20) DEFAULT NULL, @@ -1256,26 +1262,23 @@ CREATE TABLE `infra_active_requests` ( `END_TIME` datetime DEFAULT NULL, `SOURCE` varchar(45) DEFAULT NULL, `VNF_ID` varchar(45) DEFAULT NULL, + `PNF_ID` varchar(45) DEFAULT NULL, `VNF_NAME` varchar(80) DEFAULT NULL, `VNF_TYPE` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(45) DEFAULT NULL, - `AIC_NODE_CLLI` varchar(11) DEFAULT NULL, `TENANT_ID` varchar(45) DEFAULT NULL, - `PROV_STATUS` varchar(20) DEFAULT NULL, `VNF_PARAMS` longtext, `VNF_OUTPUTS` longtext, `REQUEST_BODY` longtext, `RESPONSE_BODY` longtext, `LAST_MODIFIED_BY` varchar(100) DEFAULT NULL, `MODIFY_TIME` datetime DEFAULT NULL, - `REQUEST_TYPE` varchar(20) DEFAULT NULL, `VOLUME_GROUP_ID` varchar(45) DEFAULT NULL, `VOLUME_GROUP_NAME` varchar(45) DEFAULT NULL, `VF_MODULE_ID` varchar(45) DEFAULT NULL, `VF_MODULE_NAME` varchar(200) DEFAULT NULL, `VF_MODULE_MODEL_NAME` varchar(200) DEFAULT NULL, - `AAI_SERVICE_ID` varchar(50) DEFAULT NULL, - `AIC_CLOUD_REGION` varchar(11) DEFAULT NULL, + `CLOUD_REGION` varchar(11) DEFAULT NULL, `CALLBACK_URL` varchar(200) DEFAULT NULL, `CORRELATOR` varchar(80) DEFAULT NULL, `NETWORK_ID` varchar(45) DEFAULT NULL, @@ -1294,14 +1297,11 @@ CREATE TABLE `infra_active_requests` ( `ORIGINAL_REQUEST_ID` varchar(45) DEFAULT NULL, `EXT_SYSTEM_ERROR_SOURCE` varchar(80) DEFAULT NULL, `ROLLBACK_EXT_SYSTEM_ERROR_SOURCE` varchar(80) DEFAULT NULL, - PRIMARY KEY (`REQUEST_ID`), - UNIQUE KEY `UK_bhu6w8p7wvur4pin0gjw2d5ak` (`CLIENT_REQUEST_ID`) + PRIMARY KEY (`REQUEST_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `archived_infra_requests` ( `REQUEST_ID` varchar(45) NOT NULL, - `CLIENT_REQUEST_ID` varchar(45) DEFAULT NULL, - `ACTION` varchar(45) DEFAULT NULL, `REQUEST_STATUS` varchar(20) DEFAULT NULL, `STATUS_MESSAGE` longtext DEFAULT NULL, `PROGRESS` bigint(20) DEFAULT NULL, @@ -1312,23 +1312,19 @@ CREATE TABLE `archived_infra_requests` ( `VNF_NAME` varchar(80) DEFAULT NULL, `VNF_TYPE` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(45) DEFAULT NULL, - `AIC_NODE_CLLI` varchar(11) DEFAULT NULL, `TENANT_ID` varchar(45) DEFAULT NULL, - `PROV_STATUS` varchar(20) DEFAULT NULL, `VNF_PARAMS` longtext, `VNF_OUTPUTS` longtext, `REQUEST_BODY` longtext, `RESPONSE_BODY` longtext, `LAST_MODIFIED_BY` varchar(100) DEFAULT NULL, `MODIFY_TIME` datetime DEFAULT NULL, - `REQUEST_TYPE` varchar(20) DEFAULT NULL, `VOLUME_GROUP_ID` varchar(45) DEFAULT NULL, `VOLUME_GROUP_NAME` varchar(45) DEFAULT NULL, `VF_MODULE_ID` varchar(45) DEFAULT NULL, `VF_MODULE_NAME` varchar(200) DEFAULT NULL, `VF_MODULE_MODEL_NAME` varchar(200) DEFAULT NULL, - `AAI_SERVICE_ID` varchar(50) DEFAULT NULL, - `AIC_CLOUD_REGION` varchar(11) DEFAULT NULL, + `CLOUD_REGION` varchar(11) DEFAULT NULL, `CALLBACK_URL` varchar(200) DEFAULT NULL, `CORRELATOR` varchar(80) DEFAULT NULL, `NETWORK_ID` varchar(45) DEFAULT NULL, @@ -1344,8 +1340,7 @@ CREATE TABLE `archived_infra_requests` ( `OPERATIONAL_ENV_ID` varchar(45) DEFAULT NULL, `OPERATIONAL_ENV_NAME` varchar(200) DEFAULT NULL, `REQUEST_URL` varchar(500) DEFAULT NULL, - PRIMARY KEY (`REQUEST_ID`), - UNIQUE KEY `UK_bhu6w8p7wvur4pin0gjw2d59h` (`CLIENT_REQUEST_ID`) + PRIMARY KEY (`REQUEST_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `site_status` ( |