aboutsummaryrefslogtreecommitdiffstats
path: root/mso-api-handlers/mso-api-handler-infra
diff options
context:
space:
mode:
Diffstat (limited to 'mso-api-handlers/mso-api-handler-infra')
-rw-r--r--mso-api-handlers/mso-api-handler-infra/pom.xml4
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java61
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java29
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java7
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java180
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java185
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java33
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java146
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java84
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java83
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java22
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckResponse.java49
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckStatus.java (renamed from mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java)4
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java40
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java116
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java25
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java29
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java44
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java3
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java209
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java228
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java277
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java283
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoSubsystems.java (renamed from mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java)15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java5
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java96
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java6
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java26
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java21
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java22
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java11
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java8
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java11
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java85
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java410
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java89
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java89
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java94
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java87
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java97
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java29
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/CloudConfigurationNotFoundException.java29
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/NoRecipeException.java31
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java30
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.java29
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java214
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java113
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java116
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java125
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java110
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java104
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java40
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java80
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java5
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java19
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java11
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java9
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java10
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java70
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java19
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java5
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java6
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java15
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java3
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/resources/application-local.yaml179
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml29
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java55
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java340
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java182
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java47
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java152
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java330
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java20
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java444
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java483
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java221
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java147
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java64
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java143
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java189
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java190
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java154
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java145
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java83
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json57
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json48
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json2
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json8
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json44
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json62
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json13
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json19
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json19
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/CustomWorkflowRequest.json21
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json33
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json33
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json57
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json57
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json20
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json25
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json20
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json25
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json35
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json37
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json131
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json56
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml37
-rw-r--r--mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql27
124 files changed, 8134 insertions, 1429 deletions
diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml
index dc665a9446..a3b9827d9f 100644
--- a/mso-api-handlers/mso-api-handler-infra/pom.xml
+++ b/mso-api-handlers/mso-api-handler-infra/pom.xml
@@ -88,6 +88,10 @@
</exclusions>
</dependency>
<dependency>
+ <groupId>org.springframework.retry</groupId>
+ <artifactId>spring-retry</artifactId>
+ </dependency>
+ <dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/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 77dbff9ebb..d0302f2e59 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
@@ -20,9 +20,30 @@
package org.onap.so.apihandlerinfra;
-/*
- * Enum for Status values returned by API Handler to Tail-F
- */
+
public enum Action implements Actions {
- createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers
+ createInstance,
+ updateInstance,
+ deleteInstance,
+ configureInstance,
+ replaceInstance,
+ replaceInstanceRetainAssignments,
+ activateInstance,
+ deactivateInstance,
+ enablePort,
+ disablePort,
+ addRelationships,
+ removeRelationships,
+ inPlaceSoftwareUpdate,
+ applyUpdatedConfig,
+ completeTask,
+ assignInstance,
+ unassignInstance,
+ compareModel,
+ scaleInstance,
+ deactivateAndCloudDelete,
+ scaleOut,
+ recreateInstance,
+ addMembers,
+ removeMembers
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java
index bc1972a593..5beb4810ec 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,17 +21,18 @@
package org.onap.so.apihandlerinfra;
import java.util.concurrent.Executor;
-import org.springframework.beans.factory.annotation.Autowired;
+import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
+import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator;
@SpringBootApplication(scanBasePackages = {"org.onap"})
@EnableAsync
+@EnableScheduling
public class ApiHandlerApplication {
@Value("${mso.async.core-pool-size}")
@@ -53,6 +54,7 @@ public class ApiHandlerApplication {
public static void main(String[] args) {
SpringApplication.run(ApiHandlerApplication.class, args);
+ java.security.Security.setProperty("networkaddress.cache.ttl", "10");
System.getProperties().setProperty("mso.db", "MARIADB");
System.getProperties().setProperty("server.name", "Springboot");
setLogsDir();
@@ -69,4 +71,5 @@ public class ApiHandlerApplication {
executor.initialize();
return executor;
}
+
}
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
new file mode 100644
index 0000000000..e56eb422d8
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java
@@ -0,0 +1,180 @@
+package org.onap.so.apihandlerinfra;
+
+import java.security.GeneralSecurityException;
+import java.util.ArrayList;
+import java.util.Collections;
+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.so.utils.CryptoUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.core.env.Environment;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.retry.policy.SimpleRetryPolicy;
+import org.springframework.retry.support.RetryTemplate;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.ResourceAccessException;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+
+@Component
+public class CamundaRequestHandler {
+
+ private static Logger logger = LoggerFactory.getLogger(CamundaRequestHandler.class);
+
+ @Autowired
+ private RestTemplate restTemplate;
+
+ @Autowired
+ private Environment env;
+
+ public ResponseEntity<List<HistoricProcessInstanceEntity>> getCamundaProcessInstanceHistory(String requestId) {
+ RetryTemplate retryTemplate = setRetryTemplate();
+ String path = env.getProperty("mso.camunda.rest.history.uri") + requestId;
+ String targetUrl = env.getProperty("mso.camundaURL") + path;
+ HttpHeaders headers =
+ setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey"));
+
+ HttpEntity<?> requestEntity = new HttpEntity<>(headers);
+
+ 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 {
+ 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);
+ } else {
+ logger.info(
+ "Retry: {} of 3. Querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}",
+ context.getRetryCount(), processInstanceId, requestId);
+ }
+
+ return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity,
+ new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {});
+ });
+
+ } 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();
+ }
+ }
+
+ protected String getTaskName(String requestId) throws ContactCamundaException {
+ ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
+ ResponseEntity<List<HistoricActivityInstanceEntity>> activityResponse = null;
+ String processInstanceId = null;
+ try {
+ response = getCamundaProcessInstanceHistory(requestId);
+ } catch (RestClientException e) {
+ logger.error("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();
+ }
+
+ List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody();
+
+ if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) {
+ Collections.reverse(historicProcessInstanceList);
+ processInstanceId = historicProcessInstanceList.get(0).getId();
+ } else {
+ return "No processInstances returned for requestId: " + requestId;
+ }
+
+ if (processInstanceId != null) {
+ activityResponse = getCamundaActivityHistory(processInstanceId, requestId);
+ } else {
+ return "No processInstanceId returned for requestId: " + requestId;
+ }
+
+ return getActivityName(activityResponse.getBody());
+ }
+
+ protected String getActivityName(List<HistoricActivityInstanceEntity> activityInstanceList) {
+ String activityName = null;
+ HistoricActivityInstanceEntity activityInstance = null;
+ String result = null;
+
+ if (activityInstanceList == null || activityInstanceList.isEmpty()) {
+ result = "No results returned on activityInstance history lookup.";
+ } else {
+ activityInstance = activityInstanceList.get(0);
+ activityName = activityInstance.getActivityName();
+
+ if (activityName == null) {
+ result = "Task name is null.";
+ } else {
+ result = "Last task executed: " + activityName;
+ }
+ }
+
+ return result;
+ }
+
+ protected HttpHeaders setCamundaHeaders(String auth, String msoKey) {
+ HttpHeaders headers = new HttpHeaders();
+ List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>();
+ acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
+ headers.setAccept(acceptableMediaTypes);
+ try {
+ String userCredentials = CryptoUtils.decrypt(auth, msoKey);
+ if (userCredentials != null) {
+ headers.add(HttpHeaders.AUTHORIZATION,
+ "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
+ }
+ } catch (GeneralSecurityException e) {
+ logger.error("Security exception", e);
+ }
+ return headers;
+ }
+
+ protected RetryTemplate setRetryTemplate() {
+ RetryTemplate retryTemplate = new RetryTemplate();
+ Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
+ retryableExceptions.put(ResourceAccessException.class, true);
+ SimpleRetryPolicy policy = new SimpleRetryPolicy(4, retryableExceptions);
+ retryTemplate.setRetryPolicy(policy);
+ return retryTemplate;
+ }
+}
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 449aa4ba3f..d3a279fd8e 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
@@ -38,6 +38,7 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
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.json.JSONObject;
@@ -55,6 +56,7 @@ import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.GetE2EServiceInstance
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
+import org.onap.so.constants.Status;
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.beans.ServiceRecipe;
import org.onap.so.db.catalog.client.CatalogDbClient;
@@ -90,6 +92,8 @@ public class E2EServiceInstances {
private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
+ private static final String SERVICE_ID = "serviceId";
+
@Autowired
private MsoRequest msoRequest;
@@ -136,9 +140,9 @@ public class E2EServiceInstances {
public Response updateE2EServiceInstance(String request, @PathParam("version") String version,
@PathParam("serviceId") String serviceId) throws ApiException {
- instanceIdMap.put("serviceId", serviceId);
+ instanceIdMap.put(SERVICE_ID, serviceId);
- return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap, version);
+ return updateE2EserviceInstances(request, Action.updateInstance, version);
}
/**
@@ -153,9 +157,9 @@ public class E2EServiceInstances {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
public Response deleteE2EServiceInstance(String request, @PathParam("version") String version,
- @PathParam("serviceId") String serviceId) throws ApiException {
+ @PathParam(SERVICE_ID) String serviceId) throws ApiException {
- instanceIdMap.put("serviceId", serviceId);
+ instanceIdMap.put(SERVICE_ID, serviceId);
return deleteE2EserviceInstances(request, Action.deleteInstance, instanceIdMap, version);
}
@@ -165,7 +169,7 @@ public class E2EServiceInstances {
@ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId",
response = Response.class)
@Produces(MediaType.APPLICATION_JSON)
- public Response getE2EServiceInstances(@PathParam("serviceId") String serviceId,
+ public Response getE2EServiceInstances(@PathParam(SERVICE_ID) String serviceId,
@PathParam("version") String version, @PathParam("operationId") String operationId) {
return getE2EServiceInstance(serviceId, operationId, version);
}
@@ -182,11 +186,11 @@ public class E2EServiceInstances {
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Scale E2E Service Instance on a specified version", response = Response.class)
public Response scaleE2EServiceInstance(String request, @PathParam("version") String version,
- @PathParam("serviceId") String serviceId) throws ApiException {
+ @PathParam(SERVICE_ID) String serviceId) throws ApiException {
logger.debug("------------------scale begin------------------");
- instanceIdMap.put("serviceId", serviceId);
- return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version);
+ instanceIdMap.put(SERVICE_ID, serviceId);
+ return scaleE2EserviceInstances(request, Action.scaleInstance, version);
}
/**
@@ -205,7 +209,7 @@ public class E2EServiceInstances {
public Response compareModelwithTargetVersion(String request, @PathParam("serviceId") String serviceId,
@PathParam("version") String version) throws ApiException {
- instanceIdMap.put("serviceId", serviceId);
+ instanceIdMap.put(SERVICE_ID, serviceId);
return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version);
}
@@ -214,7 +218,6 @@ public class E2EServiceInstances {
HashMap<String, String> instanceIdMap, String version) throws ApiException {
String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
CompareModelsRequest e2eCompareModelReq;
@@ -228,19 +231,19 @@ public class E2EServiceInstances {
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString());
return response;
}
- return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, startTime, action, version);
+ return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, action, version);
}
private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, String requestJSON,
- String requestId, long startTime, Action action, String version) throws ApiException {
+ String requestId, Action action, String version) throws ApiException {
// Define RecipeLookupResult info here instead of query DB for efficiency
String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance";
@@ -249,8 +252,6 @@ public class E2EServiceInstances {
RequestClient requestClient;
HttpResponse response;
- long subStartTime = System.currentTimeMillis();
-
try {
requestClient = requestClientFactory.getRequestClient(workflowUrl);
@@ -259,7 +260,7 @@ public class E2EServiceInstances {
// Capture audit event
logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- String serviceId = instanceIdMap.get("serviceId");
+ String serviceId = instanceIdMap.get(SERVICE_ID);
String serviceType = e2eCompareModelReq.getServiceType();
RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
.setBaseVfModule(false).setRecipeTimeout(recipeTimeout).setRequestAction(action.name())
@@ -280,8 +281,8 @@ public class E2EServiceInstances {
Response resp =
msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
"bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
return resp;
}
@@ -289,8 +290,7 @@ public class E2EServiceInstances {
ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
- version);
+ return beplStatusUpdate(requestClient, respHandler, bpelStatus, version);
}
private Response getE2EServiceInstance(String serviceId, String operationId, String version) {
@@ -299,14 +299,12 @@ public class E2EServiceInstances {
String apiVersion = version.substring(1);
- long startTime = System.currentTimeMillis();
-
OperationStatus operationStatus;
try {
operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
ErrorCode.AvailabilityError.getValue(),
"Exception while communciate with Request DB - Infra Request Lookup", e);
Response response =
@@ -321,8 +319,8 @@ public class E2EServiceInstances {
Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT,
MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB",
ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(),
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(),
"Null response from RequestDB when searching by serviceId");
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
@@ -337,7 +335,6 @@ public class E2EServiceInstances {
private Response deleteE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
String version) throws ApiException {
// TODO should be a new one or the same service instance Id
- long startTime = System.currentTimeMillis();
E2EServiceInstanceDeleteRequest e2eDelReq;
ObjectMapper mapper = new ObjectMapper();
@@ -350,8 +347,8 @@ public class E2EServiceInstances {
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
return response;
}
@@ -375,8 +372,8 @@ public class E2EServiceInstances {
return response;
}
if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB");
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
MsoException.ServiceException, "Recipe does not exist in catalog DB",
ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
@@ -390,7 +387,6 @@ public class E2EServiceInstances {
RequestClient requestClient;
HttpResponse response;
- long subStartTime = System.currentTimeMillis();
try {
requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
@@ -401,7 +397,7 @@ public class E2EServiceInstances {
// Capture audit event
logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- String serviceId = instanceIdMap.get("serviceId");
+ String serviceId = instanceIdMap.get(SERVICE_ID);
String serviceInstanceType = e2eDelReq.getServiceType();
RequestClientParameter clientParam = new RequestClientParameter.Builder().setRequestId(requestId)
.setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
@@ -414,8 +410,9 @@ public class E2EServiceInstances {
Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(),
+ "Exception while communicate with BPMN engine");
logger.debug("End of the transaction, the final response is: " + resp.getEntity());
return resp;
}
@@ -424,8 +421,8 @@ public class E2EServiceInstances {
Response resp =
msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
"bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
}
@@ -433,17 +430,14 @@ public class E2EServiceInstances {
ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
- version);
+ return beplStatusUpdate(requestClient, respHandler, bpelStatus, version);
}
- private Response updateE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
- String version) throws ApiException {
+ private Response updateE2EserviceInstances(String requestJSON, Action action, String version) throws ApiException {
String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
E2EServiceInstanceRequest e2eSir;
- String serviceId = instanceIdMap.get("serviceId");
+ String serviceId = instanceIdMap.get(SERVICE_ID);
ObjectMapper mapper = new ObjectMapper();
try {
@@ -455,8 +449,8 @@ public class E2EServiceInstances {
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
return response;
}
@@ -473,8 +467,8 @@ public class E2EServiceInstances {
if (requestId != null) {
logger.debug("Logging failed message to the database");
}
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
return response;
}
@@ -483,7 +477,7 @@ public class E2EServiceInstances {
try {
recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
@@ -495,8 +489,8 @@ public class E2EServiceInstances {
}
if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB");
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
MsoException.ServiceException, "Recipe does not exist in catalog DB",
ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
@@ -510,7 +504,6 @@ public class E2EServiceInstances {
RequestClient requestClient;
HttpResponse response;
- long subStartTime = System.currentTimeMillis();
String sirRequestJson = convertToString(sir);
try {
@@ -530,8 +523,9 @@ public class E2EServiceInstances {
MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(),
+ "Exception while communicate with BPMN engine");
logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
return getBPMNResp;
@@ -541,8 +535,8 @@ public class E2EServiceInstances {
Response getBPMNResp =
msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
"bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
return getBPMNResp;
}
@@ -550,15 +544,13 @@ public class E2EServiceInstances {
ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- return beplStatusUpdate(serviceId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
- version);
+ return beplStatusUpdate(requestClient, respHandler, bpelStatus, version);
}
private Response processE2EserviceInstances(String requestJSON, Action action,
HashMap<String, String> instanceIdMap, String version) throws ApiException {
String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
E2EServiceInstanceRequest e2eSir;
MsoRequest msoRequest = new MsoRequest();
@@ -572,8 +564,8 @@ public class E2EServiceInstances {
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
return response;
}
@@ -590,8 +582,8 @@ public class E2EServiceInstances {
if (requestId != null) {
logger.debug("Logging failed message to the database");
}
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
return response;
}
@@ -600,7 +592,7 @@ public class E2EServiceInstances {
try {
recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
@@ -610,8 +602,8 @@ public class E2EServiceInstances {
}
if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB");
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
MsoException.ServiceException, "Recipe does not exist in catalog DB",
ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
@@ -621,11 +613,10 @@ public class E2EServiceInstances {
String serviceInstanceType = e2eSir.getService().getServiceType();
- String serviceId = "";
+ String serviceId = e2eSir.getService().getServiceId();
RequestClient requestClient;
HttpResponse response;
- long subStartTime = System.currentTimeMillis();
String sirRequestJson = convertToString(sir);
try {
@@ -644,8 +635,9 @@ public class E2EServiceInstances {
MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(),
+ "Exception while communicate with BPMN engine");
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
}
@@ -654,8 +646,8 @@ public class E2EServiceInstances {
Response resp =
msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
"bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
}
@@ -663,15 +655,12 @@ public class E2EServiceInstances {
ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
- version);
+ return beplStatusUpdate(requestClient, respHandler, bpelStatus, version);
}
- private Response scaleE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
- String version) throws ApiException {
+ private Response scaleE2EserviceInstances(String requestJSON, Action action, String version) throws ApiException {
String requestId = UUID.randomUUID().toString();
- long startTime = System.currentTimeMillis();
E2EServiceInstanceScaleRequest e2eScaleReq;
ObjectMapper mapper = new ObjectMapper();
@@ -684,8 +673,8 @@ public class E2EServiceInstances {
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
ErrorNumbers.SVC_BAD_PARAMETER, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.SchemaError.getValue(), requestJSON, e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.SchemaError.getValue(), requestJSON, e);
logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
return response;
}
@@ -695,7 +684,7 @@ public class E2EServiceInstances {
// TODO Get the service template model version uuid from AAI.
recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
@@ -708,8 +697,8 @@ public class E2EServiceInstances {
return response;
}
if (recipeLookupResult == null) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.DataError.getValue(), "No recipe found in DB");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.DataError.getValue(), "No recipe found in DB");
Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
MsoException.ServiceException, "Recipe does not exist in catalog DB",
@@ -723,7 +712,6 @@ public class E2EServiceInstances {
RequestClient requestClient;
HttpResponse response;
- long subStartTime = System.currentTimeMillis();
try {
requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
@@ -734,7 +722,7 @@ public class E2EServiceInstances {
// Capture audit event
logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
- String serviceId = instanceIdMap.get("serviceId");
+ String serviceId = instanceIdMap.get(SERVICE_ID);
String serviceInstanceType = e2eScaleReq.getService().getServiceType();
RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
.setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
@@ -747,8 +735,9 @@ public class E2EServiceInstances {
MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e);
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.AvailabilityError.getValue(),
+ "Exception while communicate with BPMN engine", e);
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
}
@@ -757,8 +746,8 @@ public class E2EServiceInstances {
Response resp =
msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
"bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
- ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(),
+ MSO_PROP_APIHANDLER_INFRA, ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
}
@@ -766,12 +755,10 @@ public class E2EServiceInstances {
ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
- version);
+ return beplStatusUpdate(requestClient, respHandler, bpelStatus, version);
}
- private Response beplStatusUpdate(String serviceId, long startTime, RequestClient requestClient,
- ResponseHandler respHandler, int bpelStatus, Action action, HashMap<String, String> instanceIdMap,
+ private Response beplStatusUpdate(RequestClient requestClient, ResponseHandler respHandler, int bpelStatus,
String version) {
String apiVersion = version.substring(1);
@@ -790,8 +777,8 @@ public class E2EServiceInstances {
Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
"Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version);
- logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
- ErrorCode.BusinessProcesssError.getValue(),
+ logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(),
+ requestClient.getUrl(), ErrorCode.BusinessProcesssError.getValue(),
"Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
return resp;
@@ -870,7 +857,6 @@ public class E2EServiceInstances {
ServiceInstancesRequest sir = new ServiceInstancesRequest();
- String returnString = null;
RequestDetails requestDetails = new RequestDetails();
ModelInfo modelInfo = new ModelInfo();
@@ -928,21 +914,14 @@ public class E2EServiceInstances {
// subscriptionServiceType
requestParameters.setSubscriptionServiceType("MOG");
- // Userparams
- // List<E2EUserParam> userParams;
- // userParams =
- // e2eSir.getService().getParameters().getRequestParameters().getUserParams();
+
List<Map<String, Object>> userParamList = new ArrayList<>();
Map<String, Object> userParamMap = new HashMap<>();
// complete json request updated in the camunda
userParamMap.put("UUIRequest", requestJSON);
userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
- // Map<String, String> userParamMap3 = null;
- // for (E2EUserParam userp : userParams) {
- // userParamMap.put(userp.getName(), userp.getValue());
- //
- // }
+
userParamList.add(userParamMap);
requestParameters.setUserParams(userParamList);
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 4d283f26b1..0379ae3578 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,10 +25,8 @@ package org.onap.so.apihandlerinfra;
import java.net.URI;
import java.util.Collections;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
+import java.util.List;
+import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import javax.ws.rs.DefaultValue;
@@ -41,14 +39,20 @@ 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;
@@ -58,45 +62,38 @@ import io.swagger.annotations.ApiOperation;
@Api(value = "/globalhealthcheck", description = "APIH Infra Global Health Check")
public class GlobalHealthcheckHandler {
private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class);
- private static final String CONTEXTPATH_PROPERTY = "management.context-path";
- private static final String PROPERTY_DOMAIN = "mso.health.endpoints";
- private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb";
- private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb";
- private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc";
- private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack";
- private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn";
- private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc";
- private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc";
- private static final String DEFAULT_PROPERTY_VALUE = "";
+ 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
@@ -107,29 +104,25 @@ public class GlobalHealthcheckHandler {
@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("{} {}", 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));
+ logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
+
+ 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());
@@ -148,70 +141,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 dd6050bf60..15572f2b39 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
@@ -33,6 +33,7 @@ import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
+import org.onap.so.constants.Status;
import org.onap.so.db.catalog.beans.Workflow;
import org.onap.so.db.catalog.client.CatalogDbClient;
import org.onap.so.db.request.beans.InfraActiveRequests;
@@ -104,19 +105,14 @@ public class InstanceManagement {
private Response processCustomWorkflowRequest(String requestJSON, Actions action,
HashMap<String, String> instanceIdMap, String version, String requestId,
ContainerRequestContext requestContext) throws ApiException {
- String serviceInstanceId = null;
- if (instanceIdMap != null) {
- serviceInstanceId = instanceIdMap.get("serviceInstanceId");
- }
+ String serviceInstanceId;
Boolean aLaCarte = true;
- long startTime = System.currentTimeMillis();
- ServiceInstancesRequest sir = null;
+ ServiceInstancesRequest sir;
String apiVersion = version.substring(1);
String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
- sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest,
- requestId, requestUri);
+ sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri);
String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
InfraActiveRequests currentActiveReq =
msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
@@ -149,16 +145,15 @@ public class InstanceManagement {
InfraActiveRequests dup = null;
boolean inProgress = false;
- dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope,
- currentActiveReq);
+ dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq);
if (dup != null) {
inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
}
if (dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
- msoRequest, null, requestScope, dup);
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope,
+ dup);
}
ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
@@ -201,7 +196,7 @@ public class InstanceManagement {
.setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
.setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId).setVnfId(vnfId)
.setServiceType(serviceInstanceType).setVnfType(vnfType)
- .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
+ .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, null, aLaCarte, action))
.setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
} catch (IOException e) {
ErrorLoggerInfo errorLoggerInfo =
@@ -221,7 +216,7 @@ public class InstanceManagement {
try {
recipeLookupResult = getCustomWorkflowUri(workflowUuid);
- } catch (IOException e) {
+ } catch (Exception e) {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
.errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
@@ -248,7 +243,7 @@ public class InstanceManagement {
return recipeLookupResult;
}
- private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException {
+ private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) {
String recipeUri = null;
Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java
index 67d6a0d1fc..e162a67680 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.
@@ -24,9 +24,18 @@ import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
-import org.onap.so.apihandler.filters.RequestUriFilter;
import org.onap.so.apihandler.filters.RequestIdFilter;
import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper;
+import org.onap.so.apihandlerinfra.infra.rest.Network;
+import org.onap.so.apihandlerinfra.infra.rest.ServiceInstance;
+import org.onap.so.apihandlerinfra.infra.rest.VfModules;
+import org.onap.so.apihandlerinfra.infra.rest.Vnf;
+import org.onap.so.apihandlerinfra.infra.rest.Volumes;
+import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.AAIEntityNotFoundMapper;
+import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.CloudConfigurationNotFoundMapper;
+import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.NoRecipeExceptionMapper;
+import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.RequestConflictMapper;
+import org.onap.so.apihandlerinfra.infra.rest.exception.mapper.WorkflowEngineConnectionMapper;
import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration;
import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration;
import org.onap.so.apihandlerinfra.tenantisolation.ModelDistributionRequest;
@@ -41,8 +50,6 @@ import io.swagger.jaxrs.listing.SwaggerSerializers;
@ApplicationPath("/")
public class JerseyConfiguration extends ResourceConfig {
-
-
@PostConstruct
public void setUp() {
register(GlobalHealthcheckHandler.class);
@@ -52,6 +59,11 @@ public class JerseyConfiguration extends ResourceConfig {
register(CloudOrchestration.class);
register(CloudResourcesOrchestration.class);
register(OrchestrationRequests.class);
+ register(VfModules.class);
+ register(Vnf.class);
+ register(Network.class);
+ register(Volumes.class);
+ register(ServiceInstance.class);
register(JaxRsFilterLogging.class);
register(ManualTasks.class);
register(TasksHandler.class);
@@ -59,11 +71,16 @@ public class JerseyConfiguration extends ResourceConfig {
register(SwaggerSerializers.class);
register(ApiExceptionMapper.class);
register(RuntimeExceptionMapper.class);
- register(RequestUriFilter.class);
register(RequestIdFilter.class);
register(E2EServiceInstances.class);
register(WorkflowSpecificationsHandler.class);
register(InstanceManagement.class);
+ register(ResumeOrchestrationRequest.class);
+ register(AAIEntityNotFoundMapper.class);
+ register(CloudConfigurationNotFoundMapper.class);
+ register(NoRecipeExceptionMapper.class);
+ register(RequestConflictMapper.class);
+ register(WorkflowEngineConnectionMapper.class);
// this registration seems to be needed to get predictable
// execution behavior for the above JSON Exception Mappers
register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class);
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java
index 3c06804594..b9b7fcc0d4 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,6 +34,7 @@ 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;
@@ -49,7 +50,6 @@ import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference;
import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
import org.onap.so.apihandlerinfra.tasksbeans.Value;
import org.onap.so.apihandlerinfra.tasksbeans.Variables;
-import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
@@ -91,8 +91,7 @@ public class ManualTasks {
@PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException {
String requestId = requestContext.getProperty("requestId").toString();
- logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
- long startTime = System.currentTimeMillis();
+ logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
logger.debug("requestId is: {}", requestId);
TasksRequest taskRequest = null;
String apiVersion = version.substring(1);
@@ -139,9 +138,6 @@ public class ManualTasks {
throw validateException;
}
- // Create Request Record
- InfraActiveRequests currentActiveReq =
- msoRequest.createRequestObject(taskRequest, Action.completeTask, requestId, Status.PENDING, request);
// Transform the request to Camunda-style Complete request
Variables variablesForComplete = new Variables();
@@ -155,7 +151,7 @@ public class ManualTasks {
variablesForComplete.setResponseValue(responseValue);
variablesForComplete.setRequestorId(requestorIdValue);
- String camundaJsonReq = null;
+ String camundaJsonReq;
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
@@ -174,9 +170,8 @@ public class ManualTasks {
throw validateException;
}
- RequestClient requestClient = null;
- HttpResponse response = null;
- long subStartTime = System.currentTimeMillis();
+ RequestClient requestClient;
+ HttpResponse response;
String requestUrl = taskUri + "/" + taskId + "/complete";
try {
requestClient = reqClientFactory.getRequestClient(requestUrl);
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 277675f310..4bcc0d4111 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
@@ -25,14 +25,12 @@ package org.onap.so.apihandlerinfra;
import java.io.IOException;
import java.io.StringWriter;
-import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Optional;
import java.util.StringTokenizer;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
@@ -44,13 +42,13 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.onap.so.apihandler.common.ResponseBuilder;
import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
-import org.onap.so.apihandlerinfra.validation.MembersValidation;
import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation;
import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation;
import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation;
import org.onap.so.apihandlerinfra.validation.CustomWorkflowValidation;
import org.onap.so.apihandlerinfra.validation.InPlaceSoftwareUpdateValidation;
import org.onap.so.apihandlerinfra.validation.InstanceIdMapValidation;
+import org.onap.so.apihandlerinfra.validation.MembersValidation;
import org.onap.so.apihandlerinfra.validation.ModelInfoValidation;
import org.onap.so.apihandlerinfra.validation.PlatformLOBValidation;
import org.onap.so.apihandlerinfra.validation.ProjectOwningEntityValidation;
@@ -65,12 +63,11 @@ import org.onap.so.apihandlerinfra.validation.ValidationRule;
import org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType;
import org.onap.so.apihandlerinfra.vnfbeans.VnfInputs;
import org.onap.so.apihandlerinfra.vnfbeans.VnfRequest;
+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.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.InstanceDirection;
import org.onap.so.serviceinstancebeans.ModelInfo;
@@ -151,8 +148,7 @@ public class MsoRequest {
mapper.setSerializationInclusion(Include.NON_DEFAULT);
requestErrorStr = mapper.writeValueAsString(re);
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(),
- "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
+ logger.error("Exception in buildServiceErrorResponse writing exceptionType to string ", e);
}
return builder.buildResponse(httpResponseCode, null, requestErrorStr, version);
@@ -396,8 +392,7 @@ public class MsoRequest {
aq.setRequestStatus(status.toString());
aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
- "Exception when creation record request", e);
+ logger.error("Exception when creation record request", e);
if (!status.equals(Status.FAILED)) {
throw e;
@@ -437,8 +432,7 @@ public class MsoRequest {
aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
- "Exception when creation record request", e);
+ logger.error("Exception when creation record request", e);
if (!status.equals(Status.FAILED)) {
throw e;
@@ -465,8 +459,7 @@ public class MsoRequest {
request.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
requestsDbClient.save(request);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
- ErrorCode.DataError.getValue(), "Exception when updating record in DB");
+ logger.error("Exception when updating record in DB", e);
logger.debug("Exception: ", e);
}
}
@@ -547,8 +540,7 @@ public class MsoRequest {
return null;
} catch (Exception e) {
- logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(),
- "Exception in domToStr", e);
+ logger.error("Exception in domToStr", e);
}
return null;
}
@@ -574,7 +566,7 @@ public class MsoRequest {
throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
- // mapper.configure(Feature.WRAP_ROOT_VALUE, true);
+
logger.debug("building sir from object {}", sir);
String requestJSON = mapper.writeValueAsString(sir);
@@ -636,7 +628,7 @@ public class MsoRequest {
public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {
String serviceInstanceType = null;
- String networkType = null;
+
String vnfType = null;
String vfModuleType = null;
String vfModuleModelName = null;
@@ -785,22 +777,4 @@ public class MsoRequest {
}
- public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
- Optional<URL> selfLinkUrl = Optional.empty();
- String version = "";
- try {
- URL aUrl = new URL(url);
- String aPath = aUrl.getPath();
- if (aPath.indexOf("/v") == -1) {
- version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4);
- } else {
- version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4);
- }
- String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
- selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
- } catch (Exception e) {
- selfLinkUrl = Optional.empty(); // ignore
- }
- return selfLinkUrl;
- }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java
index 9810895ad9..3337c62afd 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
@@ -30,6 +30,7 @@ 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;
@@ -57,7 +58,7 @@ public class NodeHealthcheckHandler {
public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException {
// Generated RequestId
String requestId = requestContext.getProperty("requestId").toString();
- logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
+ logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
return HEALTH_CHECK_RESPONSE;
}
}
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 34dcd4b0c4..8896e93175 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
@@ -35,24 +35,30 @@ import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.EnumUtils;
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandler.common.ResponseBuilder;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
+import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
+import org.onap.so.constants.OrchestrationRequestFormat;
+import org.onap.so.constants.Status;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.beans.RequestProcessingData;
import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.logger.ErrorCode;
import org.onap.so.logger.MessageEnum;
+import org.onap.so.serviceinstancebeans.CloudRequestData;
import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse;
import org.onap.so.serviceinstancebeans.GetOrchestrationResponse;
import org.onap.so.serviceinstancebeans.InstanceReferences;
@@ -61,6 +67,7 @@ import org.onap.so.serviceinstancebeans.RequestDetails;
import org.onap.so.serviceinstancebeans.RequestList;
import org.onap.so.serviceinstancebeans.RequestStatus;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.onap.so.utils.UUIDChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -69,13 +76,14 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
+
@Path("onap/so/infra/orchestrationRequests")
@Api(value = "onap/so/infra/orchestrationRequests", description = "API Requests for Orchestration requests")
@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;
@@ -86,20 +94,32 @@ public class OrchestrationRequests {
@Autowired
private ResponseBuilder builder;
+ @Autowired
+ private CamundaRequestHandler camundaRequestHandler;
+
@GET
@Path("/{version:[vV][4-7]}/{requestId}")
@ApiOperation(value = "Find Orchestrated Requests for a given requestId", response = Response.class)
@Produces(MediaType.APPLICATION_JSON)
@Transactional
public Response getOrchestrationRequest(@PathParam("requestId") String requestId,
- @PathParam("version") String version) throws ApiException {
+ @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest,
+ @QueryParam(value = "format") String format) throws ApiException {
String apiVersion = version.substring(1);
GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse();
-
InfraActiveRequests infraActiveRequest = null;
List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null;
+
+ if (!UUIDChecker.isValidUUID(requestId)) {
+
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MODIFIED_BY_APIHANDLER).build();
+ 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);
@@ -109,14 +129,11 @@ public class OrchestrationRequests {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build();
-
-
ValidateException validateException =
new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup",
HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e)
.errorInfo(errorLoggerInfo).build();
-
throw validateException;
}
@@ -126,7 +143,6 @@ public class OrchestrationRequests {
ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
ErrorCode.BusinessProcesssError).build();
-
ValidateException validateException =
new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
@@ -135,7 +151,8 @@ public class OrchestrationRequests {
throw validateException;
}
- Request request = mapInfraActiveRequestToRequest(infraActiveRequest);
+ Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest, format);
+
if (!requestProcessingData.isEmpty()) {
request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
}
@@ -150,16 +167,15 @@ public class OrchestrationRequests {
@ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class)
@Produces(MediaType.APPLICATION_JSON)
@Transactional
- public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version)
+ public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version,
+ @QueryParam("includeCloudRequest") boolean includeCloudRequest, @QueryParam(value = "format") String format)
throws ApiException {
- long startTime = System.currentTimeMillis();
-
MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
- List<InfraActiveRequests> activeRequests = null;
+ List<InfraActiveRequests> activeRequests;
- GetOrchestrationListResponse orchestrationList = null;
+ GetOrchestrationListResponse orchestrationList;
Map<String, List<String>> orchestrationMap;
String apiVersion = version.substring(1);
@@ -188,7 +204,8 @@ public class OrchestrationRequests {
List<RequestProcessingData> requestProcessingData =
requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId());
RequestList requestList = new RequestList();
- Request request = mapInfraActiveRequestToRequest(infraActive);
+ Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest, format);
+
if (!requestProcessingData.isEmpty()) {
request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData));
}
@@ -200,7 +217,6 @@ public class OrchestrationRequests {
return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
}
-
@POST
@Path("/{version: [vV][4-7]}/{requestId}/unlock")
@Consumes(MediaType.APPLICATION_JSON)
@@ -210,12 +226,10 @@ public class OrchestrationRequests {
public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId,
@PathParam("version") String version) throws ApiException {
- long startTime = System.currentTimeMillis();
logger.debug("requestId is: {}", requestId);
- ServiceInstancesRequest sir = null;
+ ServiceInstancesRequest sir;
- InfraActiveRequests infraActiveRequest = null;
- Request request = null;
+ InfraActiveRequests infraActiveRequest;
try {
ObjectMapper mapper = new ObjectMapper();
@@ -251,7 +265,6 @@ public class OrchestrationRequests {
ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
ErrorCode.BusinessProcesssError).build();
-
ValidateException validateException =
new ValidateException.Builder("Null response from RequestDB when searching by RequestId",
HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
@@ -261,9 +274,10 @@ public class OrchestrationRequests {
} else {
String status = infraActiveRequest.getRequestStatus();
- if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING")
- || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) {
- infraActiveRequest.setRequestStatus("UNLOCKED");
+ 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);
@@ -273,7 +287,6 @@ public class OrchestrationRequests {
new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
.build();
-
ValidateException validateException = new ValidateException.Builder(
"Orchestration RequestId " + requestId + " has a status of " + status
+ " and can not be unlocked",
@@ -286,8 +299,8 @@ public class OrchestrationRequests {
return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build();
}
- private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
-
+ protected Request mapInfraActiveRequestToRequest(InfraActiveRequests iar, boolean includeCloudRequest,
+ String format) throws ApiException {
String requestBody = iar.getRequestBody();
Request request = new Request();
@@ -296,10 +309,11 @@ public class OrchestrationRequests {
request.setRequestId(iar.getRequestId());
request.setRequestScope(iar.getRequestScope());
request.setRequestType(iar.getRequestAction());
- String rollbackStatusMessage = iar.getRollbackStatusMessage();
- String flowStatusMessage = iar.getFlowStatus();
- String retryStatusMessage = iar.getRetryStatusMessage();
+ String originalRequestId = iar.getOriginalRequestId();
+ if (originalRequestId != null) {
+ request.setOriginalRequestId(originalRequestId);
+ }
InstanceReferences ir = new InstanceReferences();
if (iar.getNetworkId() != null)
@@ -329,8 +343,6 @@ public class OrchestrationRequests {
if (iar.getInstanceGroupName() != null)
ir.setInstanceGroupName(iar.getInstanceGroupName());
-
-
request.setInstanceReferences(ir);
RequestDetails requestDetails = null;
@@ -367,52 +379,125 @@ public class OrchestrationRequests {
String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
request.setFinishTime(endTimeStamp);
}
- String statusMessages = null;
+
RequestStatus status = new RequestStatus();
- if (iar.getStatusMessage() != null) {
- statusMessages = "STATUS: " + iar.getStatusMessage();
+
+ if (iar.getModifyTime() != null) {
+ String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT";
+ status.setTimeStamp(timeStamp);
}
- if (flowStatusMessage != null) {
- if (statusMessages != null) {
- statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage;
+
+ status.setRequestState(mapRequestStatusToRequest(iar, format));
+
+ if (iar.getProgress() != null) {
+ status.setPercentProgress(iar.getProgress().intValue());
+ }
+
+ if (iar.getCloudApiRequests() != null && !iar.getCloudApiRequests().isEmpty() && includeCloudRequest) {
+ iar.getCloudApiRequests().stream().forEach(cloudRequest -> {
+ try {
+ request.getCloudRequestData()
+ .add(new CloudRequestData(mapper.readValue(cloudRequest.getRequestBody(), Object.class),
+ cloudRequest.getCloudIdentifier()));
+ } catch (Exception e) {
+ logger.error("Error reading Cloud Request", e);
+ }
+ });
+ }
+
+ mapRequestStatusAndExtSysErrSrcToRequest(iar, status, format);
+
+ request.setRequestStatus(status);
+ return request;
+ }
+
+ protected String mapRequestStatusToRequest(InfraActiveRequests iar, String format) {
+ if (iar.getRequestStatus() != null) {
+ boolean requestFormat = false;
+ if (format != null) {
+ requestFormat = EnumUtils.isValidEnum(OrchestrationRequestFormat.class, format.toUpperCase());
+ }
+ if (requestFormat) {
+ return iar.getRequestStatus();
} else {
- statusMessages = "FLOW STATUS: " + flowStatusMessage;
+ if (Status.ABORTED.toString().equalsIgnoreCase(iar.getRequestStatus())
+ || Status.ROLLED_BACK.toString().equalsIgnoreCase(iar.getRequestStatus())
+ || Status.ROLLED_BACK_TO_ASSIGNED.toString().equalsIgnoreCase(iar.getRequestStatus())
+ || Status.ROLLED_BACK_TO_CREATED.toString().equalsIgnoreCase(iar.getRequestStatus())) {
+ return Status.FAILED.toString();
+ } else {
+ return iar.getRequestStatus();
+ }
}
}
- if (retryStatusMessage != null) {
- if (statusMessages != null) {
- statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage;
- } else {
- statusMessages = "RETRY STATUS: " + retryStatusMessage;
+ return null;
+ }
+
+ protected void mapRequestStatusAndExtSysErrSrcToRequest(InfraActiveRequests iar, RequestStatus status,
+ String format) throws ContactCamundaException {
+ String rollbackStatusMessage = iar.getRollbackStatusMessage();
+ String flowStatusMessage = iar.getFlowStatus();
+ String retryStatusMessage = iar.getRetryStatusMessage();
+ String taskName = null;
+
+ if (flowStatusMessage != null && !flowStatusMessage.equals("Successfully completed all Building Blocks")
+ && !flowStatusMessage.equals("All Rollback flows have completed successfully")) {
+ taskName = camundaRequestHandler.getTaskName(iar.getRequestId());
+ if (taskName != null) {
+ flowStatusMessage = flowStatusMessage + " TASK INFORMATION: " + taskName;
}
}
- if (rollbackStatusMessage != null) {
- if (statusMessages != null) {
- statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage;
+
+ String statusMessages = null;
+ if (iar.getStatusMessage() != null) {
+ if (StringUtils.isNotBlank(iar.getExtSystemErrorSource())) {
+ statusMessages = "STATUS: "
+ + String.format(ERROR_MESSAGE_PREFIX, iar.getExtSystemErrorSource(), iar.getStatusMessage());
} else {
- statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage;
+ statusMessages = "STATUS: " + iar.getStatusMessage();
}
}
- if (statusMessages != null) {
- status.setStatusMessage(statusMessages);
- }
- if (iar.getModifyTime() != null) {
- String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT";
- status.setTimeStamp(timeStamp);
- }
+ if (OrchestrationRequestFormat.STATUSDETAIL.toString().equalsIgnoreCase(format)) {
+ if (flowStatusMessage != null) {
+ status.setFlowStatus(flowStatusMessage);
+ }
+ if (retryStatusMessage != null) {
+ status.setRetryStatusMessage(retryStatusMessage);
+ }
+ if (rollbackStatusMessage != null) {
+ status.setRollbackStatusMessage(rollbackStatusMessage);
+ }
+ status.setExtSystemErrorSource(iar.getExtSystemErrorSource());
+ status.setRollbackExtSystemErrorSource(iar.getRollbackExtSystemErrorSource());
+ } else {
- if (iar.getRequestStatus() != null) {
- status.setRequestState(iar.getRequestStatus());
+ if (flowStatusMessage != null) {
+ if (statusMessages != null) {
+ statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage;
+ } else {
+ statusMessages = "FLOW STATUS: " + flowStatusMessage;
+ }
+ }
+ if (retryStatusMessage != null) {
+ if (statusMessages != null) {
+ statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage;
+ } else {
+ statusMessages = "RETRY STATUS: " + retryStatusMessage;
+ }
+ }
+ if (rollbackStatusMessage != null) {
+ if (statusMessages != null) {
+ statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage;
+ } else {
+ statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage;
+ }
+ }
}
- if (iar.getProgress() != null) {
- status.setPercentProgress(iar.getProgress().intValue());
+ if (statusMessages != null) {
+ status.setStatusMessage(statusMessages);
}
-
- request.setRequestStatus(status);
-
- return request;
}
public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData(
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
index bbcc120ab6..2fddfd9a95 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
@@ -24,8 +24,18 @@
package org.onap.so.apihandlerinfra;
-import com.fasterxml.jackson.annotation.JsonInclude.Include;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
+import java.io.IOException;
+import java.net.URL;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
@@ -47,7 +57,11 @@ import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
+import org.onap.so.apihandlerinfra.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.VfModule;
import org.onap.so.db.catalog.client.CatalogDbClient;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.client.RequestsDbClient;
@@ -55,44 +69,28 @@ 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.ModelInfo;
import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.RelatedInstance;
import org.onap.so.serviceinstancebeans.RelatedInstanceList;
import org.onap.so.serviceinstancebeans.RequestParameters;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
-import org.onap.so.utils.CryptoUtils;
import org.onap.so.utils.UUIDChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.env.Environment;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpStatusCodeException;
-import org.springframework.web.client.RestTemplate;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.xml.bind.DatatypeConverter;
-import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
-import java.io.IOException;
-import java.net.URL;
-import java.security.GeneralSecurityException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+import org.springframework.web.client.RestClientException;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+import com.fasterxml.jackson.databind.ObjectMapper;
@Component
-public class RequestHandlerUtils {
+public class RequestHandlerUtils extends AbstractRestHandler {
private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
@@ -114,7 +112,7 @@ public class RequestHandlerUtils {
private MsoRequest msoRequest;
@Autowired
- private RestTemplate restTemplate;
+ private CamundaRequestHandler camundaRequestHandler;
@Autowired
private CatalogDbClient catalogDbClient;
@@ -180,8 +178,8 @@ public class RequestHandlerUtils {
ObjectMapper mapper = new ObjectMapper();
jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
- Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(),
- requestClientParameter.getRequestId());
+ Optional<URL> selfLinkUrl =
+ buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
if (selfLinkUrl.isPresent()) {
jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
} else {
@@ -293,12 +291,11 @@ public class RequestHandlerUtils {
return requestUri;
}
- public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
- MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
- throws ApiException {
+ public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap,
+ String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
InfraActiveRequests dup = null;
try {
- if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance
+ if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
|| action == Action.activateInstance || action == Action.assignInstance))) {
dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
}
@@ -319,30 +316,25 @@ public class RequestHandlerUtils {
public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq)
throws RequestDbFailureException, ContactCamundaException {
String requestId = duplicateRecord.getRequestId();
- String path = env.getProperty("mso.camunda.rest.history.uri") + requestId;
- String targetUrl = env.getProperty("mso.camundaURL") + path;
- HttpHeaders headers =
- setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey"));
- HttpEntity<?> requestEntity = new HttpEntity<>(headers);
ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
try {
- response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity,
- new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {});
- } catch (HttpStatusCodeException e) {
- ErrorLoggerInfo errorLoggerInfo =
- new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
- .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId);
+ } catch (RestClientException e) {
+ logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}",
+ requestId, e.getMessage());
ContactCamundaException contactCamundaException =
- new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
- ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ new ContactCamundaException.Builder("process-instance", requestId, e.toString(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
+ .build();
updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage());
throw contactCamundaException;
}
+
if (response.getBody().isEmpty()) {
updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
}
for (HistoricProcessInstance instance : response.getBody()) {
- if (instance.getState().equals("ACTIVE")) {
+ if (("ACTIVE").equals(instance.getState())) {
return true;
} else {
updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
@@ -351,26 +343,8 @@ public class RequestHandlerUtils {
return false;
}
- protected HttpHeaders setCamundaHeaders(String auth, String msoKey) {
- HttpHeaders headers = new HttpHeaders();
- List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>();
- acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
- headers.setAccept(acceptableMediaTypes);
- try {
- String userCredentials = CryptoUtils.decrypt(auth, msoKey);
- if (userCredentials != null) {
- headers.add(HttpHeaders.AUTHORIZATION,
- "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
- }
- } catch (GeneralSecurityException e) {
- logger.error("Security exception", e);
- }
- return headers;
- }
-
public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action,
- long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri)
- throws ApiException {
+ String requestId, String requestUri) throws ApiException {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(requestJSON, ServiceInstancesRequest.class);
@@ -415,8 +389,8 @@ public class RequestHandlerUtils {
}
public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action,
- HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName,
- String requestScope, InfraActiveRequests dup) throws ApiException {
+ HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup)
+ throws ApiException {
String instance = null;
if (instanceName != null) {
@@ -505,24 +479,11 @@ public class RequestHandlerUtils {
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) {
@@ -622,4 +583,107 @@ public class RequestHandlerUtils {
return requestScope;
}
+ protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest,
+ String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId,
+ String originalRequestId) throws ApiException {
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setRequestId(requestId);
+ request.setStartTime(startTimeStamp);
+ request.setSource(source);
+ request.setRequestUrl(requestUri);
+ request.setProgress(new Long(5));
+ request.setRequestorId(requestorId);
+ request.setRequestStatus(Status.IN_PROGRESS.toString());
+ request.setOriginalRequestId(originalRequestId);
+ request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ if (infraActiveRequest != null) {
+ request.setTenantId(infraActiveRequest.getTenantId());
+ request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId));
+ request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion());
+ request.setRequestScope(infraActiveRequest.getRequestScope());
+ request.setRequestAction(infraActiveRequest.getRequestAction());
+ setInstanceIdAndName(infraActiveRequest, request);
+ }
+ return request;
+ }
+
+ protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest,
+ InfraActiveRequests currentActiveRequest) throws ApiException {
+ String requestScope = infraActiveRequest.getRequestScope();
+ try {
+ ModelType type = ModelType.valueOf(requestScope);
+ String instanceName = type.getName(infraActiveRequest);
+ if (instanceName == null && type.equals(ModelType.vfModule)) {
+ logger.error("vfModule for requestId: {} being resumed does not have an instanceName.",
+ infraActiveRequest.getRequestId());
+ ValidateException validateException = new ValidateException.Builder(
+ "vfModule for requestId: " + infraActiveRequest.getRequestId()
+ + " being resumed does not have an instanceName.",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).build();
+ updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
+ throw validateException;
+ }
+ if (instanceName != null) {
+ type.setName(currentActiveRequest, instanceName);
+ }
+ type.setId(currentActiveRequest, type.getId(infraActiveRequest));
+ } catch (IllegalArgumentException e) {
+ logger.error(
+ "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.",
+ requestScope);
+ }
+ }
+
+ protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType,
+ String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException {
+ // Get VF Module-specific base module indicator
+ VfModule vfm = null;
+ String modelVersionId = modelInfo.getModelVersionId();
+ Boolean isBaseVfModule = false;
+
+ if (modelVersionId != null) {
+ vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
+ } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) {
+ vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(),
+ modelInfo.getModelVersion());
+ }
+
+ if (vfm != null) {
+ if (vfm.getIsBase()) {
+ isBaseVfModule = true;
+ }
+ } else if (action == Action.createInstance || action == Action.updateInstance) {
+ String serviceVersionText = "";
+ if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) {
+ serviceVersionText = " with version " + sdcServiceModelVersion;
+ }
+ String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName()
+ + serviceVersionText + " not found in MSO Catalog DB";
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage,
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage());
+ throw vfModuleException;
+ }
+ return isBaseVfModule;
+ }
+
+ protected ModelType getModelType(Actions action, ModelInfo modelInfo) {
+ if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
+ return ModelType.vnf;
+ } else if (action == Action.addMembers || action == Action.removeMembers) {
+ return ModelType.instanceGroup;
+ } else {
+ return modelInfo.getModelType();
+ }
+ }
+
+ protected String updateRequestorIdInRequestBody(InfraActiveRequests infraActiveRequest, String newRequestorId) {
+ String requestBody = infraActiveRequest.getRequestBody();
+ return requestBody.replaceAll(
+ "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))",
+ "$1" + newRequestorId + "$3");
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java
new file mode 100644
index 0000000000..ed300d95c2
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java
@@ -0,0 +1,277 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.apihandlerinfra;
+
+import java.io.IOException;
+import java.sql.Timestamp;
+import java.util.HashMap;
+import javax.transaction.Transactional;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.http.HttpStatus;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandler.common.RequestClientParameter;
+import org.onap.so.apihandlerinfra.exceptions.ApiException;
+import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
+import org.onap.so.apihandlerinfra.exceptions.ValidateException;
+import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
+import org.onap.so.constants.Status;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.logger.ErrorCode;
+import org.onap.so.logger.HttpHeadersConstants;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.logger.MdcConstants;
+import org.onap.so.logger.MessageEnum;
+import org.onap.so.serviceinstancebeans.ModelInfo;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.HttpClientErrorException;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+
+@Path("onap/so/infra/orchestrationRequests")
+@Api(value = "onap/so/infra/orchestrationRequests")
+@Component
+public class ResumeOrchestrationRequest {
+ private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class);
+ private static final String SAVE_TO_DB = "save instance to db";
+ private static String uriPrefix = "/orchestrationRequests/";
+
+ @Autowired
+ private RequestHandlerUtils requestHandlerUtils;
+
+ @Autowired
+ private ServiceInstances serviceInstances;
+
+ @Autowired
+ private RequestsDbClient requestsDbClient;
+
+ @Autowired
+ private MsoRequest msoRequest;
+
+ @POST
+ @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)
+ @Transactional
+ public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId,
+ @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException {
+
+ Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+ String currentRequestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
+ logger.info("Beginning resume operation for new request: {}", currentRequestId);
+ InfraActiveRequests infraActiveRequest = null;
+ String source = MDC.get(MdcConstants.ORIGINAL_PARTNER_NAME);
+ String requestorId = MDC.get(HttpHeadersConstants.REQUESTOR_ID);
+ requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
+ String requestUri = MDC.get(LogConstants.HTTP_URL);
+ version = version.substring(1);
+
+ try {
+ infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
+ } catch (HttpClientErrorException e) {
+ logger.error("Error occurred while performing requestDb lookup by requestId: " + requestId, e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build();
+ throw new ValidateException.Builder("Exception while performing requestDb lookup by requestId",
+ HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ }
+
+ InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest(
+ infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId, requestId);
+
+ if (infraActiveRequest == null) {
+ logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId);
+ ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
+ ErrorCode.BusinessProcesssError).build();
+ ValidateException validateException = new ValidateException.Builder(
+ "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
+ requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
+ throw validateException;
+
+ }
+
+ return resumeRequest(infraActiveRequest, currentActiveRequest, version, requestUri);
+ }
+
+ protected Response resumeRequest(InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest,
+ String version, String requestUri) throws ApiException {
+ String requestBody = infraActiveRequest.getRequestBody();
+ Action action = Action.valueOf(infraActiveRequest.getRequestAction());
+ String requestId = currentActiveRequest.getRequestId();
+ String requestScope = infraActiveRequest.getRequestScope();
+ String instanceName = getInstanceName(infraActiveRequest, requestScope, currentActiveRequest);
+ HashMap<String, String> instanceIdMap = setInstanceIdMap(infraActiveRequest, requestScope);
+
+ checkForInProgressRequest(currentActiveRequest, instanceIdMap, requestScope, instanceName, action);
+
+ ServiceInstancesRequest sir = null;
+ sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri);
+ Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte();
+
+ String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir);
+ RecipeLookupResult recipeLookupResult = serviceInstances.getServiceInstanceOrchestrationURI(sir, action,
+ msoRequest.getAlacarteFlag(sir), currentActiveRequest);
+
+ requestDbSave(currentActiveRequest);
+
+ if (aLaCarte == null) {
+ aLaCarte = setALaCarteFlagIfNull(requestScope, action);
+ }
+
+ RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version,
+ infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir);
+
+ return requestHandlerUtils.postBPELRequest(currentActiveRequest, requestClientParameter,
+ recipeLookupResult.getOrchestrationURI(), requestScope);
+ }
+
+ protected Boolean setALaCarteFlagIfNull(String requestScope, Action action) {
+ Boolean aLaCarteFlag;
+ if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) {
+ aLaCarteFlag = true;
+ } else {
+ aLaCarteFlag = false;
+ }
+ return aLaCarteFlag;
+ }
+
+ protected HashMap<String, String> setInstanceIdMap(InfraActiveRequests infraActiveRequest, String requestScope) {
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ ModelType type;
+ try {
+ type = ModelType.valueOf(requestScope);
+ instanceIdMap.put(type.name() + "InstanceId", type.getId(infraActiveRequest));
+ } catch (IllegalArgumentException e) {
+ logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope);
+ }
+ return instanceIdMap;
+ }
+
+ protected String getInstanceName(InfraActiveRequests infraActiveRequest, String requestScope,
+ InfraActiveRequests currentActiveRequest) throws ValidateException, RequestDbFailureException {
+ ModelType type;
+ String instanceName = "";
+ try {
+ type = ModelType.valueOf(requestScope);
+ instanceName = type.getName(infraActiveRequest);
+ } catch (IllegalArgumentException e) {
+ logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope);
+ ValidateException validateException = new ValidateException.Builder(
+ "requestScope: \"" + requestScope + "\" from request: " + infraActiveRequest.getRequestId()
+ + " does not match a ModelType enum.",
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build();
+ requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
+ throw validateException;
+ }
+ return instanceName;
+ }
+
+ protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest,
+ HashMap<String, String> instanceIdMap, String requestScope, String instanceName, Action action)
+ throws ApiException {
+ boolean inProgress = false;
+ InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName,
+ requestScope, currentActiveRequest);
+ if (requestInProgress != null) {
+ inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest);
+ }
+ if (inProgress) {
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, instanceName,
+ requestScope, requestInProgress);
+ }
+ }
+
+ protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException {
+ try {
+ requestsDbClient.save(currentActiveRequest);
+ } catch (Exception e) {
+ logger.error("Exception while saving request to requestDb", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
+ }
+ }
+
+ protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version,
+ InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId,
+ Boolean aLaCarte, ServiceInstancesRequest sir) throws ApiException {
+ RequestClientParameter requestClientParameter = null;
+ Action action = Action.valueOf(infraActiveRequest.getRequestAction());
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+
+ Boolean isBaseVfModule = false;
+ if (requestHandlerUtils.getModelType(action, modelInfo).equals(ModelType.vfModule)) {
+ isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, infraActiveRequest.getVnfType(),
+ msoRequest.getSDCServiceModelVersion(sir), currentActiveRequest);
+ }
+
+ try {
+ requestClientParameter =
+ new RequestClientParameter.Builder().setRequestId(currentActiveRequest.getRequestId())
+ .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
+ .setRequestAction(infraActiveRequest.getRequestAction())
+ .setServiceInstanceId(infraActiveRequest.getServiceInstanceId())
+ .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId())
+ .setVfModuleId(infraActiveRequest.getVfModuleId())
+ .setVolumeGroupId(infraActiveRequest.getVolumeGroupId())
+ .setNetworkId(infraActiveRequest.getNetworkId())
+ .setServiceType(infraActiveRequest.getServiceType())
+ .setVnfType(infraActiveRequest.getVnfType())
+ .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope(),
+ action, Integer.parseInt(version)))
+ .setNetworkType(infraActiveRequest.getNetworkType())
+ .setRequestDetails(requestHandlerUtils
+ .mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, aLaCarte, action))
+ .setApiVersion(version).setALaCarte(aLaCarte)
+ .setRequestUri(currentActiveRequest.getRequestUrl())
+ .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build();
+ } catch (IOException e) {
+ logger.error("IOException while generating requestClientParameter to send to BPMN", e);
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new ValidateException.Builder(
+ "IOException while generating requestClientParameter to send to BPMN: " + e.getMessage(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+ .build();
+ }
+ return requestClientParameter;
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
index 931a1eb52b..9b72bdc608 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
@@ -23,12 +23,24 @@
package org.onap.so.apihandlerinfra;
-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 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;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.onap.so.apihandler.common.CommonConstants;
@@ -38,8 +50,10 @@ 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.exceptions.VfModuleNotFoundException;
+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;
@@ -74,29 +88,18 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
-import javax.transaction.Transactional;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+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;
@Component
@Path("/onap/so/infra/serviceInstantiation")
@Api(value = "/onap/so/infra/serviceInstantiation", description = "Infrastructure API Requests for Service Instances")
-public class ServiceInstances {
+public class ServiceInstances extends AbstractRestHandler {
private static Logger logger = LoggerFactory.getLogger(MsoRequest.class);
private static String NAME = "name";
@@ -108,6 +111,9 @@ public class ServiceInstances {
private Environment env;
@Autowired
+ private RestTemplate restTemplate;
+
+ @Autowired
private CatalogDbClient catalogDbClient;
@Autowired
@@ -119,6 +125,9 @@ public class ServiceInstances {
@Autowired
private RequestHandlerUtils requestHandlerUtils;
+ @Autowired
+ private RequestValidatorListenerRunner requestValidatorListenerRunner;
+
@POST
@Path("/{version:[vV][5-7]}/serviceInstances")
@Consumes(MediaType.APPLICATION_JSON)
@@ -203,7 +212,7 @@ public class ServiceInstances {
@PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
throws ApiException {
String requestId = requestHandlerUtils.getRequestId(requestContext);
- HashMap<String, String> instanceIdMap = new HashMap<String, String>();
+ HashMap<String, String> instanceIdMap = new HashMap<>();
instanceIdMap.put("serviceInstanceId", serviceInstanceId);
return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId,
requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
@@ -435,7 +444,6 @@ public class ServiceInstances {
requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
}
-
@DELETE
@Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}")
@Consumes(MediaType.APPLICATION_JSON)
@@ -584,7 +592,6 @@ public class ServiceInstances {
requestHandlerUtils.getRequestUri(requestContext, uriPrefix));
}
-
@POST
@Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups")
@Consumes(MediaType.APPLICATION_JSON)
@@ -757,16 +764,45 @@ public class ServiceInstances {
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 {
- String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId");
+ 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;
- long startTime = System.currentTimeMillis();
- ServiceInstancesRequest sir = null;
+ ServiceInstancesRequest sir;
String apiVersion = version.substring(1);
- sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest,
- requestId, requestUri);
+ 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);
@@ -797,16 +833,15 @@ public class ServiceInstances {
InfraActiveRequests dup = null;
boolean inProgress = false;
- dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,
- requestScope, currentActiveReq);
+ dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq);
if (dup != null) {
inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
}
if (dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
- msoRequest, instanceName, requestScope, dup);
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName,
+ requestScope, dup);
}
ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
@@ -815,64 +850,20 @@ public class ServiceInstances {
referencesResponse.setRequestId(requestId);
serviceResponse.setRequestReferences(referencesResponse);
- Boolean isBaseVfModule = false;
-
RecipeLookupResult recipeLookupResult =
getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq);
String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag);
- ModelType modelType;
- ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
- if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
- modelType = ModelType.vnf;
- } else if (action == Action.addMembers || action == Action.removeMembers) {
- modelType = ModelType.instanceGroup;
- } else {
- modelType = modelInfo.getModelType();
- }
-
- if (modelType.equals(ModelType.vfModule)) {
-
-
- // Get VF Module-specific base module indicator
- VfModule vfm = null;
- String modelVersionId = modelInfo.getModelVersionId();
-
- if (modelVersionId != null) {
- vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
- } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) {
- vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(),
- modelInfo.getModelVersion());
- }
-
- if (vfm != null) {
- if (vfm.getIsBase()) {
- isBaseVfModule = true;
- }
- } else if (action == Action.createInstance || action == Action.updateInstance) {
- // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in
- // Catalog DB.
- // This request cannot proceed
-
- String serviceVersionText = "";
- if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) {
- serviceVersionText = " with version " + sdcServiceModelVersion;
- }
+ ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+ ModelType modelType = requestHandlerUtils.getModelType(action, modelInfo);
- String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName()
- + serviceVersionText + " not found in MSO Catalog DB";
- ErrorLoggerInfo errorLoggerInfo =
- new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
- .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
- VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage,
- HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
- requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage());
+ Boolean isBaseVfModule = false;
- throw vfModuleException;
- }
+ if (modelType.equals(ModelType.vfModule)) {
+ isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion,
+ currentActiveReq);
}
-
serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
String vnfId = "";
String vfModuleId = "";
@@ -905,6 +896,7 @@ public class ServiceInstances {
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();
@@ -918,6 +910,7 @@ public class ServiceInstances {
aLaCarte = false;
}
+
RequestClientParameter requestClientParameter = null;
try {
requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
@@ -930,6 +923,7 @@ public class ServiceInstances {
.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();
@@ -941,11 +935,39 @@ public class ServiceInstances {
recipeLookupResult.getOrchestrationURI(), requestScope);
}
+ /**
+ * @param action
+ * @param sir
+ * @return
+ */
+ protected Actions handleReplaceInstance(Actions action, ServiceInstancesRequest sir) {
+ if (action != null && action.equals(Action.replaceInstance)
+ && sir.getRequestDetails().getRequestParameters().getRetainAssignments() != null
+ && sir.getRequestDetails().getRequestParameters().getRetainAssignments()) {
+ action = Action.replaceInstanceRetainAssignments;
+ }
+ 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);
Boolean aLaCarte = true;
- long startTime = System.currentTimeMillis();
String apiVersion = version.substring(1);
ServiceInstancesRequest sir = new ServiceInstancesRequest();
sir.setInstanceGroupId(instanceGroupId);
@@ -968,8 +990,8 @@ public class ServiceInstances {
throw validateException;
}
- InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null,
- requestScope, currentActiveReq);
+ InfraActiveRequests dup =
+ requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq);
boolean inProgress = false;
if (dup != null) {
@@ -977,8 +999,8 @@ public class ServiceInstances {
}
if (dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
- msoRequest, null, requestScope, dup);
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope,
+ dup);
}
ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
@@ -995,6 +1017,7 @@ public class ServiceInstances {
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();
@@ -1007,20 +1030,22 @@ public class ServiceInstances {
.setRequestAction(action.toString()).setApiVersion(apiVersion).setALaCarte(aLaCarte)
.setRequestUri(requestUri).setInstanceGroupId(instanceGroupId).build();
+
return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
recipeLookupResult.getOrchestrationURI(), requestScope);
}
- private String getPnfCorrelationId(ServiceInstancesRequest sir) {
+ protected String getPnfCorrelationId(ServiceInstancesRequest sir) {
return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails)
.map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId"))
.orElse("");
}
- private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action,
+ 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
+ // 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
@@ -1036,7 +1061,6 @@ public class ServiceInstances {
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();
@@ -1055,7 +1079,6 @@ public class ServiceInstances {
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();
@@ -1073,7 +1096,6 @@ public class ServiceInstances {
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();
@@ -1090,7 +1112,6 @@ public class ServiceInstances {
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)
@@ -1103,8 +1124,8 @@ public class ServiceInstances {
return recipeLookupResult;
}
- private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag)
- throws IOException {
+ protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action,
+ boolean alaCarteFlag) throws IOException {
// SERVICE REQUEST
// Construct the default service name
// TODO need to make this a configurable property
@@ -1140,7 +1161,8 @@ public class ServiceInstances {
}
}
- // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
+ // 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;
@@ -1262,8 +1284,7 @@ public class ServiceInstances {
return mapFlatMapToNameValue(userParams);
}
- private Service serviceMapper(Map<String, Object> params)
- throws JsonProcessingException, IOException, JsonParseException, JsonMappingException {
+ 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);
@@ -1300,7 +1321,7 @@ public class ServiceInstances {
instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
}
- Recipe recipe = null;
+ Recipe recipe;
String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq);
String modelCustomizationId = modelInfo.getModelCustomizationId();
String modelCustomizationName = modelInfo.getModelCustomizationName();
@@ -1330,23 +1351,32 @@ public class ServiceInstances {
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
+ // 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
+ // 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
+ // 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
+ // 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
+ // 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
+ // 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
+ // 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;
@@ -1477,14 +1507,13 @@ public class ServiceInstances {
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
+ // VfModuleCustomization table
}
if (modelInfo.getModelVersionId() == null) {
modelInfo.setModelVersionId(vfModule.getModelUUID());
}
-
recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
vfModule.getModelUUID(), vnfComponentType, action.toString());
if (recipe == null) {
@@ -1547,7 +1576,6 @@ public class ServiceInstances {
return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
}
-
private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
String defaultNetworkType = requestHandlerUtils.getDefaultModel(sir);
@@ -1587,19 +1615,15 @@ public class ServiceInstances {
return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
}
-
private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
String version, String requestId, String requestUri) throws ApiException {
- String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId");
+ String serviceInstanceId;
Boolean aLaCarte = null;
String apiVersion = version.substring(1);
boolean inProgress = false;
+ ServiceInstancesRequest sir;
- long startTime = System.currentTimeMillis();
- ServiceInstancesRequest sir = null;
-
- sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest,
- requestId, requestUri);
+ sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri);
String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
InfraActiveRequests currentActiveReq =
msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
@@ -1613,16 +1637,15 @@ public class ServiceInstances {
InfraActiveRequests dup = null;
- dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,
- requestScope, currentActiveReq);
+ dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq);
if (dup != null) {
inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
}
if (instanceIdMap != null && dup != null && inProgress) {
- requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime,
- msoRequest, instanceName, requestScope, dup);
+ requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName,
+ requestScope, dup);
}
ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
@@ -1630,7 +1653,6 @@ public class ServiceInstances {
referencesResponse.setRequestId(requestId);
serviceResponse.setRequestReferences(referencesResponse);
-
String orchestrationUri = env.getProperty(CommonConstants.ALACARTE_ORCHESTRATION);
String timeOut = env.getProperty(CommonConstants.ALACARTE_RECIPE_TIMEOUT);
@@ -1642,7 +1664,6 @@ public class ServiceInstances {
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();
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 fd0df1d2b0..5842531dc3 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,13 +19,18 @@
*/
package org.onap.so.apihandlerinfra;
-public enum MsoSubsystems {
- APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK(
- "Openstack Adapter"), REQUESTDB(
- "RequestDB Adapter"), REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter");
+public enum SoSubsystems implements Subsystem {
+ APIH("API Handler"),
+ ASDC("ASDC Controller"),
+ BPMN("BPMN Infra"),
+ CATALOGDB("CatalogDb Adapter"),
+ OPENSTACK("Openstack Adapter"),
+ REQUESTDB("RequestDB Adapter"),
+ SDNC("SDNC Adapter");
+
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 7bd7f95286..3c4c90cc37 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
@@ -91,7 +91,7 @@ public class TasksHandler {
@QueryParam("originalRequestDate") String originalRequestDate,
@QueryParam("originalRequestorId") String originalRequestorId, @PathParam("version") String version)
throws ApiException {
- Response responseBack = null;
+
String apiVersion = version.substring(1);
// Prepare the query string to /task interface
@@ -159,60 +159,49 @@ public class TasksHandler {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
.build();
+ throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo)
+ .build();
-
- ValidateException validateException =
- new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
-
- throw validateException;
} catch (IOException e) {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
.build();
- BPMNFailureException bpmnFailureException =
- new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
- HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
- throw bpmnFailureException;
+ throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY,
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
}
TasksGetResponse trr = new TasksGetResponse();
List<TaskList> taskList = new ArrayList<>();
ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
int bpelStatus = respHandler.getStatus();
- if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
- String respBody = respHandler.getResponseBody();
- if (respBody != null) {
- JSONArray data = new JSONArray(respBody);
+ String respBody = respHandler.getResponseBody();
+ if ((bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) && (null != respBody)) {
- for (int i = 0; i < data.length(); i++) {
- JSONObject taskEntry = data.getJSONObject(i);
- String id = taskEntry.getString("id");
- if (taskId != null && !taskId.equals(id)) {
- continue;
- }
- // Get variables info for each task ID
- TaskList taskListEntry = null;
- taskListEntry = getTaskInfo(id);
-
- taskList.add(taskListEntry);
+ JSONArray data = new JSONArray(respBody);
+ for (int i = 0; i < data.length(); i++) {
+ JSONObject taskEntry = data.getJSONObject(i);
+ String id = taskEntry.getString("id");
+ if (taskId != null && !taskId.equals(id)) {
+ continue;
}
- trr.setTaskList(taskList);
+ // Get variables info for each task ID
+ TaskList taskListEntry = null;
+ taskListEntry = getTaskInfo(id);
+
+ taskList.add(taskListEntry);
+
}
+ trr.setTaskList(taskList);
} else {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
.build();
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
- bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-
- throw bpmnFailureException;
+ throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus,
+ ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
}
String jsonResponse = null;
@@ -223,14 +212,10 @@ public class TasksHandler {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
.build();
+ throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+ HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo)
+ .build();
-
- ValidateException validateException =
- new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
- HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
- .errorInfo(errorLoggerInfo).build();
-
- throw validateException;
}
return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion);
@@ -250,10 +235,8 @@ public class TasksHandler {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
.build();
- BPMNFailureException validateException =
- new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
- HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
- throw validateException;
+ throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY,
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
}
ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType());
int bpelStatus = respHandler.getStatus();
@@ -264,14 +247,10 @@ public class TasksHandler {
} else {
ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
ErrorCode.AvailabilityError).build();
+ throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+ HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo)
+ .build();
-
-
- BPMNFailureException bpmnFailureException =
- new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
- HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
-
- throw bpmnFailureException;
}
} else {
@@ -279,20 +258,15 @@ public class TasksHandler {
new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
.build();
-
-
- BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
- bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
-
-
- throw bpmnFailureException;
+ throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus,
+ ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
}
return taskList;
}
- private TaskList buildTaskList(String taskId, String respBody) throws JSONException {
+ private TaskList buildTaskList(String taskId, String respBody) {
TaskList taskList = new TaskList();
JSONObject variables = new JSONObject(respBody);
@@ -317,7 +291,7 @@ public class TasksHandler {
return taskList;
}
- private String getOptVariableValue(JSONObject variables, String name) throws JSONException {
+ private String getOptVariableValue(JSONObject variables, String name) {
String variableEntry = variables.optString(name);
String value = "";
if (!variableEntry.isEmpty()) {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java
index 97b80098e6..632f371af5 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java
@@ -4,6 +4,8 @@
* ================================================================================
* 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
@@ -39,8 +41,8 @@ public class WebSecurityConfigImpl extends WebSecurityConfig {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
- .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString())
- .and().httpBasic();
+ .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and()
+ .httpBasic();
}
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 bba8064f7c..b57bb5d1d8 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
@@ -4,6 +4,8 @@
* ================================================================================
* Copyright (C) 2019 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
@@ -91,13 +93,13 @@ public class WorkflowSpecificationsHandler {
List<Workflow> workflows = catalogDbClient.findWorkflowByModelUUID(vnfModelVersionId);
List<Workflow> nativeWorkflows = catalogDbClient.findWorkflowBySource(NATIVE_WORKFLOW);
- if (nativeWorkflows != null && nativeWorkflows.size() != 0) {
+ if (nativeWorkflows != null && !nativeWorkflows.isEmpty()) {
workflows.addAll(nativeWorkflows);
}
WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows);
- String jsonResponse = null;
+ String jsonResponse;
try {
ObjectMapper mapper = new ObjectMapper();
jsonResponse = mapper.writeValueAsString(workflowSpecifications);
@@ -116,11 +118,11 @@ public class WorkflowSpecificationsHandler {
}
protected WorkflowSpecifications mapWorkflowsToWorkflowSpecifications(List<Workflow> workflows) {
- if (workflows == null || workflows.size() == 0) {
+ if (workflows == null || workflows.isEmpty()) {
return null;
}
WorkflowSpecifications workflowSpecifications = new WorkflowSpecifications();
- List<WorkflowSpecificationList> workflowSpecificationList = new ArrayList<WorkflowSpecificationList>();
+ List<WorkflowSpecificationList> workflowSpecificationList = new ArrayList<>();
for (Workflow workflow : workflows) {
WorkflowSpecificationList workflowSpecificationListItem = new WorkflowSpecificationList();
@@ -153,10 +155,10 @@ public class WorkflowSpecificationsHandler {
private List<ActivitySequence> buildActivitySequence(Workflow workflow) {
List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = workflow.getWorkflowActivitySpecSequence();
- if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.size() == 0) {
+ if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.isEmpty()) {
return null;
}
- List<ActivitySequence> activitySequences = new ArrayList<ActivitySequence>();
+ List<ActivitySequence> activitySequences = new ArrayList<>();
for (WorkflowActivitySpecSequence workflowActivitySpecSequence : workflowActivitySpecSequences) {
if (workflowActivitySpecSequence != null) {
ActivitySpec activitySpec = workflowActivitySpecSequence.getActivitySpec();
@@ -174,17 +176,17 @@ public class WorkflowSpecificationsHandler {
private List<WorkflowInputParameter> buildWorkflowInputParameters(Workflow workflow) {
List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = workflow.getWorkflowActivitySpecSequence();
- if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.size() == 0) {
- return new ArrayList<WorkflowInputParameter>();
+ if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.isEmpty()) {
+ return new ArrayList<>();
}
- Map<String, WorkflowInputParameter> workflowInputParameterMap = new HashMap<String, WorkflowInputParameter>();
+ Map<String, WorkflowInputParameter> workflowInputParameterMap = new HashMap<>();
for (WorkflowActivitySpecSequence workflowActivitySpecSequence : workflowActivitySpecSequences) {
if (workflowActivitySpecSequence != null) {
ActivitySpec activitySpec = workflowActivitySpecSequence.getActivitySpec();
if (activitySpec != null) {
List<ActivitySpecUserParameters> activitySpecUserParameters =
activitySpec.getActivitySpecUserParameters();
- if (activitySpecUserParameters != null && activitySpecUserParameters.size() != 0) {
+ if (activitySpecUserParameters != null && !activitySpecUserParameters.isEmpty()) {
for (ActivitySpecUserParameters activitySpecUserParameter : activitySpecUserParameters) {
UserParameters userParameter = activitySpecUserParameter.getUserParameters();
if (userParameter != null) {
@@ -199,7 +201,7 @@ public class WorkflowSpecificationsHandler {
}
if (workflowInputParameterMap.size() == 0) {
- return new ArrayList<WorkflowInputParameter>();
+ return new ArrayList<>();
}
List<WorkflowInputParameter> workflowInputParameterList =
workflowInputParameterMap.values().stream().collect(Collectors.toList());
@@ -220,7 +222,7 @@ public class WorkflowSpecificationsHandler {
private List<Validation> buildValidationList(UserParameters userParameter) {
List<Validation> validationList = null;
if (userParameter.getMaxLength() != null || userParameter.getAllowableChars() != null) {
- validationList = new ArrayList<Validation>();
+ validationList = new ArrayList<>();
Validation validation = new Validation();
if (userParameter.getMaxLength() != null) {
validation.setMaxLength(userParameter.getMaxLength().toString());
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java
index 4d81695e55..0db63e7493 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java
@@ -23,8 +23,8 @@ package org.onap.so.apihandlerinfra.configuration;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
@@ -32,10 +32,13 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jmx.export.MBeanExporter;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
@Configuration
@EnableTransactionManagement
@@ -44,11 +47,23 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Profile({"!test"})
public class CatalogDBConfig {
+ @Autowired(required = false)
+ private MBeanExporter mBeanExporter;
+
+ @Bean
+ @ConfigurationProperties(prefix = "spring.datasource.hikari")
+ public HikariConfig catalogDbConfig() {
+ return new HikariConfig();
+ }
+
@Primary
@Bean(name = "dataSource")
- @ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
- return DataSourceBuilder.create().build();
+ if (mBeanExporter != null) {
+ mBeanExporter.addExcludedBean("dataSource");
+ }
+ HikariConfig hikariConfig = this.catalogDbConfig();
+ return new HikariDataSource(hikariConfig);
}
@Primary
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java
index 1bc54ffe7b..02cbf2f3bf 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java
@@ -23,18 +23,21 @@ package org.onap.so.apihandlerinfra.configuration;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jmx.export.MBeanExporter;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
@Configuration
@EnableTransactionManagement
@@ -43,13 +46,24 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Profile({"!test"})
public class RequestDBConfig {
+ @Autowired(required = false)
+ private MBeanExporter mBeanExporter;
+
+ @Bean
+ @ConfigurationProperties(prefix = "request.datasource.hikari")
+ public HikariConfig requestDbConfig() {
+ return new HikariConfig();
+ }
+
@Bean(name = "requestDataSource")
- @ConfigurationProperties(prefix = "request.datasource")
public DataSource dataSource() {
- return DataSourceBuilder.create().build();
+ if (mBeanExporter != null) {
+ mBeanExporter.addExcludedBean("requestDataSource");
+ }
+ HikariConfig hikariConfig = this.requestDbConfig();
+ return new HikariDataSource(hikariConfig);
}
-
@Bean(name = "requestEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
@Qualifier("requestDataSource") DataSource dataSource) {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java
index 77abbbfa9a..6e77ce84a6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java
@@ -21,7 +21,7 @@
package org.onap.so.apihandlerinfra.e2eserviceinstancebeans;
-import java.sql.Timestamp;
+
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java
index f969674ed1..d6a99af8cd 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java
@@ -47,6 +47,9 @@ public class E2EService {
@JsonProperty("serviceType")
private String serviceType;
+ @JsonProperty("serviceId")
+ private String serviceId;
+
@JsonProperty("parameters")
private E2EParameters parameters;
@@ -109,6 +112,14 @@ public class E2EService {
this.serviceType = serviceType;
}
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
public String getServiceUuid() {
return serviceUuid;
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java
index f7fa01aeb0..4fc6181bf8 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java
@@ -29,13 +29,7 @@ public class GetE2EServiceInstanceResponse {
protected OperationStatus operation;
- // public OperationStatus getOperationStatus() {
- // return operation;
- // }
- //
- // public void setOperationStatus(OperationStatus requestDB) {
- // this.operation = requestDB;
- // }
+
public OperationStatus getOperation() {
return operation;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java
index 44592ce2e4..ae462ebffa 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java
@@ -39,6 +39,9 @@ public class ResourceRequest {
@JsonProperty("resourceCustomizationUuid")
private String resourceCustomizationUuid;
+ @JsonProperty("resourceIndex")
+ private String resourceIndex;
+
@JsonProperty("parameters")
private E2EParameters parameters;
@@ -98,4 +101,12 @@ public class ResourceRequest {
public void setParameters(E2EParameters parameters) {
this.parameters = parameters;
}
+
+ public String getResourceIndex() {
+ return resourceIndex;
+ }
+
+ public void setResourceIndex(String resourceIndex) {
+ this.resourceIndex = resourceIndex;
+ }
}
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
new file mode 100644
index 0000000000..ee2bb586cf
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java
@@ -0,0 +1,410 @@
+/*-
+ * ============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;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+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.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.entities.AAIResultWrapper;
+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.CloudConfiguration;
+import org.onap.so.serviceinstancebeans.ModelInfo;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.RequestParameters;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.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;
+
+@Component
+public class BpmnRequestBuilder {
+
+ private static final String CLOUD_CONFIGURATION_COULD_NOT_BE_FOUND = "Cloud Configuration could not be found";
+
+ private static final String CLOUD_REGION_ID = "cloud-region-id";
+
+ private static final String CLOUD_OWNER = "cloud-owner";
+
+ private static final String TENANT_ID = "tenant-id";
+
+ private static final String GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID =
+ "Generic Vnf Not Found In Inventory, VnfId: ";
+
+ private static final String VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID = "VF Module Not Found In Inventory, VnfId: ";
+
+ private static final Logger logger = LoggerFactory.getLogger(BpmnRequestBuilder.class);
+
+ @Autowired
+ private RequestsDbClient infraActiveRequestsClient;
+
+ @Autowired
+ private AAIDataRetrieval aaiDataRet;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+
+ public ServiceInstancesRequest buildVFModuleDeleteRequest(String vnfId, String vfModuleId, ModelType modelType)
+ throws AAIEntityNotFound {
+ GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId);
+ if (vnf == null) {
+ throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId);
+ }
+ 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 ServiceInstancesRequest buildVolumeGroupDeleteRequest(String vnfId, String volumeGroupId)
+ throws AAIEntityNotFound {
+ GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId);
+ if (vnf == null) {
+ throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId);
+ }
+ VolumeGroup volumeGroup = aaiDataRet.getVolumeGroup(vnfId, volumeGroupId);
+ if (volumeGroup == null) {
+ throw new AAIEntityNotFound(
+ VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId);
+ }
+ return createServiceInstancesRequest(vnf, volumeGroup);
+ }
+
+ public ServiceInstancesRequest buildServiceDeleteRequest(String serviceInstanceId) throws AAIEntityNotFound {
+ ServiceInstance serviceInstance = aaiDataRet.getServiceInstance(serviceInstanceId);
+ if (serviceInstance == null) {
+ throw new AAIEntityNotFound(
+ "ServiceInstance Not Found In Inventory, ServiceInstanceId: " + serviceInstanceId);
+ }
+ return createServiceInstancesRequest(serviceInstance);
+ }
+
+ public ServiceInstancesRequest buildVnfDeleteRequest(String vnfId) throws AAIEntityNotFound {
+ GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId);
+ if (vnf == null) {
+ throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId);
+ }
+ return createServiceInstancesRequest(vnf);
+ }
+
+ public ServiceInstancesRequest buildNetworkDeleteRequest(String networkId) throws AAIEntityNotFound {
+ L3Network network = aaiDataRet.getNetwork(networkId);
+ if (network == null) {
+ throw new AAIEntityNotFound("Network Not Found In Inventory, NetworkId: " + networkId);
+ }
+ return createServiceInstancesRequest(network);
+ }
+
+ protected ServiceInstancesRequest createServiceInstancesRequest(ServiceInstance serviceInstance) {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = mapServiceRequestDetails(serviceInstance);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ protected ServiceInstancesRequest createServiceInstancesRequest(GenericVnf vnf) {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = mapVnfRequestDetails(vnf);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ protected ServiceInstancesRequest createServiceInstancesRequest(GenericVnf vnf, VfModule vfModule,
+ ModelType modelType) {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = mapRequestDetails(vnf, vfModule, modelType);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ protected ServiceInstancesRequest createServiceInstancesRequest(GenericVnf vnf, VolumeGroup volumeGroup) {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = mapRequestDetails(vnf, volumeGroup);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ protected ServiceInstancesRequest createServiceInstancesRequest(L3Network network) {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = mapNetworkRequestDetails(network);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ protected RequestDetails mapRequestDetails(GenericVnf vnf, VfModule vfModule, ModelType modelType) {
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setRequestInfo(createRequestInfo());
+ if (vfModule.getVfModuleName() != null) {
+ requestDetails.getRequestInfo().setInstanceName(vfModule.getVfModuleName());
+ }
+ requestDetails.setModelInfo(mapVfModuleModelInformation(vfModule, modelType));
+
+ requestDetails.setCloudConfiguration(mapCloudConfiguration(vnf, vfModule));
+ requestDetails.setRequestParameters(createRequestParameters());
+ return requestDetails;
+ }
+
+ protected RequestDetails mapRequestDetails(GenericVnf vnf, VolumeGroup volumeGroup) {
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setRequestInfo(createRequestInfo());
+ if (volumeGroup.getVolumeGroupName() != null) {
+ requestDetails.getRequestInfo().setInstanceName(volumeGroup.getVolumeGroupName());
+ }
+ requestDetails.setModelInfo(mapVolumeGroupModelInformation(volumeGroup));
+ requestDetails.setCloudConfiguration(mapCloudConfigurationVolume(vnf, volumeGroup));
+ requestDetails.setRequestParameters(createRequestParameters());
+ return requestDetails;
+ }
+
+ protected RequestDetails mapVnfRequestDetails(GenericVnf vnf) {
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setRequestInfo(createRequestInfo());
+ if (vnf.getVnfName() != null) {
+ requestDetails.getRequestInfo().setInstanceName(vnf.getVnfName());
+ }
+ requestDetails.setModelInfo(mapVnfModelInformation(vnf));
+ requestDetails.setRequestParameters(createRequestParameters());
+ return requestDetails;
+ }
+
+ protected RequestDetails mapServiceRequestDetails(ServiceInstance serviceInstance) {
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setRequestInfo(createRequestInfo());
+ if (serviceInstance.getServiceInstanceName() != null) {
+ requestDetails.getRequestInfo().setInstanceName(serviceInstance.getServiceInstanceName());
+ }
+ requestDetails.setModelInfo(mapServiceModelInformation(serviceInstance));
+ requestDetails.setRequestParameters(createRequestParameters());
+ return requestDetails;
+ }
+
+ protected RequestDetails mapNetworkRequestDetails(L3Network network) {
+ RequestDetails requestDetails = new RequestDetails();
+ requestDetails.setRequestInfo(createRequestInfo());
+ if (network.getNetworkName() != null) {
+ requestDetails.getRequestInfo().setInstanceName(network.getNetworkName());
+ }
+ requestDetails.setCloudConfiguration(mapCloudConfigurationNetwork(network));
+ requestDetails.setModelInfo(mapNetworkModelInformation(network));
+ requestDetails.setRequestParameters(createRequestParameters());
+ return requestDetails;
+ }
+
+ protected ModelInfo mapVfModuleModelInformation(VfModule vfModule, ModelType modelType) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationId(vfModule.getModelCustomizationId());
+ modelInfo.setModelCustomizationUuid(vfModule.getModelCustomizationId());
+ modelInfo.setModelType(modelType);
+ return modelInfo;
+ }
+
+ protected ModelInfo mapVolumeGroupModelInformation(VolumeGroup volumeGroup) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationId(volumeGroup.getModelCustomizationId());
+ modelInfo.setModelCustomizationUuid(volumeGroup.getModelCustomizationId());
+ modelInfo.setModelType(ModelType.volumeGroup);
+ return modelInfo;
+ }
+
+ protected ModelInfo mapServiceModelInformation(ServiceInstance serviceInstance) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId(serviceInstance.getModelVersionId());
+ modelInfo.setModelType(ModelType.service);
+ return modelInfo;
+ }
+
+ protected ModelInfo mapVnfModelInformation(GenericVnf vnf) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelCustomizationId(vnf.getModelCustomizationId());
+ modelInfo.setModelCustomizationUuid(vnf.getModelCustomizationId());
+ modelInfo.setModelType(ModelType.vnf);
+ return modelInfo;
+ }
+
+ protected ModelInfo mapNetworkModelInformation(L3Network network) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.network);
+ modelInfo.setModelCustomizationId(network.getModelCustomizationId());
+ modelInfo.setModelCustomizationUuid(network.getModelCustomizationId());
+ return modelInfo;
+ }
+
+ public CloudConfiguration mapCloudConfiguration(GenericVnf vnf, VfModule vfModule) {
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ AAIResultWrapper wrapper = new AAIResultWrapper(vnf);
+ Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships();
+ String tenantId = null;
+ String cloudOwner = null;
+ String lcpRegionId = null;
+ if (relationshipsOpt.isPresent()) {
+ tenantId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst()
+ .map(item -> item.getURIKeys().get(TENANT_ID)).orElse(null);
+ cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst()
+ .map(item -> item.getURIKeys().get(CLOUD_OWNER)).orElse(null);
+ lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst()
+ .map(item -> item.getURIKeys().get(CLOUD_REGION_ID)).orElse(null);
+ }
+
+ if (tenantId == null || cloudOwner == null || lcpRegionId == null) {
+ Map<String, String[]> filters = createQueryRequest("vfModuleId", vfModule.getVfModuleId());
+ 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 CloudConfiguration mapCloudConfigurationVolume(GenericVnf vnf, VolumeGroup volumeGroup) {
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ AAIResultWrapper wrapper = new AAIResultWrapper(vnf);
+ Optional<org.onap.so.client.aai.entities.Relationships> relationshipsOpt = wrapper.getRelationships();
+ String tenantId = null;
+ String cloudOwner = null;
+ String lcpRegionId = null;
+ if (relationshipsOpt.isPresent()) {
+ tenantId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst()
+ .map(item -> item.getURIKeys().get(TENANT_ID)).orElse(null);
+ cloudOwner = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst()
+ .map(item -> item.getURIKeys().get(CLOUD_OWNER)).orElse(null);
+ lcpRegionId = relationshipsOpt.get().getRelatedUris(AAIObjectType.TENANT).stream().findFirst()
+ .map(item -> item.getURIKeys().get(CLOUD_REGION_ID)).orElse(null);
+ }
+
+ if (tenantId == null || cloudOwner == null || lcpRegionId == null) {
+ Map<String, String[]> filters = createQueryRequest("volumeGroupId", volumeGroup.getVolumeGroupId());
+ Optional<ServiceInstancesRequest> request = findServiceInstanceRequest(filters);
+ if (request.isPresent()) {
+ tenantId = request.get().getRequestDetails().getCloudConfiguration().getTenantId();
+ cloudOwner = request.get().getRequestDetails().getCloudConfiguration().getCloudOwner();
+ 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 CloudConfiguration mapCloudConfigurationNetwork(L3Network network) {
+ CloudConfiguration cloudConfig = new CloudConfiguration();
+ String tenantId = null;
+ String cloudOwner = null;
+ String lcpRegionId = null;
+
+ Map<String, String[]> filters = createQueryRequest("networkId", network.getNetworkId());
+ 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);
+ ServiceInstancesRequest siRequest;
+ try {
+ siRequest = mapper.readValue(foundRequest.getRequestBody(), ServiceInstancesRequest.class);
+ return Optional.of(siRequest);
+ } catch (Exception e) {
+ logger.error("Could not read Create Instance Request", e);
+ }
+ return Optional.empty();
+ }
+
+ public Map<String, String[]> createQueryRequest(String name, String instanceId) {
+ Map<String, String[]> filters = new HashMap<>();
+ filters.put(name, new String[] {"EQ", instanceId});
+ filters.put("requestStatus", new String[] {"EQ", Status.COMPLETE.toString()});
+ filters.put("action", new String[] {"EQ", "createInstance"});
+ return filters;
+ }
+
+ public RequestInfo createRequestInfo() {
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setSuppressRollback(false);
+ requestInfo.setSource(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ requestInfo.setRequestorId(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ return requestInfo;
+ }
+
+ public RequestParameters createRequestParameters() {
+ RequestParameters requestParams = new RequestParameters();
+ requestParams.setaLaCarte(true);
+ requestParams.setTestApi("GR_API");
+ return requestParams;
+ }
+
+
+}
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
new file mode 100644
index 0000000000..ec3df21fdb
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Network.java
@@ -0,0 +1,89 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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.infra.rest;
+
+import javax.transaction.Transactional;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandler.filters.ResponseUpdater;
+import org.onap.so.apihandlerinfra.Action;
+import org.onap.so.apihandlerinfra.infra.rest.handler.NetworkRestHandler;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+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;
+
+@Component
+@Path("/onap/so/infra/serviceInstantiation")
+public class Network {
+
+ @Autowired
+ private NetworkRestHandler networkRestHandler;
+
+ @Autowired
+ private BpmnRequestBuilder requestBuilder;
+
+ @DELETE
+ @ResponseUpdater
+ @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)
+ @Transactional
+ public Response deleteNetworkInstance(@PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId,
+ @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext)
+ throws Exception {
+ InfraActiveRequests currentRequest = null;
+ String requestId = networkRestHandler.getRequestId(requestContext);
+ String requestorId = "Unknown";
+ String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME);
+ String requestURI = requestContext.getUriInfo().getAbsolutePath().toString();
+ currentRequest = networkRestHandler.createInfraActiveRequestForDelete(requestId, serviceInstanceId,
+ networkInstanceId, requestorId, source, requestURI);
+ ServiceInstancesRequest request = requestBuilder.buildNetworkDeleteRequest(networkInstanceId);
+ networkRestHandler.saveInstanceName(request, currentRequest);
+ networkRestHandler.checkDuplicateRequest(serviceInstanceId, networkInstanceId,
+ request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId());
+ Recipe recipe = networkRestHandler.findNetworkRecipe(Action.deleteInstance.toString());
+ networkRestHandler.callWorkflowEngine(networkRestHandler.buildRequestParams(request,
+ networkRestHandler.getRequestUri(requestContext), requestId, serviceInstanceId, networkInstanceId),
+ recipe.getOrchestrationUri());
+ ServiceInstancesResponse response =
+ networkRestHandler.createResponse(networkInstanceId, requestId, requestContext);
+ return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build();
+ }
+}
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
new file mode 100644
index 0000000000..07e8092449
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/ServiceInstance.java
@@ -0,0 +1,89 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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.infra.rest;
+
+import javax.transaction.Transactional;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandler.filters.ResponseUpdater;
+import org.onap.so.apihandlerinfra.Action;
+import org.onap.so.apihandlerinfra.infra.rest.handler.ServiceInstanceRestHandler;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+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;
+
+@Component
+@Path("/onap/so/infra/serviceInstantiation")
+public class ServiceInstance {
+
+ @Autowired
+ private ServiceInstanceRestHandler requestHandler;
+
+ @Autowired
+ private BpmnRequestBuilder requestBuilder;
+
+ @DELETE
+ @ResponseUpdater
+ @Path("/{version:[vV][8]}/serviceInstances/{serviceInstanceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete a Service instance", response = ServiceInstancesResponse.class)
+ @Transactional
+ public Response deleteServiceInstance(@PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext)
+ throws Exception {
+ InfraActiveRequests currentRequest = null;
+ String requestId = requestHandler.getRequestId(requestContext);
+ String requestorId = "Unknown";
+ String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME);
+ String requestURI = requestContext.getUriInfo().getAbsolutePath().toString();
+ currentRequest = requestHandler.createInfraActiveRequestForDelete(requestId, serviceInstanceId, requestorId,
+ source, requestURI);
+ ServiceInstancesRequest request = requestBuilder.buildServiceDeleteRequest(serviceInstanceId);
+ requestHandler.saveInstanceName(request, currentRequest);
+ requestHandler.checkDuplicateRequest(serviceInstanceId,
+ request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId());
+ Recipe recipe = requestHandler.findServiceRecipe(request.getRequestDetails().getModelInfo().getModelUuid(),
+ Action.deleteInstance.toString());
+ requestHandler.callWorkflowEngine(requestHandler.buildRequestParams(request,
+ requestHandler.getRequestUri(requestContext), requestId, serviceInstanceId),
+ recipe.getOrchestrationUri());
+ ServiceInstancesResponse response = requestHandler.createResponse(serviceInstanceId, requestId, requestContext);
+ return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build();
+
+ }
+}
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
new file mode 100644
index 0000000000..1b9eb1f802
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/VfModules.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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.infra.rest;
+
+import javax.transaction.Transactional;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandler.filters.ResponseUpdater;
+import org.onap.so.apihandlerinfra.Action;
+import org.onap.so.apihandlerinfra.infra.rest.handler.VFModuleRestHandler;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+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;
+
+@Component
+@Path("/onap/so/infra/serviceInstantiation")
+public class VfModules {
+
+ @Autowired
+ private VFModuleRestHandler restHandler;
+
+ @Autowired
+ private BpmnRequestBuilder requestBuilder;
+
+ @DELETE
+ @ResponseUpdater
+ @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)
+ @Transactional
+ public Response deleteVfModuleInstance(@PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext)
+ throws Exception {
+ InfraActiveRequests currentRequest = null;
+
+ String requestId = restHandler.getRequestId(requestContext);
+ String requestorId = "Unknown";
+ String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME);
+ String requestURL = requestContext.getUriInfo().getAbsolutePath().toString();
+ currentRequest = restHandler.createInfraActiveRequestForDelete(requestId, vfmoduleInstanceId, serviceInstanceId,
+ vnfInstanceId, requestorId, source, requestURL);
+ ServiceInstancesRequest request =
+ requestBuilder.buildVFModuleDeleteRequest(vnfInstanceId, vfmoduleInstanceId, ModelType.vfModule);
+ restHandler.saveInstanceName(request, currentRequest);
+ restHandler.checkDuplicateRequest(serviceInstanceId, vnfInstanceId, vfmoduleInstanceId,
+ request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId());
+ Recipe recipe =
+ restHandler.findVfModuleRecipe(request.getRequestDetails().getModelInfo().getModelCustomizationId(),
+ ModelType.vfModule.toString(), Action.deleteInstance.toString());
+ restHandler
+ .callWorkflowEngine(restHandler.buildRequestParams(request, restHandler.getRequestUri(requestContext),
+ requestId, serviceInstanceId, vnfInstanceId, vfmoduleInstanceId), recipe.getOrchestrationUri());
+ ServiceInstancesResponse response = restHandler.createResponse(vfmoduleInstanceId, requestId, requestContext);
+ return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build();
+
+ }
+}
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
new file mode 100644
index 0000000000..a8ccdeecac
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Vnf.java
@@ -0,0 +1,87 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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.infra.rest;
+
+import javax.transaction.Transactional;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandler.filters.ResponseUpdater;
+import org.onap.so.apihandlerinfra.infra.rest.handler.VnfRestHandler;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+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;
+
+@Component
+@Path("/onap/so/infra/serviceInstantiation")
+public class Vnf {
+
+ @Autowired
+ private BpmnRequestBuilder requestBuilder;
+
+ @Autowired
+ private VnfRestHandler vnfRestHandler;
+
+ @DELETE
+ @ResponseUpdater
+ @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)
+ @Transactional
+ public Response deleteVnfInstance(@PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @Context ContainerRequestContext requestContext) throws Exception {
+ InfraActiveRequests currentRequest = null;
+ String requestId = vnfRestHandler.getRequestId(requestContext);
+ String requestorId = "Unknown";
+ String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME);
+ String requestURL = requestContext.getUriInfo().getAbsolutePath().toString();
+ currentRequest = vnfRestHandler.createInfraActiveRequestForDelete(requestId, serviceInstanceId, vnfInstanceId,
+ requestorId, source, requestURL);
+ ServiceInstancesRequest request = requestBuilder.buildVnfDeleteRequest(vnfInstanceId);
+ vnfRestHandler.saveInstanceName(request, currentRequest);
+ vnfRestHandler.checkDuplicateRequest(serviceInstanceId, vnfInstanceId,
+ request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId());
+ Recipe recipe = vnfRestHandler.findVnfModuleRecipe(
+ request.getRequestDetails().getModelInfo().getModelCustomizationId(), "vnf", "deleteInstance");
+ vnfRestHandler.callWorkflowEngine(vnfRestHandler.buildRequestParams(request,
+ vnfRestHandler.getRequestUri(requestContext), requestId, serviceInstanceId, vnfInstanceId),
+ recipe.getOrchestrationUri());
+ ServiceInstancesResponse response = vnfRestHandler.createResponse(vnfInstanceId, requestId, requestContext);
+ return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build();
+ }
+}
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
new file mode 100644
index 0000000000..d3e394d6d8
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/Volumes.java
@@ -0,0 +1,97 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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.infra.rest;
+
+import javax.transaction.Transactional;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandler.filters.ResponseUpdater;
+import org.onap.so.apihandlerinfra.Action;
+import org.onap.so.apihandlerinfra.infra.rest.handler.VFModuleRestHandler;
+import org.onap.so.apihandlerinfra.infra.rest.handler.VolumeRestHandler;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+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;
+
+@Component("VolumesV8")
+@Path("/onap/so/infra/serviceInstantiation")
+public class Volumes {
+
+ @Autowired
+ private BpmnRequestBuilder requestBuilder;
+
+ @Autowired
+ private VFModuleRestHandler vfModuleRestHandler;
+
+ @Autowired
+ private VolumeRestHandler volumeRestHandler;
+
+ @DELETE
+ @ResponseUpdater
+ @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)
+ @Transactional
+ public Response deleteVfModuleInstance(@PathParam("version") String version,
+ @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
+ @PathParam("volumeGroupInstanceId") String volumeGroupId, @Context ContainerRequestContext requestContext)
+ throws Exception {
+ InfraActiveRequests currentRequest = null;
+ String requestId = volumeRestHandler.getRequestId(requestContext);
+ String requestorId = "Unknown";
+ String source = MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME);
+ String requestURL = requestContext.getUriInfo().getAbsolutePath().toString();
+ currentRequest = volumeRestHandler.createInfraActiveRequestForDelete(requestId, volumeGroupId,
+ serviceInstanceId, vnfInstanceId, requestorId, source, requestURL);
+ ServiceInstancesRequest request = requestBuilder.buildVolumeGroupDeleteRequest(vnfInstanceId, volumeGroupId);
+ volumeRestHandler.saveInstanceName(request, currentRequest);
+ volumeRestHandler.checkDuplicateRequest(serviceInstanceId, vnfInstanceId, volumeGroupId,
+ request.getRequestDetails().getRequestInfo().getInstanceName(), currentRequest.getRequestId());
+ Recipe recipe = vfModuleRestHandler.findVfModuleRecipe(
+ request.getRequestDetails().getModelInfo().getModelCustomizationId(), ModelType.volumeGroup.toString(),
+ Action.deleteInstance.toString());
+ volumeRestHandler
+ .callWorkflowEngine(
+ volumeRestHandler.buildRequestParams(request, volumeRestHandler.getRequestUri(requestContext),
+ requestId, serviceInstanceId, vnfInstanceId, volumeGroupId),
+ recipe.getOrchestrationUri());
+ ServiceInstancesResponse response = volumeRestHandler.createResponse(volumeGroupId, requestId, requestContext);
+ return Response.status(HttpStatus.ACCEPTED.value()).entity(response).build();
+ }
+}
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
new file mode 100644
index 0000000000..2153d9a628
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/AAIEntityNotFound.java
@@ -0,0 +1,29 @@
+/*-
+ * ============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.exception;
+
+public class AAIEntityNotFound extends Exception {
+
+ 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/exception/CloudConfigurationNotFoundException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/CloudConfigurationNotFoundException.java
new file mode 100644
index 0000000000..5135478a3e
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/CloudConfigurationNotFoundException.java
@@ -0,0 +1,29 @@
+/*-
+ * ============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.exception;
+
+public class CloudConfigurationNotFoundException extends RuntimeException {
+
+ public CloudConfigurationNotFoundException(String errorMessage) {
+ super(errorMessage);
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/NoRecipeException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/NoRecipeException.java
new file mode 100644
index 0000000000..db35b5c5cd
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/NoRecipeException.java
@@ -0,0 +1,31 @@
+/*-
+ * ============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.exception;
+
+public class NoRecipeException extends Exception {
+
+ public NoRecipeException(String error) {
+ super(error);
+ }
+
+
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java
new file mode 100644
index 0000000000..35cb21945c
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/RequestConflictedException.java
@@ -0,0 +1,30 @@
+/*-
+ * ============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.exception;
+
+public class RequestConflictedException extends RuntimeException {
+
+ public RequestConflictedException(String errorMessage) {
+ super(errorMessage);
+ }
+
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.java
new file mode 100644
index 0000000000..f9206628a4
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/WorkflowEngineConnectionException.java
@@ -0,0 +1,29 @@
+/*-
+ * ============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.exception;
+
+public class WorkflowEngineConnectionException extends Exception {
+
+ public WorkflowEngineConnectionException(String error, Throwable t) {
+ super(error, t);
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java
new file mode 100644
index 0000000000..519578ce6c
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/AAIEntityNotFoundMapper.java
@@ -0,0 +1,48 @@
+/*-
+ * ============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.exception.mapper;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound;
+import org.onap.so.serviceinstancebeans.RequestError;
+import org.onap.so.serviceinstancebeans.ServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class AAIEntityNotFoundMapper implements ExceptionMapper<AAIEntityNotFound> {
+
+ private static final Logger logger = LoggerFactory.getLogger(AAIEntityNotFoundMapper.class);
+
+ @Override
+ public Response toResponse(AAIEntityNotFound e) {
+ logger.error("AAIEntity Not Found", e);
+ RequestError error = new RequestError();
+ ServiceException value = new ServiceException();
+ value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR);
+ value.setText(e.getMessage());
+ error.setServiceException(value);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java
new file mode 100644
index 0000000000..24bf7434ee
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/CloudConfigurationNotFoundMapper.java
@@ -0,0 +1,48 @@
+/*-
+ * ============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.exception.mapper;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException;
+import org.onap.so.serviceinstancebeans.RequestError;
+import org.onap.so.serviceinstancebeans.ServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class CloudConfigurationNotFoundMapper implements ExceptionMapper<CloudConfigurationNotFoundException> {
+
+ private static final Logger logger = LoggerFactory.getLogger(CloudConfigurationNotFoundMapper.class);
+
+ @Override
+ public Response toResponse(CloudConfigurationNotFoundException e) {
+ logger.error("Cloud Configuration Not Found", e);
+ RequestError error = new RequestError();
+ ServiceException value = new ServiceException();
+ value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR);
+ value.setText(e.getMessage());
+ error.setServiceException(value);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java
new file mode 100644
index 0000000000..c807aa2597
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/NoRecipeExceptionMapper.java
@@ -0,0 +1,48 @@
+/*-
+ * ============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.exception.mapper;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandlerinfra.infra.rest.exception.NoRecipeException;
+import org.onap.so.serviceinstancebeans.RequestError;
+import org.onap.so.serviceinstancebeans.ServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class NoRecipeExceptionMapper implements ExceptionMapper<NoRecipeException> {
+
+ private static final Logger logger = LoggerFactory.getLogger(NoRecipeExceptionMapper.class);
+
+ @Override
+ public Response toResponse(NoRecipeException e) {
+ logger.error("No Recipe Found", e);
+ RequestError error = new RequestError();
+ ServiceException value = new ServiceException();
+ value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR);
+ value.setText(e.getMessage());
+ error.setServiceException(value);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java
new file mode 100644
index 0000000000..42d07c627b
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/RequestConflictMapper.java
@@ -0,0 +1,48 @@
+/*-
+ * ============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.exception.mapper;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException;
+import org.onap.so.serviceinstancebeans.RequestError;
+import org.onap.so.serviceinstancebeans.ServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class RequestConflictMapper implements ExceptionMapper<RequestConflictedException> {
+
+ private static final Logger logger = LoggerFactory.getLogger(RequestConflictMapper.class);
+
+ @Override
+ public Response toResponse(RequestConflictedException e) {
+ logger.error("Request Conflict Error", e);
+ RequestError error = new RequestError();
+ ServiceException value = new ServiceException();
+ value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR);
+ value.setText(e.getMessage());
+ error.setServiceException(value);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java
new file mode 100644
index 0000000000..71e0dacd56
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/exception/mapper/WorkflowEngineConnectionMapper.java
@@ -0,0 +1,48 @@
+/*-
+ * ============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.exception.mapper;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandlerinfra.infra.rest.exception.WorkflowEngineConnectionException;
+import org.onap.so.serviceinstancebeans.RequestError;
+import org.onap.so.serviceinstancebeans.ServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class WorkflowEngineConnectionMapper implements ExceptionMapper<WorkflowEngineConnectionException> {
+
+ private static final Logger logger = LoggerFactory.getLogger(WorkflowEngineConnectionMapper.class);
+
+ @Override
+ public Response toResponse(WorkflowEngineConnectionException e) {
+ logger.error("Workflow Engine Connection Error", e);
+ RequestError error = new RequestError();
+ ServiceException value = new ServiceException();
+ value.setMessageId(ErrorNumbers.SVC_GENERAL_SERVICE_ERROR);
+ value.setText(e.getMessage());
+ error.setServiceException(value);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
+ }
+}
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
new file mode 100644
index 0000000000..20e27a5265
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java
@@ -0,0 +1,214 @@
+/*-
+ * ============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.handler;
+
+import java.io.IOException;
+import java.net.URL;
+import java.sql.Timestamp;
+import java.util.Map;
+import java.util.Optional;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.apache.http.HttpStatus;
+import org.onap.so.apihandler.common.ErrorNumbers;
+import org.onap.so.apihandler.common.RequestClient;
+import org.onap.so.apihandler.common.RequestClientFactory;
+import org.onap.so.apihandler.common.RequestClientParameter;
+import org.onap.so.apihandlerinfra.Action;
+import org.onap.so.apihandlerinfra.Actions;
+import org.onap.so.apihandlerinfra.Constants;
+import org.onap.so.apihandlerinfra.MsoRequest;
+import org.onap.so.apihandlerinfra.exceptions.ApiException;
+import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
+import org.onap.so.apihandlerinfra.exceptions.ValidateException;
+import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException;
+import org.onap.so.apihandlerinfra.infra.rest.exception.WorkflowEngineConnectionException;
+import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.logger.ErrorCode;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.logger.MessageEnum;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestReferences;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+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;
+
+@Component
+public abstract class AbstractRestHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class);
+
+ public static final String CONFLICT_FAIL_MESSAGE = "Error: Locked instance - This %s (%s) "
+ + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
+
+
+ @Autowired
+ protected CatalogDbClient catalogDbClient;
+
+ @Autowired
+ protected RequestsDbClient infraActiveRequestsClient;
+
+ @Autowired
+ protected RequestClientFactory reqClientFactory;
+
+ public String getRequestUri(ContainerRequestContext context) {
+ String requestUri = context.getUriInfo().getPath();
+ String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
+ MDC.put(LogConstants.HTTP_URL, httpUrl);
+ requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22);
+ return requestUri;
+ }
+
+ public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
+ String requestId = null;
+ if (requestContext.getProperty("requestId") != null) {
+ requestId = requestContext.getProperty("requestId").toString();
+ }
+ if (UUIDChecker.isValidUUID(requestId)) {
+ return requestId;
+ } else {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+ .build();
+ }
+ }
+
+ public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
+ MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
+ throws ApiException {
+ return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq);
+ }
+
+ public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
+ String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
+ InfraActiveRequests dup = null;
+ try {
+ if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
+ || action == Action.activateInstance || action == Action.assignInstance))) {
+ dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
+ }
+ } catch (Exception e) {
+ ErrorLoggerInfo errorLoggerInfo =
+ new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
+ .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+ RequestDbFailureException requestDbFailureException =
+ new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
+ HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
+ .errorInfo(errorLoggerInfo).build();
+ updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
+ throw requestDbFailureException;
+ }
+ return dup;
+ }
+
+ public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
+ throws RequestDbFailureException {
+ if ((aq != null) && ((status == Status.FAILED) || (status == Status.COMPLETE))) {
+
+ aq.setStatusMessage(errorMessage);
+ aq.setProgress(100L);
+ aq.setRequestStatus(status.toString());
+ Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
+ aq.setEndTime(endTimeStamp);
+ try {
+ infraActiveRequestsClient.updateInfraActiveRequests(aq);
+ } catch (Exception e) {
+ logger.error("Error updating status", e);
+ }
+
+ }
+ }
+
+
+
+ public void callWorkflowEngine(RequestClientParameter requestClientParameter, String orchestrationUri)
+ throws WorkflowEngineConnectionException {
+ RequestClient requestClient = reqClientFactory.getRequestClient(orchestrationUri);
+ try {
+ requestClient.post(requestClientParameter);
+ } catch (IOException e) {
+ logger.error("Error Calling Workflow Engine", e);
+ throw new WorkflowEngineConnectionException("Error Calling Workflow Engine", e);
+ }
+ }
+
+ public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
+ Optional<URL> selfLinkUrl = Optional.empty();
+ String version = "";
+ try {
+ URL aUrl = new URL(url);
+ String aPath = aUrl.getPath();
+ if (aPath.indexOf("/v") == -1) {
+ version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4);
+ } else {
+ version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4);
+ }
+ String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
+ selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
+ } catch (Exception e) {
+ selfLinkUrl = Optional.empty(); // ignore
+ logger.error("Exception in buildSelfLinkUrl", e);
+ }
+ return selfLinkUrl;
+ }
+
+ /**
+ * @param instanceId
+ * @param requestId
+ * @param requestContext
+ */
+ public ServiceInstancesResponse createResponse(String instanceId, String requestId,
+ ContainerRequestContext requestContext) {
+ ServiceInstancesResponse response = new ServiceInstancesResponse();
+ RequestReferences requestReferences = new RequestReferences();
+ requestReferences.setInstanceId(instanceId);
+ requestReferences.setRequestId(requestId);
+ Optional<URL> optionalUrl = buildSelfLinkUrl(getRequestUri(requestContext), requestId);
+ if (optionalUrl.isPresent()) {
+ requestReferences.setRequestSelfLink(optionalUrl.get());
+ }
+ response.setRequestReferences(requestReferences);
+ return response;
+ }
+
+ public void checkDuplicateRequest(Map<String, String> instanceIdMap, ModelType modelType, String instanceName,
+ String requestId) throws RequestConflictedException {
+ InfraActiveRequests conflictedRequest =
+ infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString());
+ if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) {
+ throw new RequestConflictedException(String.format(CONFLICT_FAIL_MESSAGE, modelType.toString(),
+ instanceName, conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId()));
+ }
+ }
+
+
+
+}
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
new file mode 100644
index 0000000000..7b095fc9d0
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandler.java
@@ -0,0 +1,113 @@
+/*-
+ * ============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.handler;
+
+import java.sql.Timestamp;
+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.apihandlerinfra.infra.rest.exception.RequestConflictedException;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.NetworkRecipe;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class NetworkRestHandler extends AbstractRestHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(NetworkRestHandler.class);
+
+ public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String serviceInstanceId,
+ String networkId, String requestorId, String source, String requestURL) {
+ 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);
+ deleteRequest.setRequestId(requestId);
+ deleteRequest.setRequestorId(requestorId);
+ deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+ deleteRequest.setSource(source);
+ deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ deleteRequest.setRequestUrl(requestURL);
+ deleteRequest.setRequestScope(ModelType.network.toString());
+ deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ return deleteRequest;
+ }
+
+ public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String serviceInstanceId,
+ String networkId, String requestorId, String source, String requestURL) {
+ InfraActiveRequests request = mapInfraActiveRequestForDelete(requestId, serviceInstanceId, networkId,
+ requestorId, source, requestURL);
+ infraActiveRequestsClient.save(request);
+ return request;
+ }
+
+ public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI,
+ String requestId, String serviceInstanceId, String networkId) throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId)
+ .setNetworkId(networkId).setALaCarte(true).setRequestDetails(mapper.writeValueAsString(request))
+ .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8")
+ .build();
+ }
+
+ public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) {
+ try {
+ currentRequest.setNetworkName(request.getRequestDetails().getRequestInfo().getInstanceName());
+ infraActiveRequestsClient.updateInfraActiveRequests(currentRequest);
+ } catch (Exception e) {
+ logger.warn("Could not update instance name", e);
+ }
+ }
+
+ public void checkDuplicateRequest(String serviceInstanceId, String networkInstanceId, String instanceName,
+ String requestId) throws RequestConflictedException {
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("networkInstanceId", networkInstanceId);
+ checkDuplicateRequest(instanceIdMap, ModelType.network, instanceName, requestId);
+ }
+
+ public Recipe findNetworkRecipe(String action) throws NoRecipeException {
+ String modelName = "GR-API-DEFAULT";
+ NetworkRecipe recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action);
+
+ if (recipe == null) {
+ throw new NoRecipeException(String.format("Unable to locate default recipe for, Action: %s, Model Name: %s",
+ action, modelName));
+ }
+ return recipe;
+ }
+}
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
new file mode 100644
index 0000000000..afadf36157
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandler.java
@@ -0,0 +1,116 @@
+/*-
+ * ============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.handler;
+
+
+import java.sql.Timestamp;
+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.apihandlerinfra.infra.rest.exception.RequestConflictedException;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.catalog.beans.ServiceRecipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class ServiceInstanceRestHandler extends AbstractRestHandler {
+
+ private static final String DEFAULT_VF_MODULE_UUID = "d88da85c-d9e8-4f73-b837-3a72a431622b";
+
+ private static final Logger logger = LoggerFactory.getLogger(ServiceInstanceRestHandler.class);
+
+ public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String serviceInstanceId,
+ String requestorId, String source, String requestURL) {
+ 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);
+ deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+ deleteRequest.setRequestorId(requestorId);
+ deleteRequest.setSource(source);
+ deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ deleteRequest.setRequestUrl(requestURL);
+ deleteRequest.setRequestScope(ModelType.service.toString());
+ return deleteRequest;
+ }
+
+ public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String serviceInstanceId,
+ String requestorId, String source, String requestURL) {
+ InfraActiveRequests request =
+ mapInfraActiveRequestForDelete(requestId, serviceInstanceId, requestorId, source, requestURL);
+ infraActiveRequestsClient.save(request);
+ return request;
+ }
+
+ public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI,
+ String requestId, String serviceInstanceId) throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId)
+ .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(request))
+ .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8")
+ .build();
+ }
+
+ public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) {
+ try {
+ currentRequest.setServiceInstanceName(request.getRequestDetails().getRequestInfo().getInstanceName());
+ infraActiveRequestsClient.updateInfraActiveRequests(currentRequest);
+ } catch (Exception e) {
+ logger.warn("Could not update instance name", e);
+ }
+ }
+
+ public void checkDuplicateRequest(String serviceInstanceId, String instanceName, String requestId)
+ throws RequestConflictedException {
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ checkDuplicateRequest(instanceIdMap, ModelType.service, instanceName, requestId);
+ }
+
+ public Recipe findServiceRecipe(String modelUUID, String action) throws NoRecipeException {
+ ServiceRecipe recipe = catalogDbClient.findServiceRecipeByActionAndServiceModelUUID(action, modelUUID);
+ if (recipe == null) {
+ recipe = catalogDbClient.findServiceRecipeByActionAndServiceModelUUID(action, DEFAULT_VF_MODULE_UUID);
+ }
+ if (recipe == null) {
+ throw new NoRecipeException(String.format(
+ "Unable to locate custom or default recipe for, Action: %s, Model UUID: %s", action, modelUUID));
+ }
+ return recipe;
+ }
+
+}
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
new file mode 100644
index 0000000000..0762803488
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VFModuleRestHandler.java
@@ -0,0 +1,125 @@
+/*-
+ * ============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.handler;
+
+
+import java.sql.Timestamp;
+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.VnfComponentsRecipe;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class VFModuleRestHandler extends AbstractRestHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(VFModuleRestHandler.class);
+
+ public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String vfModuleId,
+ String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) {
+ 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);
+ deleteRequest.setVfModuleId(vfModuleId);
+ deleteRequest.setRequestId(requestId);
+ deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+ deleteRequest.setRequestorId(requestorId);
+ deleteRequest.setSource(source);
+ deleteRequest.setVfModuleId(vfModuleId);
+ deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ deleteRequest.setRequestUrl(requestURL);
+ deleteRequest.setRequestScope(ModelType.vfModule.toString());
+ deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ return deleteRequest;
+ }
+
+ public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String vfModuleId,
+ String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) {
+ InfraActiveRequests request = mapInfraActiveRequestForDelete(requestId, vfModuleId, serviceInstanceId, vnfId,
+ requestorId, source, requestURL);
+ infraActiveRequestsClient.save(request);
+ return request;
+ }
+
+ public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI,
+ String requestId, String serviceInstanceId, String vnfId, String vfModuleId)
+ throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId)
+ .setVnfId(vnfId).setVfModuleId(vfModuleId).setALaCarte(true)
+ .setRequestDetails(mapper.writeValueAsString(request))
+ .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8")
+ .build();
+ }
+
+ public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) {
+ try {
+ currentRequest.setVfModuleName(request.getRequestDetails().getRequestInfo().getInstanceName());
+ infraActiveRequestsClient.updateInfraActiveRequests(currentRequest);
+ } catch (Exception e) {
+ logger.warn("Could not update instance name", e);
+ }
+ }
+
+ public void checkDuplicateRequest(String serviceInstanceId, String vnfInstanceId, String vfmoduleInstanceId,
+ String instanceName, String requestId) {
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
+ checkDuplicateRequest(instanceIdMap, ModelType.vfModule, instanceName, requestId);
+ }
+
+ public Recipe findVfModuleRecipe(String modelCustomizationId, String modelType, String action)
+ throws NoRecipeException {
+ VnfComponentsRecipe recipe =
+ catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ modelCustomizationId, modelType, action);
+ if (recipe == null) {
+ recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ "GR-API-DEFAULT", modelType, action);
+ }
+ if (recipe == null) {
+ throw new NoRecipeException(String.format(
+ "Unable to locate custom or default recipe for ModelType: %s , Action: %s, CustomizationId: %s",
+ modelType, action, modelCustomizationId));
+ }
+ return recipe;
+
+ }
+}
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
new file mode 100644
index 0000000000..e157d926f3
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandler.java
@@ -0,0 +1,110 @@
+/*-
+ * ============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.handler;
+
+
+import java.sql.Timestamp;
+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;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class VnfRestHandler extends AbstractRestHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(VnfRestHandler.class);
+
+ public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String serviceInstanceId, String vnfId,
+ String requestorId, String source, String requestURL) {
+ 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);
+ deleteRequest.setRequestId(requestId);
+ deleteRequest.setRequestorId(requestorId);
+ deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+ deleteRequest.setSource(source);
+ deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ deleteRequest.setRequestScope(ModelType.vnf.toString());
+ deleteRequest.setRequestUrl(requestURL);
+ return deleteRequest;
+ }
+
+ public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String serviceInstanceId,
+ String vnfId, String requestorId, String source, String requestURL) {
+ InfraActiveRequests request =
+ mapInfraActiveRequestForDelete(requestId, serviceInstanceId, vnfId, requestorId, source, requestURL);
+ infraActiveRequestsClient.save(request);
+ return request;
+ }
+
+ public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI,
+ String requestId, String serviceInstanceId, String vnfId) throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId)
+ .setVnfId(vnfId).setALaCarte(true).setRequestDetails(mapper.writeValueAsString(request))
+ .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8")
+ .build();
+ }
+
+ public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) {
+ try {
+ currentRequest.setVnfName(request.getRequestDetails().getRequestInfo().getInstanceName());
+ infraActiveRequestsClient.updateInfraActiveRequests(currentRequest);
+ } catch (Exception e) {
+ logger.warn("Could not update instance name", e);
+ }
+ }
+
+ public void checkDuplicateRequest(String serviceInstanceId, String vnfInstanceId, String instanceName,
+ String requestId) {
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ checkDuplicateRequest(instanceIdMap, ModelType.vnf, instanceName, requestId);
+ }
+
+ public Recipe findVnfModuleRecipe(String modelCustomizationId, String modelType, String action)
+ throws NoRecipeException {
+ 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
new file mode 100644
index 0000000000..48a8aa2cd8
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandler.java
@@ -0,0 +1,104 @@
+/*-
+ * ============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.handler;
+
+
+import java.sql.Timestamp;
+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.constants.Status;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.logger.LogConstants;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@Component
+public class VolumeRestHandler extends AbstractRestHandler {
+
+ private static final Logger logger = LoggerFactory.getLogger(VolumeRestHandler.class);
+
+ public InfraActiveRequests mapInfraActiveRequestForDelete(String requestId, String volumeGroupId,
+ String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) {
+ 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);
+ deleteRequest.setVolumeGroupId(volumeGroupId);
+ deleteRequest.setRequestId(requestId);
+ deleteRequest.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
+ deleteRequest.setRequestorId(requestorId);
+ deleteRequest.setSource(source);
+ deleteRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ deleteRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ deleteRequest.setRequestScope(ModelType.volumeGroup.toString());
+ deleteRequest.setRequestUrl(requestURL);
+ return deleteRequest;
+ }
+
+ public InfraActiveRequests createInfraActiveRequestForDelete(String requestId, String volumeGroupId,
+ String serviceInstanceId, String vnfId, String requestorId, String source, String requestURL) {
+ InfraActiveRequests request = mapInfraActiveRequestForDelete(requestId, volumeGroupId, serviceInstanceId, vnfId,
+ requestorId, source, requestURL);
+ infraActiveRequestsClient.save(request);
+ return request;
+ }
+
+ public RequestClientParameter buildRequestParams(ServiceInstancesRequest request, String requestURI,
+ String requestId, String serviceInstanceId, String vnfId, String volumeGroupId)
+ throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ return new RequestClientParameter.Builder().setRequestId(requestId).setServiceInstanceId(serviceInstanceId)
+ .setVnfId(vnfId).setVolumeGroupId(volumeGroupId).setALaCarte(true)
+ .setRequestDetails(mapper.writeValueAsString(request))
+ .setRequestAction(Action.deleteInstance.toString()).setRequestUri(requestURI).setApiVersion("v8")
+ .build();
+ }
+
+ public void saveInstanceName(ServiceInstancesRequest request, InfraActiveRequests currentRequest) {
+ try {
+ currentRequest.setVolumeGroupName(request.getRequestDetails().getRequestInfo().getInstanceName());
+ infraActiveRequestsClient.updateInfraActiveRequests(currentRequest);
+ } catch (Exception e) {
+ logger.warn("Could not update instance name", e);
+ }
+ }
+
+ public void checkDuplicateRequest(String serviceInstanceId, String vnfInstanceId, String volumeGroupId,
+ String instanceName, String requestId) {
+ HashMap<String, String> instanceIdMap = new HashMap<>();
+ instanceIdMap.put("serviceInstanceId", serviceInstanceId);
+ instanceIdMap.put("vnfInstanceId", vnfInstanceId);
+ instanceIdMap.put("volumeGroupInstanceId", volumeGroupId);
+ checkDuplicateRequest(instanceIdMap, ModelType.volumeGroup, instanceName, requestId);
+ }
+
+}
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 d79d73c036..d3fb7986ce 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
@@ -38,10 +38,10 @@ 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.HttpStatus;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.apihandlerinfra.Constants;
-import org.onap.so.apihandlerinfra.Status;
import org.onap.so.apihandlerinfra.exceptions.ApiException;
import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
import org.onap.so.apihandlerinfra.exceptions.ValidateException;
@@ -50,6 +50,7 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.Action;
import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment;
import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestReferences;
import org.onap.so.apihandlerinfra.tenantisolationbeans.TenantSyncResponse;
+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.exceptions.ValidationException;
@@ -125,7 +126,7 @@ public class CloudOrchestration {
private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
String version, String requestId) throws ApiException {
- logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
+ logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
long startTime = System.currentTimeMillis();
CloudOrchestrationRequest cor = null;
tenantIsolationRequest.setRequestId(requestId);
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 be6d5b06ca..e9cd303c0b 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
@@ -88,11 +88,11 @@ public class CloudResourcesOrchestration {
public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId,
@PathParam("version") String version) throws ApiException {
TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId);
- InfraActiveRequests infraActiveRequest = null;
+ InfraActiveRequests infraActiveRequest;
- CloudOrchestrationRequest cor = null;
+ CloudOrchestrationRequest cor;
- logger.debug("requestId is: " + requestId);
+ logger.debug("requestId is: {}", requestId);
try {
ObjectMapper mapper = new ObjectMapper();
@@ -140,8 +140,8 @@ public class CloudResourcesOrchestration {
} else {
String status = infraActiveRequest.getRequestStatus();
- if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING")
- || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) {
+ if ("IN_PROGRESS".equalsIgnoreCase(status) || "PENDING".equalsIgnoreCase(status)
+ || "PENDING_MANUAL_TASK".equalsIgnoreCase(status)) {
infraActiveRequest.setRequestStatus("UNLOCKED");
infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
infraActiveRequest.setRequestId(requestId);
@@ -181,8 +181,7 @@ public class CloudResourcesOrchestration {
String requestId = requestIdKey.get(0);
CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
- TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest(requestId);
- InfraActiveRequests requestDB = null;
+ InfraActiveRequests requestDB;
try {
requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
@@ -213,8 +212,8 @@ public class CloudResourcesOrchestration {
} else {
TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest();
- List<InfraActiveRequests> activeRequests = null;
- CloudOrchestrationRequestList orchestrationList = null;
+ List<InfraActiveRequests> activeRequests;
+ CloudOrchestrationRequestList orchestrationList;
Map<String, String> orchestrationMap;
@@ -233,7 +232,7 @@ public class CloudResourcesOrchestration {
}
activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
orchestrationList = new CloudOrchestrationRequestList();
- List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
+ List<CloudOrchestrationResponse> requestLists = new ArrayList<>();
for (InfraActiveRequests infraActive : activeRequests) {
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 b2933df030..ef5abe9f74 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
@@ -75,8 +75,7 @@ public class ModelDistributionRequest {
@Transactional
public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version,
@PathParam("distributionId") String distributionId) throws ApiException {
- long startTime = System.currentTimeMillis();
- Distribution distributionRequest = null;
+ Distribution distributionRequest;
try {
ObjectMapper mapper = new ObjectMapper();
@@ -138,15 +137,13 @@ 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);
- String requestErrorStr = null;
+ String requestErrorStr;
try {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_DEFAULT);
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 696616099f..6449b0bb75 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
@@ -30,7 +30,6 @@ import java.util.Map.Entry;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.commons.lang3.StringUtils;
import org.onap.so.apihandlerinfra.Constants;
-import org.onap.so.apihandlerinfra.Status;
import org.onap.so.apihandlerinfra.tenantisolationbeans.Action;
import org.onap.so.apihandlerinfra.tenantisolationbeans.Manifest;
import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment;
@@ -42,11 +41,10 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters;
import org.onap.so.apihandlerinfra.tenantisolationbeans.ResourceType;
import org.onap.so.apihandlerinfra.tenantisolationbeans.ServiceModelList;
import org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType;
+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.exceptions.ValidationException;
-import org.onap.so.logger.ErrorCode;
-import org.onap.so.logger.MessageEnum;
import org.onap.so.utils.UUIDChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -94,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);
}
@@ -327,6 +326,7 @@ public class TenantIsolationRequest {
orchestrationFilterParams.put(queryParam, value);
}
} catch (Exception e) {
+ logger.error("Exception in getOrchestrationFilters", e);
throw new ValidationException(e.getMessage(), true);
}
}
@@ -356,8 +356,7 @@ public class TenantIsolationRequest {
request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
requestsDbClient.save(request);
} catch (Exception e) {
- logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
- ErrorCode.DataError.getValue(), "Exception when updating record in DB");
+ logger.error("Exception when updating record in DB", e);
logger.debug("Exception: ", e);
}
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java
index 8b3b91ae1a..6942d441e6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java
@@ -34,15 +34,13 @@ 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.client.graphinventory.entities.uri.Depth;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class AAIClientHelper {
- private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class);
+
/**
* Get managing ECOMP Environment Info from A&AI
@@ -63,7 +61,7 @@ public class AAIClientHelper {
* Update managing ECOMP Environment Info from A&AI
*
* @param id = operationalEnvironmentId
- * @param AAIOperationalEnvironment object
+ * @param aaiRequest object
*/
public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest) {
@@ -75,7 +73,7 @@ public class AAIClientHelper {
public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload)
- throws Exception {
+ throws AAIClientCallFailed {
try {
AAIResourceUri uri =
AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId);
@@ -90,7 +88,7 @@ public class AAIClientHelper {
/**
* Create an Operational Environment object in A&AI
*
- * @param AAIOperationalEnvironment object
+ * @param operationalEnvironment object
*/
public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment) {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java
index 98b49d39d7..1e5958c540 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java
@@ -31,7 +31,7 @@ import org.springframework.stereotype.Component;
@Component
public class ActivateVnfDBHelper {
- private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class);
+
/**
* Insert record to OperationalEnvServiceModelStatus table
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..18ca6d3086 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
@@ -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}")
@@ -89,12 +96,11 @@ public class SDCClientHelper {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
.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);
@@ -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;
@@ -139,11 +145,9 @@ public class SDCClientHelper {
ErrorLoggerInfo errorLoggerInfo =
new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
.build();
- ValidateException validateException =
- new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST,
- ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
- throw validateException;
+ 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/ActivateVnfStatusOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java
index 3005abaf9b..3226a0c313 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());
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
index fe81a07212..5eb4a67fa6 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java
@@ -145,7 +145,7 @@ public class CreateVnfOperationalEnvironment {
throws TenantIsolationException {
List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList();
logger.debug("Number of service endpoints from GRM: {}", endpointList.size());
- List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>();
+ List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<>();
for (ServiceEndPoint serviceEndpoint : endpointList) {
serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint));
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java
index 4c66a3118e..c50f18c594 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java
@@ -34,7 +34,7 @@ public class Manifest implements Serializable {
private static final long serialVersionUID = -3460949513229380541L;
@JsonProperty("serviceModelList")
- private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>();
+ private List<ServiceModelList> serviceModelList = new ArrayList<>();
public List<ServiceModelList> getServiceModelList() {
return serviceModelList;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java
index 907bc942eb..2cf01f9390 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java
@@ -29,51 +29,59 @@ import org.onap.so.utils.UUIDChecker;
public class InstanceIdMapValidation implements ValidationRule {
+ private static final String Service_InstanceId = "serviceInstanceId";
+ private static final String Vnf_InstanceId = "vnfInstanceId";
+ private static final String vfModule_InstanceId = "vfModuleInstanceId";
+
+ private static final String volume_Group_InstanceId = "volumeGroupInstanceId";
+ private static final String Network_Instance_Id = "networkInstanceId";
+ private static final String Configuration_Instance_Id = "configurationInstanceId";
+
@Override
public ValidationInformation validate(ValidationInformation info) throws ValidationException {
HashMap<String, String> instanceIdMap = info.getInstanceIdMap();
ServiceInstancesRequest sir = info.getSir();
if (instanceIdMap != null) {
- if (instanceIdMap.get("serviceInstanceId") != null) {
- if (!UUIDChecker.isValidUUID(instanceIdMap.get("serviceInstanceId"))) {
- throw new ValidationException("serviceInstanceId");
+ if (instanceIdMap.get(Service_InstanceId) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(Service_InstanceId))) {
+ throw new ValidationException(Service_InstanceId);
}
- sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
+ sir.setServiceInstanceId(instanceIdMap.get(Service_InstanceId));
}
- if (instanceIdMap.get("vnfInstanceId") != null) {
- if (!UUIDChecker.isValidUUID(instanceIdMap.get("vnfInstanceId"))) {
- throw new ValidationException("vnfInstanceId");
+ if (instanceIdMap.get(Vnf_InstanceId) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(Vnf_InstanceId))) {
+ throw new ValidationException(Vnf_InstanceId);
}
- sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId"));
+ sir.setVnfInstanceId(instanceIdMap.get(Vnf_InstanceId));
}
- if (instanceIdMap.get("vfModuleInstanceId") != null) {
- if (!UUIDChecker.isValidUUID(instanceIdMap.get("vfModuleInstanceId"))) {
- throw new ValidationException("vfModuleInstanceId");
+ if (instanceIdMap.get(vfModule_InstanceId) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(vfModule_InstanceId))) {
+ throw new ValidationException(vfModule_InstanceId);
}
- sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId"));
+ sir.setVfModuleInstanceId(instanceIdMap.get(vfModule_InstanceId));
}
- if (instanceIdMap.get("volumeGroupInstanceId") != null) {
- if (!UUIDChecker.isValidUUID(instanceIdMap.get("volumeGroupInstanceId"))) {
- throw new ValidationException("volumeGroupInstanceId");
+ if (instanceIdMap.get(volume_Group_InstanceId) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(volume_Group_InstanceId))) {
+ throw new ValidationException(volume_Group_InstanceId);
}
- sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId"));
+ sir.setVolumeGroupInstanceId(instanceIdMap.get(volume_Group_InstanceId));
}
- if (instanceIdMap.get("networkInstanceId") != null) {
- if (!UUIDChecker.isValidUUID(instanceIdMap.get("networkInstanceId"))) {
- throw new ValidationException("networkInstanceId");
+ if (instanceIdMap.get(Network_Instance_Id) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(Network_Instance_Id))) {
+ throw new ValidationException(Network_Instance_Id);
}
- sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId"));
+ sir.setNetworkInstanceId(instanceIdMap.get(Network_Instance_Id));
}
- if (instanceIdMap.get("configurationInstanceId") != null) {
- if (!UUIDChecker.isValidUUID(instanceIdMap.get("configurationInstanceId"))) {
- throw new ValidationException("configurationInstanceId");
+ if (instanceIdMap.get(Configuration_Instance_Id) != null) {
+ if (!UUIDChecker.isValidUUID(instanceIdMap.get(Configuration_Instance_Id))) {
+ throw new ValidationException(Configuration_Instance_Id);
}
- sir.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
+ sir.setConfigurationId(instanceIdMap.get(Configuration_Instance_Id));
}
if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
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 c80e89e21d..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
@@ -23,9 +23,9 @@ package org.onap.so.apihandlerinfra.validation;
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.Actions;
-import org.onap.so.apihandlerinfra.ModelType;
import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.LineOfBusiness;
+import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.Platform;
public class PlatformLOBValidation implements ValidationRule {
@@ -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 60e1274469..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
@@ -23,8 +23,8 @@ package org.onap.so.apihandlerinfra.validation;
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.Actions;
-import org.onap.so.apihandlerinfra.ModelType;
import org.onap.so.exceptions.ValidationException;
+import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.OwningEntity;
import org.onap.so.serviceinstancebeans.Project;
@@ -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/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java
index b02bd95d97..3b87d91d3f 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java
@@ -119,12 +119,25 @@ public class RelatedInstancesValidation implements ValidationRule {
isRelatedServiceInstancePresent = true;
}
+ if (requestScope.equalsIgnoreCase(ModelType.service.name())) {
+ if (empty(relatedInstance.getInstanceName())
+ && ModelType.vpnBinding.equals(relatedInstanceModelInfo.getModelType())) {
+ throw new ValidationException("instanceName in relatedInstance for vpnBinding modelType", true);
+ }
+ if (empty(relatedInstance.getInstanceName())
+ && ModelType.network.equals(relatedInstanceModelInfo.getModelType())) {
+ throw new ValidationException("instanceName in relatedInstance for network modelType", true);
+ }
+ }
+
if (action != Action.deleteInstance
&& !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
if (!(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)
|| relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint)
|| relatedInstanceModelInfo.getModelType().equals(ModelType.pnf)
- || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) {
+ || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup)
+ || relatedInstanceModelInfo.getModelType().equals(ModelType.network)
+ || relatedInstanceModelInfo.getModelType().equals(ModelType.vpnBinding))) {
if (empty(relatedInstanceModelInfo.getModelInvariantId())) {
throw new ValidationException("modelInvariantId in relatedInstance");
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java
index 2236b09f2a..7a0a6fe633 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java
@@ -49,8 +49,7 @@ import javax.xml.namespace.QName;
public class ObjectFactory {
private final static QName _VnfParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "vnf-params");
- private final static QName _NetworkParams_QNAME =
- new QName("http://org.onap/so/infra/vnf-request/v1", "network-params");
+
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-local.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-local.yaml
deleted file mode 100644
index a39d28038c..0000000000
--- a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-local.yaml
+++ /dev/null
@@ -1,179 +0,0 @@
-# will be used as entry in DB to say SITE OFF/ON for healthcheck
-
-server:
- port: 8080
- tomcat:
- max-threads: 50
-ssl-enable: false
-
-apih-healthcheck-urn: /ecomp/mso/healthcheck,/ecomp/mso/homing/healthcheck,/ecomp/mso/infra/healthcheck,/asdc/healthcheck,/dbadapters/healthcheck,/ecomp/mso/catalog/v2/healthcheck
-jra-healthcheck-urn: /networks/rest/healthcheck,/adapters/rest/healthcheck,/vnfs/rest/healthcheck,/tenants/rest/healthcheck,/appc/rest/healthcheck,/workflows/messages/healthcheck
-camunda-healthcheck-urn: /mso/healthcheck
-
-apih-nodehealthcheck-urn: /ecomp/mso/infra/nodehealthcheck
-jra-nodehealthcheck-urn: /adapters/rest/nodehealthcheck
-camunda-nodehealthcheck-urn: /mso/nodehealthcheck
-
-
-
-mso:
- health:
- endpoints:
- catalogdb: http://localhost:8800
- sdnc: http://localhost:8400
- openstack: http://localhost:8300
- requestdb: http://localhost:8700
- bpmn: http://localhost:8200
- asdc: http://localhost:8400
- requestdbattsvc: http://localhost:8600
-
- adapters:
- requestDb:
- auth: Basic YnBlbDptc28tZGItMTUwNyE=
- endpoint: http://localhost:8081
- logPath: logs
- site-name: mtanj
- catalog:
- db:
- spring:
- endpoint: "http://localhost:8080"
- db:
- auth: Basic YnBlbDptc28tZGItMTUwNyE=
- config:
- path: /src/main/resources/
- infra:
- default:
- alacarte:
- orchestrationUri: /mso/async/services/ALaCarteOrchestrator
- recipeTimeout: 180
- testApi: VNF_API
- service:
- macro:
- default:
- testApi: GR_API
- apih:
- homing:
- sdna:
- url: http://localhost:8089/
- password: 4E0BDC08EE8EDC0572ABBE9FD2D59B62DB725A00B8469E39393D6C86D64284C5D34A57D56F7B58C375316F
- camundaURL: http://localhost:8089/
- camundaAuth: E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE
- async:
- core-pool-size: 50
- max-pool-size: 50
- queue-capacity: 500
- sdc:
- client:
- auth: 97FF88AB352DA16E00DDD81E3876431DEF8744465DACA489EB3B3BE1F10F63EDA1715E626D0A4827A3E19CD88421BF
- activate:
- instanceid: test
- userid: cs0008
- endpoint: http://localhost:28090
- msoKey: 07a7159d3bf51a0e53be7a8f89699be7
- tenant:
- isolation:
- retry:
- count: 3
- aai:
- endpoint: http://localhost:28090
- auth: 5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C
- grm:
- endpoint: http://localhost:28090
- username: gmruser
- password: test
- so:
- operational-environment:
- dmaap:
- username: testuser
- password: VjR5NDcxSzA=
- host: http://localhost:28090
- publisher:
- topic: com.att.ecomp.mso.operationalEnvironmentEvent
-
-# controls what actions the infra API (APIH) allows sent in on REST request
-vnf:
- v1:
- ApiAllowableActions:
- v2:
- ApiAllowableActions:
- v3:
- ApiAllowableActions:
-
-network:
- v1:
- ApiAllowableActions:
- v2:
- ApiAllowableActions:
- v3:
- ApiAllowableActions:
-
-volume:
- v1:
- ApiAllowableActions:
- v2:
- ApiAllowableActions:
- v3:
- ApiAllowableActions:
-
-# H2
-spring:
- datasource:
- url: jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
- username: sa
- password: sa
- driver-class-name: org.h2.Driver
- intialize: true
- h2:
- console:
- enabled: true
- path: /h2
-
- jpa:
- show-sql: true
- hibernate:
- dialect: org.hibernate.dialect.H2Dialect
- ddl-auto: validate
- naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
- enable_lazy_load_no_trans: true
- jersey:
- type: filter
- security:
- usercredentials:
- -
- username: sitecontrol
- password: '$2a$12$VBUF.qBmeK1FNyO2MqTpD.P2M1tvlesZlhCkAjjHvF9hmYNVdMDmu'
- role: SiteControl-Client
- -
- username: gui
- password: '$2a$12$9Y4daXavh.oX5fz6t/e7TuCdj7EKW5B5ibqq425fN3/xpp0/Fhyti'
- role: GUI-Client
- -
- username: infraportal
- password: '$2a$12$IpUEhQijWTNbq0fGYVkA9upZrDvdIK6QfblIaKAiwi0vBQRE.C6Ri'
- role: InfraPortal-Client
- -
- username: bpel
- password: '$2a$12$1xyutEZNfjGewIZRfKaE8eZE99f5sYFUmmM80BobI65KNjmcK0JuO'
- role: BPEL-Client
- -
- username: mso_admin
- password: '$2a$12$tidKuu.h88E2nuL95pTVY.ZOYMN/1dp29A9b1o.0GFDsVVSYlMkHa'
- role: ACTUATOR
-request:
- datasource:
- url: jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
- username: sa
- password: sa
- driver-class-name: org.h2.Driver
- intialize: true
-
-#Actuator
-management:
- context-path: /manage
-
-org:
- onap:
- so:
- adapters:
- network:
- encryptionKey: aa3871669d893c7fb8abbcda31b88b4f
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml
index 03934edf20..babefd9478 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml
+++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application.yaml
@@ -26,13 +26,20 @@ mso:
uri: /sobpmnengine/task
history:
uri: /sobpmnengine/history/process-instance?variables=mso-request-id_eq_
+ activity:
+ uri: /sobpmnengine/history/activity-instance?processInstanceId=
+ camundaURL: http://localhost:8089
+ camundaAuth: E8E19DD16CC90D2E458E8FF9A884CC0452F8F3EB8E321F96038DE38D5C1B0B02DFAE00B88E2CF6E2A4101AB2C011FC161212EE
spring:
datasource:
- jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb
- username: ${DB_USERNAME}
- password: ${DB_PASSWORD}
- driver-class-name: org.mariadb.jdbc.Driver
+ hikari:
+ jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/catalogdb
+ username: ${DB_USERNAME}
+ password: ${DB_PASSWORD}
+ driver-class-name: org.mariadb.jdbc.Driver
+ pool-name: catdb-pool
+ registerMbeans: true
jpa:
show-sql: true
hibernate:
@@ -42,14 +49,18 @@ spring:
enable-lazy-load-no-trans: true
jersey:
type: filter
+ main:
+ allow-bean-definition-overriding: true
request:
datasource:
- jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/requestdb
- username: ${DB_USERNAME}
- password: ${DB_PASSWORD}
- driver-class-name: org.mariadb.jdbc.Driver
-
+ hikari:
+ jdbcUrl: jdbc:mariadb://${DB_HOST}:${DB_PORT}/requestdb
+ username: ${DB_USERNAME}
+ password: ${DB_PASSWORD}
+ driver-class-name: org.mariadb.jdbc.Driver
+ pool-name: reqdb-pool
+ registerMbeans: true
#Actuator
management:
endpoints:
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
new file mode 100644
index 0000000000..830f38f98b
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java
@@ -0,0 +1,340 @@
+/*-
+ * ============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.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.Collections;
+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.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;
+
+ @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");
+ }
+
+ 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() {
+ String expectedActivityName = "Last task executed: BB to Execute";
+ String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
+
+ assertEquals(expectedActivityName, actualActivityName);
+ }
+
+ @Test
+ public void getActivityNameNullActivityNameTest() {
+ 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() {
+ 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() {
+ 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 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 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 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 getTaskNameEmptyProcessInstanceListTest() throws ContactCamundaException {
+ ResponseEntity<List<HistoricProcessInstanceEntity>> response =
+ new ResponseEntity<>(Collections.emptyList(), 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 getTaskNameProcessInstanceLookupFailureTest() throws ContactCamundaException {
+ doThrow(HttpClientErrorException.class).when(camundaRequestHandler)
+ .getCamundaProcessInstanceHistory(REQUEST_ID);
+
+ thrown.expect(ContactCamundaException.class);
+ camundaRequestHandler.getTaskName(REQUEST_ID);
+ }
+
+ @Test
+ public void getCamundaActivityHistoryTest() throws 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() {
+ 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() {
+ 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() {
+ 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/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/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java
index c30b9dedf2..86bf8060a7 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
@@ -24,13 +24,11 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.StringReader;
-import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
-import java.util.Optional;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.xml.parsers.DocumentBuilder;
@@ -46,13 +44,13 @@ import org.onap.so.exceptions.ValidationException;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
-import org.w3c.dom.Document;
-import org.xml.sax.InputSource;
@RunWith(JUnitParamsRunner.class)
public class MsoRequestTest extends BaseTest {
@@ -83,6 +81,12 @@ public class MsoRequestTest extends BaseTest {
return input;
}
+ public String inputStreamVpnBonding(String JsonInput) throws IOException {
+ JsonInput = "src/test/resources/Validation" + JsonInput;
+ String input = new String(Files.readAllBytes(Paths.get(JsonInput)));
+ return input;
+ }
+
// Tests for successful validation of incoming JSON requests through the parse method
@Test
@Parameters(method = "successParameters")
@@ -188,6 +192,8 @@ public class MsoRequestTest extends BaseTest {
instanceIdMapTest, Action.addRelationships, "5"},
{mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"),
ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"},
+ {mapper.readValue(inputStream("/RelatedInstances/ServiceInstanceVpnBondingService.json"),
+ ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "7"},
{mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"),
ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}});
}
@@ -546,6 +552,22 @@ public class MsoRequestTest extends BaseTest {
mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"),
ServiceInstancesRequest.class),
instanceIdMapTest, Action.addRelationships, 6},
+ {"No valid modelType in relatedInstance is specified",
+ mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoModelType.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ {"No valid instanceId in relatedInstance is specified",
+ mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceId.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ {"No valid instanceName in relatedInstance for vpnBinding modelType is specified",
+ mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceNameVpnBinding.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
+ {"No valid instanceName in relatedInstance for network modelType is specified",
+ mapper.readValue(inputStreamVpnBonding("/VpnBondingValidation/NoInstanceNameNetwork.json"),
+ ServiceInstancesRequest.class),
+ instanceIdMapTest, Action.createInstance, 7},
{"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified",
mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"),
ServiceInstancesRequest.class),
@@ -1038,20 +1060,5 @@ public class MsoRequestTest extends BaseTest {
assertNotNull(result);
}
- @Test
- public void buildSelfLinkUrlTest() throws Exception {
- // v - version
- String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances";
- String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1";
- String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1";
- this.msoRequest = new MsoRequest();
- Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId);
- assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString());
- // V - Version
- String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances";
- String expectedSelfLinkV =
- "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1";
- Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId);
- assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString());
- }
+
}
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 321ea3ac7d..12f0ffcc11 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java
@@ -26,6 +26,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.shazam.shazamcrest.MatcherAssert.assertThat;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
@@ -42,12 +43,13 @@ import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.http.HttpStatus;
-import org.junit.Ignore;
+import org.junit.Before;
import org.junit.Test;
import org.onap.so.apihandler.common.ErrorNumbers;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.db.request.client.RequestsDbClient;
import org.onap.so.exceptions.ValidationException;
+import org.onap.so.serviceinstancebeans.CloudRequestData;
import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse;
import org.onap.so.serviceinstancebeans.GetOrchestrationResponse;
import org.onap.so.serviceinstancebeans.Request;
@@ -92,6 +94,21 @@ public class OrchestrationRequestsTest extends BaseTest {
return list;
}
+ @Before
+ public void setup() throws IOException {
+ wireMockServer.stubFor(get(urlMatching("/sobpmnengine/history/process-instance.*")).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(
+ Paths.get("src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json"))))
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+ wireMockServer.stubFor(
+ get(("/sobpmnengine/history/activity-instance?processInstanceId=c4c6b647-a26e-11e9-b144-0242ac14000b"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(Paths.get(
+ "src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json"))))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
@Test
public void testGetOrchestrationRequest() throws Exception {
setupTestGetOrchestrationRequest();
@@ -119,7 +136,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-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0));
+ assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0));
assertNotNull(response.getBody().getRequest().getFinishTime());
}
@@ -149,12 +166,22 @@ public class OrchestrationRequestsTest extends BaseTest {
}
@Test
- public void testGetOrchestrationRequestRequestDetails() throws Exception {
- setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED");
+ public void testGetOrchestrationRequestWithOpenstackDetails() throws Exception {
+ setupTestGetOrchestrationRequestOpenstackDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED");
// Test request with modelInfo request body
GetOrchestrationResponse testResponse = new GetOrchestrationResponse();
Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest();
+ List<CloudRequestData> cloudRequestData = new ArrayList<>();
+ CloudRequestData cloudData = new CloudRequestData();
+ cloudData.setCloudIdentifier("heatstackName/123123");
+ ObjectMapper mapper = new ObjectMapper();
+ Object reqData = mapper.readValue(
+ "{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}",
+ Object.class);
+ cloudData.setCloudRequest(reqData);
+ cloudRequestData.add(cloudData);
+ request.setCloudRequestData(cloudRequestData);
testResponse.setRequest(request);
String testRequestId = request.getRequestId();
@@ -163,13 +190,14 @@ public class OrchestrationRequestsTest extends BaseTest {
headers.set("Content-Type", MediaType.APPLICATION_JSON);
HttpEntity<Request> entity = new HttpEntity<Request>(null, headers);
- UriComponentsBuilder builder = UriComponentsBuilder
- .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId));
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(
+ "/onap/so/infra/orchestrationRequests/v7/" + testRequestId + "?includeCloudRequest=true"));
ResponseEntity<GetOrchestrationResponse> response =
restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
-
+ System.out.println("Response :" + response.getBody().toString());
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));
@@ -194,6 +222,29 @@ public class OrchestrationRequestsTest extends BaseTest {
}
@Test
+ public void testGetOrchestrationRequestInvalidRequestID() throws Exception {
+ setupTestGetOrchestrationRequest();
+ // TEST INVALID REQUESTID
+ GetOrchestrationResponse testResponse = new GetOrchestrationResponse();
+
+ Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest();
+ testResponse.setRequest(request);
+ String testRequestId = "00032ab7-pfb3-42e5-965d-8ea592502016";
+ HttpHeaders headers = new HttpHeaders();
+ headers.set("Accept", MediaType.APPLICATION_JSON);
+ headers.set("Content-Type", MediaType.APPLICATION_JSON);
+ HttpEntity<Request> entity = new HttpEntity<Request>(null, headers);
+
+ UriComponentsBuilder builder = UriComponentsBuilder
+ .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId));
+
+ ResponseEntity<GetOrchestrationResponse> response =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
+
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value());
+ }
+
+ @Test
public void testGetOrchestrationRequestFilter() throws Exception {
setupTestGetOrchestrationRequestFilter();
List<String> values = new ArrayList<>();
@@ -319,75 +370,11 @@ public class OrchestrationRequestsTest extends BaseTest {
"/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock"));
response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class);
- // Cannot assert anything further here, already have a wiremock in place which ensures that the post was
+ // Cannot assert anything further here, already have a wiremock in place
+ // which ensures that the post was
// properly called to update.
}
- @Ignore // What is this testing?
- @Test
- public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception {
- InfraActiveRequests requests = new InfraActiveRequests();
- requests.setAction("create");
- requests.setRequestBody(" ");
- requests.setRequestId("requestId");
- requests.setRequestScope("service");
- requests.setRequestType("createInstance");
- ObjectMapper mapper = new ObjectMapper();
- String json = mapper.writeValueAsString(requests);
-
- requestsDbClient.save(requests);
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<Request> entity = new HttpEntity<Request>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder
- .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId"));
-
- ResponseEntity<GetOrchestrationResponse> response =
- restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
- 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("requestId", response.getHeaders().get("X-TransactionID").get(0));
- }
-
- @Ignore // What is this testing?
- @Test
- public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException {
- InfraActiveRequests requests = new InfraActiveRequests();
-
- String requestJSON = new String(
- Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json")));
-
- requests.setAction("create");
- requests.setRequestBody(requestJSON);
- requests.setRequestId("requestId");
- requests.setRequestScope("service");
- requests.setRequestType("createInstance");
- // iar.save(requests);
- HttpHeaders headers = new HttpHeaders();
- headers.set("Accept", MediaType.APPLICATION_JSON);
- headers.set("Content-Type", MediaType.APPLICATION_JSON);
- HttpEntity<Request> entity = new HttpEntity<Request>(null, headers);
-
- UriComponentsBuilder builder = UriComponentsBuilder
- .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId"));
-
- ResponseEntity<GetOrchestrationResponse> response =
- restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class);
-
- assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value());
- assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0));
- 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("requestId", response.getHeaders().get("X-TransactionID").get(0));
- }
-
@Test
public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException {
RequestProcessingData entry = new RequestProcessingData();
@@ -423,14 +410,14 @@ public class OrchestrationRequestsTest extends BaseTest {
public void setupTestGetOrchestrationRequest() throws Exception {
// For testGetOrchestrationRequest
- wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018"))
+ wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(new String(Files.readAllBytes(
Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json"))))
.withStatus(HttpStatus.SC_OK)));
wireMockServer
.stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/"))
- .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018"))
+ .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(new String(Files.readAllBytes(Paths
.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json"))))
@@ -439,14 +426,14 @@ public class OrchestrationRequestsTest extends BaseTest {
public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception {
// For testGetOrchestrationRequest
- wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018"))
+ wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(new String(Files.readAllBytes(Paths.get(
"src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json"))))
.withStatus(HttpStatus.SC_OK)));
wireMockServer
.stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/"))
- .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018"))
+ .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-1a18-42e5-965d-8ea592502018"))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(new String(Files.readAllBytes(Paths
.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json"))))
@@ -461,15 +448,20 @@ public class OrchestrationRequestsTest extends BaseTest {
.withStatus(HttpStatus.SC_OK)));
}
+ private void setupTestGetOrchestrationRequestOpenstackDetails(String requestId, String status) throws Exception {
+ wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse()
+ .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(new String(Files.readAllBytes(Paths
+ .get("src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json"))))
+ .withStatus(HttpStatus.SC_OK)));
+ }
+
private void setupTestUnlockOrchestrationRequest(String requestId, String status) {
wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId)))
.willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK)));
-
}
-
-
private void setupTestUnlockOrchestrationRequest_invalid_Json() {
wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse()
.withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND)));
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
new file mode 100644
index 0000000000..627bbc631d
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java
@@ -0,0 +1,330 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.apihandlerinfra;
+
+import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
+import static org.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;
+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.junit.MockitoJUnitRunner;
+import org.onap.so.apihandler.common.ResponseBuilder;
+import org.onap.so.apihandlerinfra.exceptions.ApiException;
+import org.onap.so.constants.OrchestrationRequestFormat;
+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.InstanceReferences;
+import org.onap.so.serviceinstancebeans.Request;
+import org.onap.so.serviceinstancebeans.RequestStatus;
+
+@RunWith(MockitoJUnitRunner.class)
+public class OrchestrationRequestsUnitTest {
+ @Mock
+ private RequestsDbClient requestDbClient;
+ @Mock
+ private MsoRequest msoRequest;
+ @Mock
+ private ResponseBuilder builder;
+ @Mock
+ private Response response;
+ @Mock
+ private CamundaRequestHandler camundaRequestHandler;
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+ @InjectMocks
+ private OrchestrationRequests orchestrationRequests;
+
+ private static final String REQUEST_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebba";
+ private static final String SERVICE_INSTANCE_ID = "7cb9aa56-dd31-41e5-828e-d93027d4ebbb";
+ private static final String ORIGINAL_REQUEST_ID = "8f2d38a6-7c20-465a-bd7e-075645f1394b";
+ private static final String SERVICE = "service";
+ private static final String EXT_SYSTEM_ERROR_SOURCE = "external system error source";
+ private static final String FLOW_STATUS = "FlowStatus";
+ private static final String RETRY_STATUS_MESSAGE = "RetryStatusMessage";
+ private static final String ROLLBACK_STATUS_MESSAGE = "RollbackStatusMessage";
+ private static final String TASK_INFORMATION = " TASK INFORMATION: Last task executed: Call SDNC";
+ private InfraActiveRequests iar;
+ boolean includeCloudRequest = false;
+ private static final String ROLLBACK_EXT_SYSTEM_ERROR_SOURCE = "SDNC";
+
+
+ @Before
+ public void setup() {
+ iar = new InfraActiveRequests();
+ iar.setRequestScope(SERVICE);
+ iar.setRequestId(REQUEST_ID);
+ iar.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ iar.setExtSystemErrorSource(EXT_SYSTEM_ERROR_SOURCE);
+ iar.setRollbackExtSystemErrorSource(ROLLBACK_EXT_SYSTEM_ERROR_SOURCE);
+ iar.setFlowStatus(FLOW_STATUS);
+ iar.setRollbackStatusMessage(ROLLBACK_STATUS_MESSAGE);
+ iar.setRetryStatusMessage(RETRY_STATUS_MESSAGE);
+ }
+
+ @Test
+ public void mapInfraActiveRequestToRequestWithOriginalRequestIdTest() throws ApiException {
+ doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID);
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s",
+ FLOW_STATUS + TASK_INFORMATION, RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setOriginalRequestId(ORIGINAL_REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ iar.setOriginalRequestId(ORIGINAL_REQUEST_ID);
+
+ Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+ assertThat(result, sameBeanAs(expected));
+ }
+
+ @Test
+ public void mapInfraActiveRequestToRequestOriginalRequestIdNullTest() throws ApiException {
+ doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID);
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s",
+ FLOW_STATUS + TASK_INFORMATION, RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ Request result = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+ assertThat(result, sameBeanAs(expected));
+ }
+
+ @Test
+ public void mapRequestStatusAndExtSysErrSrcToRequestFalseTest() throws ApiException {
+ doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID);
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s",
+ FLOW_STATUS + TASK_INFORMATION, RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ includeCloudRequest = false;
+
+ Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void mapRequestStatusAndExtSysErrSrcToRequestStatusDetailTest() throws ApiException {
+ doReturn(null).when(camundaRequestHandler).getTaskName(REQUEST_ID);
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setExtSystemErrorSource(EXT_SYSTEM_ERROR_SOURCE);
+ requestStatus.setRollbackExtSystemErrorSource(ROLLBACK_EXT_SYSTEM_ERROR_SOURCE);
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setFlowStatus(FLOW_STATUS);
+ requestStatus.setRollbackStatusMessage(ROLLBACK_STATUS_MESSAGE);
+ requestStatus.setRetryStatusMessage(RETRY_STATUS_MESSAGE);
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ includeCloudRequest = false;
+
+ Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.STATUSDETAIL.toString());
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void mapRequestStatusAndExtSysErrSrcToRequestDetailTest() throws ApiException {
+ doReturn("Last task executed: Call SDNC").when(camundaRequestHandler).getTaskName(REQUEST_ID);
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s",
+ FLOW_STATUS + TASK_INFORMATION, RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ includeCloudRequest = false;
+
+ Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void mapRequestStatusAndExtSysErrSrcToRequestNoFlowStatusTest() throws ApiException {
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(
+ String.format("RETRY STATUS: %s ROLLBACK STATUS: %s", RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ includeCloudRequest = false;
+ iar.setFlowStatus(null);
+
+ Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @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);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s",
+ "Successfully completed all Building Blocks", RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ includeCloudRequest = false;
+ iar.setFlowStatus("Successfully completed all Building Blocks");
+
+ Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void mapRequestStatusAndExtSysErrSrcToRequestFlowStatusSuccessfulRollbackTest() throws ApiException {
+ InstanceReferences instanceReferences = new InstanceReferences();
+ instanceReferences.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setRequestState(iar.getRequestStatus());
+ requestStatus.setStatusMessage(String.format("FLOW STATUS: %s RETRY STATUS: %s ROLLBACK STATUS: %s",
+ "All Rollback flows have completed successfully", RETRY_STATUS_MESSAGE, ROLLBACK_STATUS_MESSAGE));
+
+ Request expected = new Request();
+ expected.setRequestId(REQUEST_ID);
+ expected.setInstanceReferences(instanceReferences);
+ expected.setRequestStatus(requestStatus);
+ expected.setRequestScope(SERVICE);
+
+ includeCloudRequest = false;
+ iar.setFlowStatus("All Rollback flows have completed successfully");
+
+ Request actual = orchestrationRequests.mapInfraActiveRequestToRequest(iar, includeCloudRequest,
+ OrchestrationRequestFormat.DETAIL.toString());
+
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void requestStatusExtSystemErrorSourceTest() {
+ RequestStatus requestStatus = new RequestStatus();
+ requestStatus.setExtSystemErrorSource(EXT_SYSTEM_ERROR_SOURCE);
+ assertThat(requestStatus.getExtSystemErrorSource(), is(equalTo(EXT_SYSTEM_ERROR_SOURCE)));
+ }
+
+ @Test
+ public void mapRequestStatusToRequestForFormatDetailTest() throws ApiException {
+ iar.setRequestStatus(Status.ABORTED.toString());
+ String result =
+ orchestrationRequests.mapRequestStatusToRequest(iar, OrchestrationRequestFormat.DETAIL.toString());
+
+ 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 {
+ iar.setRequestStatus(Status.ABORTED.toString());
+ String result = orchestrationRequests.mapRequestStatusToRequest(iar, StringUtils.EMPTY);
+
+ assertEquals(Status.FAILED.toString(), result);
+ }
+}
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 dc0cd473c2..e4532cd8d7 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
@@ -27,6 +27,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID;
@@ -38,7 +39,6 @@ import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
-import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.MediaType;
import org.apache.http.HttpStatus;
import org.junit.Before;
@@ -50,6 +50,7 @@ import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.logger.HttpHeadersConstants;
import org.onap.so.serviceinstancebeans.ModelInfo;
+import org.onap.so.serviceinstancebeans.ModelType;
import org.onap.so.serviceinstancebeans.RequestDetails;
import org.onap.so.serviceinstancebeans.RequestInfo;
import org.onap.so.serviceinstancebeans.RequestParameters;
@@ -76,6 +77,9 @@ public class RequestHandlerUtilsTest extends BaseTest {
@Autowired
private RequestHandlerUtils requestHandlerUtils;
+ @Autowired
+ private CamundaRequestHandler camundaRequestHandler;
+
@Value("${wiremock.server.port}")
private String wiremockPort;
@@ -147,6 +151,18 @@ public class RequestHandlerUtilsTest extends BaseTest {
}
+ @Test
+ public void test_mapJSONtoMSOStyleCustomWorkflowRequest() throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setSerializationInclusion(Include.NON_NULL);
+ String testRequest = inputStream("/CustomWorkflowRequest.json");
+ String resultString =
+ requestHandlerUtils.mapJSONtoMSOStyle(testRequest, null, true, Action.inPlaceSoftwareUpdate);
+ ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class);
+ assertEquals(sir.getRequestDetails().getCloudConfiguration().getTenantId(), "88a6ca3ee0394ade9403f075db23167e");
+ assertNotEquals(sir.getRequestDetails().getRequestParameters().getUserParams().size(), 0);
+ }
+
@Test
public void test_mapJSONtoMSOStyleUsePreload() throws IOException {
@@ -327,7 +343,7 @@ public class RequestHandlerUtilsTest extends BaseTest {
public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException {
String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password
String key = "07a7159d3bf51a0e53be7a8f89699be7";
- HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key);
+ HttpHeaders headers = camundaRequestHandler.setCamundaHeaders(encryptedAuth, key);
List<org.springframework.http.MediaType> acceptedType = headers.getAccept();
String expectedAcceptedType = "application/json";
assertEquals(expectedAcceptedType, acceptedType.get(0).toString());
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java
new file mode 100644
index 0000000000..d4b0c3aad1
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java
@@ -0,0 +1,444 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.apihandlerinfra;
+
+import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.sql.Timestamp;
+import org.junit.Before;
+import org.junit.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.exceptions.ValidateException;
+import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.VfModule;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.serviceinstancebeans.ModelInfo;
+import org.onap.so.serviceinstancebeans.ModelType;
+
+@RunWith(MockitoJUnitRunner.class)
+public class RequestHandlerUtilsUnitTest {
+
+ @Mock
+ private CatalogDbClient catDbClient;
+
+ @InjectMocks
+ @Spy
+ private RequestHandlerUtils requestHandler;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4";
+ private static final String RESUMED_REQUEST_ID = "59c7247f-839f-4923-90c3-05faa3ab354d";
+ private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018";
+ private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName";
+ private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017";
+ private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016";
+ private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015";
+ private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014";
+ private static final String VNF_NAME = "vnfName";
+ private static final String VFMODULE_NAME = "vfModuleName";
+ private static final String NETWORK_NAME = "networkName";
+ private static final String VOLUME_GROUP_NAME = "volumeGroupName";
+ private static final String MODEL_VERSION_ID = "883f4a7a-b5a5-44e0-8738-361c6413d24c";
+ private static final String MODEL_VERSION = "1.0";
+ private static final String MODEL_INVARIANT_ID = "d358b828-e7f8-4833-ac96-2782bed1a9a9";
+ private static final String MODEL_NAME = "modelName";
+ private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+ private String requestUri =
+ "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume";
+ private InfraActiveRequests infraActiveRequest = new InfraActiveRequests();
+ private InfraActiveRequests currentActiveRequest = new InfraActiveRequests();
+ private InfraActiveRequests currentActiveRequestIARNull = new InfraActiveRequests();
+ private Action action = Action.createInstance;
+ private String vnfType = "vnfType";
+ private String sdcServiceModelVersion = "7";
+
+ public String getRequestBody(String request) throws IOException {
+ request = "src/test/resources/ResumeOrchestrationRequest" + request;
+ return new String(Files.readAllBytes(Paths.get(request)));
+ }
+
+ @Before
+ public void setup() throws IOException {
+ setInfraActiveRequest();
+ setCurrentActiveRequest();
+ setCurrentActiveRequestNullInfraActive();
+ }
+
+ private void setInfraActiveRequest() throws IOException {
+ infraActiveRequest.setTenantId("tenant-id");
+ infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json"));
+ infraActiveRequest.setAicCloudRegion("cloudRegion");
+ infraActiveRequest.setRequestScope("service");
+ infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME);
+ infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ infraActiveRequest.setRequestAction(Action.createInstance.toString());
+ infraActiveRequest.setServiceType("serviceType");
+ }
+
+ private void setCurrentActiveRequest() throws IOException {
+ currentActiveRequest.setRequestId(CURRENT_REQUEST_ID);
+ currentActiveRequest.setSource("VID");
+ currentActiveRequest.setStartTime(startTimeStamp);
+ currentActiveRequest.setTenantId("tenant-id");
+ currentActiveRequest.setRequestBody(getRequestBody("/RequestBodyNewRequestorId.json"));
+ currentActiveRequest.setAicCloudRegion("cloudRegion");
+ currentActiveRequest.setRequestScope("service");
+ currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ currentActiveRequest.setRequestAction(Action.createInstance.toString());
+ currentActiveRequest.setRequestUrl(requestUri);
+ currentActiveRequest.setRequestorId("yyyyyy");
+ currentActiveRequest.setProgress(new Long(5));
+ currentActiveRequest.setOriginalRequestId(RESUMED_REQUEST_ID);
+ }
+
+ private void setCurrentActiveRequestNullInfraActive() throws IOException {
+ currentActiveRequestIARNull.setRequestId(CURRENT_REQUEST_ID);
+ currentActiveRequestIARNull.setSource("VID");
+ currentActiveRequestIARNull.setStartTime(startTimeStamp);
+ currentActiveRequestIARNull.setRequestStatus(Status.IN_PROGRESS.toString());
+ currentActiveRequestIARNull.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ currentActiveRequestIARNull.setRequestUrl(requestUri);
+ currentActiveRequestIARNull.setRequestorId("xxxxxx");
+ currentActiveRequestIARNull.setProgress(new Long(5));
+ currentActiveRequestIARNull.setOriginalRequestId(RESUMED_REQUEST_ID);
+ }
+
+
+ @Test
+ public void createNewRecordCopyFromInfraActiveRequestTest() throws IOException, ApiException {
+ doNothing().when(requestHandler).setInstanceIdAndName(infraActiveRequest, currentActiveRequest);
+ doReturn(getRequestBody("/RequestBodyNewRequestorId.json")).when(requestHandler)
+ .updateRequestorIdInRequestBody(infraActiveRequest, "yyyyyy");
+ InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest,
+ CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "yyyyyy", RESUMED_REQUEST_ID);
+ assertThat(currentActiveRequest, sameBeanAs(result));
+ }
+
+ @Test
+ public void createNewRecordCopyFromInfraActiveRequestNullIARTest() throws ApiException {
+ InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID,
+ startTimeStamp, "VID", requestUri, "xxxxxx", RESUMED_REQUEST_ID);
+ assertThat(currentActiveRequestIARNull, sameBeanAs(result));
+ }
+
+ @Test
+ public void setInstanceIdAndNameServiceTest() throws ApiException {
+ InfraActiveRequests serviceRequest = new InfraActiveRequests();
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+ expected.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ expected.setServiceInstanceName(SERVICE_INSTANCE_NAME);
+
+ requestHandler.setInstanceIdAndName(infraActiveRequest, serviceRequest);
+ assertThat(serviceRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void setInstanceIdAndNameServiceNullInstanceNameTest() throws ApiException {
+ InfraActiveRequests serviceRequest = new InfraActiveRequests();
+
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ request.setRequestScope(ModelType.service.toString());
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+ expected.setServiceInstanceId(SERVICE_INSTANCE_ID);
+
+ requestHandler.setInstanceIdAndName(request, serviceRequest);
+ assertThat(serviceRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void setInstanceIdAndNameServiceNullInstanceNameVfModuleTest() throws ApiException {
+ InfraActiveRequests vfModuleRequest = new InfraActiveRequests();
+ String errorMessage =
+ "vfModule for requestId: 59c7247f-839f-4923-90c3-05faa3ab354d being resumed does not have an instanceName.";
+ doNothing().when(requestHandler).updateStatus(vfModuleRequest, Status.FAILED, errorMessage);
+
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setServiceInstanceId(VFMODULE_ID);
+ request.setRequestScope(ModelType.vfModule.toString());
+ request.setRequestId(RESUMED_REQUEST_ID);
+
+ thrown.expect(ValidateException.class);
+ thrown.expectMessage(errorMessage);
+
+ requestHandler.setInstanceIdAndName(request, vfModuleRequest);
+ }
+
+ @Test
+ public void setInstanceIdAndNameRequestScopeNotValidTest() throws ApiException {
+ InfraActiveRequests originalServiceRequest = new InfraActiveRequests();
+ originalServiceRequest.setRequestScope("test");
+ InfraActiveRequests serviceRequest = new InfraActiveRequests();
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+
+ requestHandler.setInstanceIdAndName(originalServiceRequest, serviceRequest);
+ assertThat(serviceRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void setInstanceIdAndNameVnfTest() throws ApiException {
+ InfraActiveRequests vnfRequestOriginal = new InfraActiveRequests();
+ vnfRequestOriginal.setRequestScope("vnf");
+ vnfRequestOriginal.setVnfId(VNF_ID);
+ vnfRequestOriginal.setVnfName(VNF_NAME);
+ InfraActiveRequests vnfRequest = new InfraActiveRequests();
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+ expected.setVnfId(VNF_ID);
+ expected.setVnfName(VNF_NAME);
+
+ requestHandler.setInstanceIdAndName(vnfRequestOriginal, vnfRequest);
+ assertThat(vnfRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void setInstanceIdAndNameVfModuleTest() throws ApiException {
+ InfraActiveRequests vfModuleRequestOriginal = new InfraActiveRequests();
+ vfModuleRequestOriginal.setRequestScope("vfModule");
+ vfModuleRequestOriginal.setVfModuleId(VFMODULE_ID);
+ vfModuleRequestOriginal.setVfModuleName(VFMODULE_NAME);
+ InfraActiveRequests vfModuleRequest = new InfraActiveRequests();
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+ expected.setVfModuleId(VFMODULE_ID);
+ expected.setVfModuleName(VFMODULE_NAME);
+
+ requestHandler.setInstanceIdAndName(vfModuleRequestOriginal, vfModuleRequest);
+ assertThat(vfModuleRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void setInstanceIdAndNameNetworkTest() throws ApiException {
+ InfraActiveRequests networkRequestOriginal = new InfraActiveRequests();
+ networkRequestOriginal.setRequestScope("network");
+ networkRequestOriginal.setNetworkId(NETWORK_ID);
+ networkRequestOriginal.setNetworkName(NETWORK_NAME);
+ InfraActiveRequests networkRequest = new InfraActiveRequests();
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+ expected.setNetworkId(NETWORK_ID);
+ expected.setNetworkName(NETWORK_NAME);
+
+ requestHandler.setInstanceIdAndName(networkRequestOriginal, networkRequest);
+ assertThat(networkRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void setInstanceIdAndNameVolumeGroupTest() throws ApiException {
+ InfraActiveRequests volumeGroupRequestOriginal = new InfraActiveRequests();
+ volumeGroupRequestOriginal.setRequestScope("volumeGroup");
+ volumeGroupRequestOriginal.setVolumeGroupId(VOLUME_GROUP_ID);
+ volumeGroupRequestOriginal.setVolumeGroupName(VOLUME_GROUP_NAME);
+ InfraActiveRequests volumeGroupRequest = new InfraActiveRequests();
+
+ InfraActiveRequests expected = new InfraActiveRequests();
+ expected.setVolumeGroupId(VOLUME_GROUP_ID);
+ expected.setVolumeGroupName(VOLUME_GROUP_NAME);
+
+ requestHandler.setInstanceIdAndName(volumeGroupRequestOriginal, volumeGroupRequest);
+ assertThat(volumeGroupRequest, sameBeanAs(expected));
+ }
+
+ @Test
+ public void getIsBaseVfModuleTrueTest() throws ApiException {
+ VfModule vfModule = new VfModule();
+ vfModule.setIsBase(true);
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId(MODEL_VERSION_ID);
+
+ doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID);
+ Boolean expected = true;
+
+ Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion,
+ currentActiveRequest);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void getIsBaseVfModuleFalseTest() throws ApiException {
+ VfModule vfModule = new VfModule();
+ vfModule.setIsBase(false);
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId(MODEL_VERSION_ID);
+
+ doReturn(vfModule).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID);
+ Boolean expected = false;
+
+ Boolean result = requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion,
+ currentActiveRequest);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void getIsBaseVfModuleNullTest() throws ApiException {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId(MODEL_VERSION_ID);
+ modelInfo.setModelName(MODEL_NAME);
+ String errorMessage =
+ "VnfType vnfType and VF Module Model Name modelName with version 7 not found in MSO Catalog DB";
+
+ doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage);
+ doReturn(null).when(catDbClient).getVfModuleByModelUUID(MODEL_VERSION_ID);
+
+ thrown.expect(VfModuleNotFoundException.class);
+ thrown.expectMessage(errorMessage);
+ requestHandler.getIsBaseVfModule(modelInfo, action, vnfType, sdcServiceModelVersion, currentActiveRequest);
+ }
+
+ @Test
+ public void getIsBaseVfModuleModelVersionIdNullTest() throws ApiException {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantId(MODEL_INVARIANT_ID);
+ modelInfo.setModelVersion(MODEL_VERSION);
+ modelInfo.setModelName(MODEL_NAME);
+ Boolean expected = false;
+
+ doReturn(null).when(catDbClient).getVfModuleByModelInvariantUUIDAndModelVersion(MODEL_INVARIANT_ID,
+ MODEL_VERSION);
+
+ Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType,
+ sdcServiceModelVersion, currentActiveRequest);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void getIsBaseVfModuleModelInfoNotSetTest() throws ApiException {
+ ModelInfo modelInfo = new ModelInfo();
+ Boolean expected = false;
+
+ Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType,
+ sdcServiceModelVersion, currentActiveRequest);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void getIsBaseVfModuleModelVersionNullTest() throws ApiException {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantId(MODEL_INVARIANT_ID);
+ modelInfo.setModelName(MODEL_NAME);
+ Boolean expected = false;
+
+ Boolean result = requestHandler.getIsBaseVfModule(modelInfo, Action.deleteInstance, vnfType,
+ sdcServiceModelVersion, currentActiveRequest);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void getIsBaseVfModuleModelVersionNullUpdateTest() throws ApiException {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantId(MODEL_INVARIANT_ID);
+ modelInfo.setModelName(MODEL_NAME);
+ String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB";
+
+ doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage);
+
+ thrown.expect(VfModuleNotFoundException.class);
+ thrown.expectMessage(errorMessage);
+ requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, null, currentActiveRequest);
+ }
+
+ @Test
+ public void getIsBaseVfModulesdcModelVersionEmptyTest() throws ApiException {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelInvariantId(MODEL_INVARIANT_ID);
+ modelInfo.setModelName(MODEL_NAME);
+ String errorMessage = "VnfType vnfType and VF Module Model Name modelName not found in MSO Catalog DB";
+
+ doNothing().when(requestHandler).updateStatus(currentActiveRequest, Status.FAILED, errorMessage);
+
+ thrown.expect(VfModuleNotFoundException.class);
+ thrown.expectMessage(errorMessage);
+ requestHandler.getIsBaseVfModule(modelInfo, Action.updateInstance, vnfType, "", currentActiveRequest);
+ }
+
+ @Test
+ public void getModelTypeApplyUpdatedConfigTest() throws ApiException {
+ ModelType modelTypeExpected = ModelType.vnf;
+
+ ModelType modelTypeResult = requestHandler.getModelType(Action.applyUpdatedConfig, null);
+ assertEquals(modelTypeResult, modelTypeExpected);
+ }
+
+ @Test
+ public void getModelTypeInPlaceSoftwareUpdateTest() throws ApiException {
+ ModelType modelTypeExpected = ModelType.vnf;
+
+ ModelType modelTypeResult = requestHandler.getModelType(Action.inPlaceSoftwareUpdate, null);
+ assertEquals(modelTypeResult, modelTypeExpected);
+ }
+
+ @Test
+ public void getModelTypeAddMembersTest() throws ApiException {
+ ModelType modelTypeExpected = ModelType.instanceGroup;
+
+ ModelType modelTypeResult = requestHandler.getModelType(Action.addMembers, null);
+ assertEquals(modelTypeResult, modelTypeExpected);
+ }
+
+ @Test
+ public void getModelTypeRemoveMembersTest() throws ApiException {
+ ModelType modelTypeExpected = ModelType.instanceGroup;
+
+ ModelType modelTypeResult = requestHandler.getModelType(Action.removeMembers, null);
+ assertEquals(modelTypeResult, modelTypeExpected);
+ }
+
+ @Test
+ public void getModelTypeTest() throws ApiException {
+ ModelType modelTypeExpected = ModelType.service;
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(ModelType.service);
+
+ ModelType modelTypeResult = requestHandler.getModelType(Action.createInstance, modelInfo);
+ assertEquals(modelTypeResult, modelTypeExpected);
+ }
+
+ @Test
+ public void updateRequestorIdInRequestBodyTest() throws IOException {
+ String newRequestorId = "yyyyyy";
+ String expected = getRequestBody("/RequestBodyNewRequestorId.json");
+ String result = requestHandler.updateRequestorIdInRequestBody(infraActiveRequest, newRequestorId);
+ assertEquals(expected, result);
+ }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java
new file mode 100644
index 0000000000..1e755419be
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java
@@ -0,0 +1,483 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.apihandlerinfra;
+
+import static com.shazam.shazamcrest.MatcherAssert.assertThat;
+import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.junit.Assert.assertEquals;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.sql.Timestamp;
+import java.util.HashMap;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.core.Response;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.so.apihandler.common.RequestClientParameter;
+import org.onap.so.apihandlerinfra.exceptions.ApiException;
+import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
+import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
+import org.onap.so.apihandlerinfra.exceptions.ValidateException;
+import org.onap.so.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.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 {
+ @Mock
+ private RequestHandlerUtils requestHandler;
+
+ @Mock
+ private MsoRequest msoRequest;
+
+ @Mock
+ private ServiceInstances serviceInstances;
+
+ @Mock
+ private RequestsDbClient requestDbClient;
+
+ @InjectMocks
+ @Spy
+ private ResumeOrchestrationRequest resumeReq;
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4";
+ private static final String REQUEST_ID = "00032ab7-na18-42e5-965d-8ea592502019";
+ private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018";
+ private static final String VNF_ID = "00032ab7-na18-42e5-965d-8ea592502017";
+ private static final String VFMODULE_ID = "00032ab7-na18-42e5-965d-8ea592502016";
+ private static final String NETWORK_ID = "00032ab7-na18-42e5-965d-8ea592502015";
+ private static final String VOLUME_GROUP_ID = "00032ab7-na18-42e5-965d-8ea592502014";
+ private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName";
+ private static final String VNF_NAME = "vnfName";
+ private static final String VFMODULE_NAME = "vfModuleName";
+ private static final String NETWORK_NAME = "networkName";
+ private static final String VOLUME_GROUP_NAME = "volumeGroupName";
+ private static final String SERVICE = "service";
+ private static final String VNF = "vnf";
+ private static final String VFMODULE = "vfModule";
+ private static final String NETWORK = "network";
+ private static final String VOLUME_GROUP = "volumeGroup";
+ private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
+ private final Action action = Action.createInstance;
+ private final Boolean aLaCarte = false;
+ private final String version = "7";
+ private final String requestUri =
+ "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume";
+ private final RecipeLookupResult lookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 80);
+ private RequestClientParameter requestClientParameter = null;
+ private RequestClientParameter requestClientParameterVfModule = null;
+ private ObjectMapper mapper = new ObjectMapper();
+ private InfraActiveRequests infraActiveRequest = new InfraActiveRequests();
+ private InfraActiveRequests currentActiveRequest = new InfraActiveRequests();
+ private InfraActiveRequests infraActiveRequestVfModule = new InfraActiveRequests();
+ private ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ private ServiceInstancesRequest sirNullALaCarte = new ServiceInstancesRequest();
+ private String requestBody = null;
+ private String requestBodyNullALaCarte = null;
+ private ContainerRequestContext requestContext = null;
+ private HashMap<String, String> instanceIdMap = new HashMap<>();
+ ModelInfo modelInfo;
+
+
+ @Before
+ public void setup() throws ValidateException, IOException {
+ // Setup general requestHandler mocks
+ when(requestHandler.getRequestUri(any(), anyString())).thenReturn(requestUri);
+
+ // Setup InfraActiveRequests
+ setInfraActiveRequest();
+ setCurrentActiveRequest();
+ setInfraActiveRequestVfModule();
+
+ requestBody = infraActiveRequest.getRequestBody();
+ sir = mapper.readValue(requestBody, ServiceInstancesRequest.class);
+ requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json");
+ sirNullALaCarte = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class);
+ setRequestClientParameter();
+ setRequestClientParameterVfModule();
+ instanceIdMap.put("serviceInstanceId", SERVICE_INSTANCE_ID);
+ modelInfo = sir.getRequestDetails().getModelInfo();
+ }
+
+ public String getRequestBody(String request) throws IOException {
+ request = "src/test/resources/ResumeOrchestrationRequest" + request;
+ return new String(Files.readAllBytes(Paths.get(request)));
+ }
+
+ private void setInfraActiveRequest() throws IOException {
+ infraActiveRequest.setTenantId("tenant-id");
+ infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json"));
+ infraActiveRequest.setAicCloudRegion("cloudRegion");
+ infraActiveRequest.setRequestScope(SERVICE);
+ infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME);
+ infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ infraActiveRequest.setRequestAction(Action.createInstance.toString());
+ infraActiveRequest.setServiceType("serviceType");
+ infraActiveRequest.setVnfId(VNF_ID);
+ infraActiveRequest.setVfModuleId(VFMODULE_ID);
+ infraActiveRequest.setNetworkId(NETWORK_ID);
+ infraActiveRequest.setVolumeGroupId(VOLUME_GROUP_ID);
+ infraActiveRequest.setVnfName(VNF_NAME);
+ infraActiveRequest.setVfModuleName(VFMODULE_NAME);
+ infraActiveRequest.setNetworkName(NETWORK_NAME);
+ infraActiveRequest.setVolumeGroupName(VOLUME_GROUP_NAME);
+ infraActiveRequest.setRequestId(REQUEST_ID);
+ }
+
+ private void setCurrentActiveRequest() throws IOException {
+ currentActiveRequest.setRequestId(CURRENT_REQUEST_ID);
+ currentActiveRequest.setSource("VID");
+ currentActiveRequest.setStartTime(startTimeStamp);
+ currentActiveRequest.setTenantId("tenant-id");
+ currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json"));
+ currentActiveRequest.setAicCloudRegion("cloudRegion");
+ currentActiveRequest.setRequestScope(SERVICE);
+ currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID);
+ currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME);
+ currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString());
+ currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ currentActiveRequest.setRequestAction(Action.createInstance.toString());
+ currentActiveRequest.setRequestUrl(requestUri);
+ currentActiveRequest.setRequestorId("xxxxxx");
+ currentActiveRequest.setProgress(new Long(5));
+ }
+
+ private void setInfraActiveRequestVfModule() throws IOException {
+ infraActiveRequestVfModule.setRequestBody(getRequestBody("/RequestBody.json"));
+ infraActiveRequestVfModule.setRequestScope(VFMODULE);
+ infraActiveRequestVfModule.setRequestStatus(Status.IN_PROGRESS.toString());
+ infraActiveRequestVfModule.setRequestAction(Action.createInstance.toString());
+ infraActiveRequestVfModule.setVnfId(VNF_ID);
+ infraActiveRequestVfModule.setVfModuleId(VFMODULE_ID);
+ infraActiveRequestVfModule.setVnfName(VNF_NAME);
+ infraActiveRequestVfModule.setVfModuleName(VFMODULE_NAME);
+ }
+
+ private void setRequestClientParameter() {
+ requestClientParameter =
+ new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80)
+ .setRequestAction(Action.createInstance.toString()).setServiceInstanceId(SERVICE_INSTANCE_ID)
+ .setPnfCorrelationId("pnfCorrelationId").setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID)
+ .setVolumeGroupId(VOLUME_GROUP_ID).setNetworkId(NETWORK_ID).setServiceType("serviceType")
+ .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version)
+ .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build();
+ }
+
+ private void setRequestClientParameterVfModule() {
+ requestClientParameterVfModule =
+ new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID).setRecipeTimeout(80)
+ .setRequestAction(Action.createInstance.toString()).setPnfCorrelationId("pnfCorrelationId")
+ .setVnfId(VNF_ID).setVfModuleId(VFMODULE_ID).setRequestDetails(requestBody)
+ .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
+ }
+
+ @Test
+ public void resumeOrchestationRequestTest() throws Exception {
+ Response response = null;
+ when(requestDbClient.getInfraActiveRequestbyRequestId(REQUEST_ID)).thenReturn(infraActiveRequest);
+ doReturn(currentActiveRequest).when(requestHandler).createNewRecordCopyFromInfraActiveRequest(
+ any(InfraActiveRequests.class), nullable(String.class), any(Timestamp.class), nullable(String.class),
+ nullable(String.class), nullable(String.class), anyString());
+ doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class),
+ anyString(), nullable(String.class));
+
+ resumeReq.resumeOrchestrationRequest(REQUEST_ID, "v7", requestContext);
+
+ verify(resumeReq).resumeRequest(infraActiveRequest, currentActiveRequest, version, null);
+ }
+
+ @Test
+ public void resumeOrchestationRequestDbNullResultTest() throws Exception {
+ when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")).thenReturn(null);
+
+ thrown.expect(ValidateException.class);
+ thrown.expectMessage(
+ "Null response from requestDB when searching by requestId: 00032ab7-na18-42e5-965d-8ea592502018");
+ resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext);
+ }
+
+ @Test
+ public void resumeOrchestationRequestDbErrorTest() throws Exception {
+ when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018"))
+ .thenThrow(HttpClientErrorException.class);
+
+ thrown.expect(ValidateException.class);
+ thrown.expectMessage("Exception while performing requestDb lookup by requestId");
+ resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext);
+ }
+
+ @Test
+ public void resumeRequestTest() throws ApiException, IOException {
+ Response response = null;
+ doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString());
+ doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest,
+ ModelType.service.toString(), currentActiveRequest);
+ 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,
+ currentActiveRequest);
+ doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version,
+ infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir);
+ doNothing().when(resumeReq).requestDbSave(currentActiveRequest);
+ when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class),
+ anyString(), anyString())).thenReturn(response);
+ doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE,
+ SERVICE_INSTANCE_NAME, action);
+
+ resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version,
+ "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume");
+ verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter,
+ lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope());
+ }
+
+ @Test
+ public void setRequestClientParameterTest() throws ApiException, IOException {
+ doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo);
+ when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(),
+ any(Action.class))).thenReturn(requestBody);
+ RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest,
+ currentActiveRequest, "pnfCorrelationId", aLaCarte, sir);
+ assertThat(requestClientParameter, sameBeanAs(result));
+ }
+
+ @Test
+ public void setRequestClientParameterVfModuleTest() throws ApiException, IOException {
+ when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(),
+ any(Action.class))).thenReturn(requestBody);
+ doReturn(ModelType.vfModule).when(requestHandler).getModelType(action, modelInfo);
+ RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version,
+ infraActiveRequestVfModule, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir);
+ assertThat(requestClientParameterVfModule, sameBeanAs(result));
+ }
+
+ @Test
+ public void requestDbSaveTest() throws RequestDbFailureException {
+ doNothing().when(requestDbClient).save(currentActiveRequest);
+ resumeReq.requestDbSave(currentActiveRequest);
+ verify(requestDbClient).save(currentActiveRequest);
+ }
+
+ @Test
+ public void resumeRequestTestALaCarteNull() throws ApiException, IOException {
+ Response response = null;
+ doReturn(instanceIdMap).when(resumeReq).setInstanceIdMap(infraActiveRequest, ModelType.service.toString());
+ doReturn(SERVICE_INSTANCE_NAME).when(resumeReq).getInstanceName(infraActiveRequest,
+ ModelType.service.toString(), currentActiveRequest);
+ when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(),
+ 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,
+ currentActiveRequest);
+ doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version,
+ infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sirNullALaCarte);
+ doReturn(false).when(resumeReq).setALaCarteFlagIfNull(SERVICE, action);
+ doNothing().when(resumeReq).requestDbSave(currentActiveRequest);
+ when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class),
+ anyString(), anyString())).thenReturn(response);
+ doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE,
+ SERVICE_INSTANCE_NAME, action);
+
+ resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version,
+ "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume");
+ verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter,
+ lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope());
+ }
+
+ @Test
+ public void setRequestClientParameterErrorTest() throws ApiException, IOException {
+ doReturn(ModelType.service).when(requestHandler).getModelType(action, modelInfo);
+ when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(),
+ any(Action.class))).thenThrow(new IOException("IOException"));
+
+ thrown.expect(ValidateException.class);
+ thrown.expectMessage("IOException while generating requestClientParameter to send to BPMN: IOException");
+ resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest,
+ "pnfCorrelationId", aLaCarte, sir);
+ }
+
+ @Test
+ public void checkForInProgressRequest() throws ApiException {
+ doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME,
+ SERVICE, currentActiveRequest);
+ doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest);
+ doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest,
+ action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE, infraActiveRequest);
+
+ thrown.expect(DuplicateRequestException.class);
+ resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME,
+ action);
+ }
+
+ @Test
+ public void checkForInProgressRequestNoInProgressRequests() throws ApiException {
+ doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE,
+ currentActiveRequest);
+
+ resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME,
+ action);
+ verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE,
+ currentActiveRequest);
+ }
+
+ @Test
+ public void checkForInProgressRequestCamundaHistoryCheckReturnsNoInProgress() throws ApiException {
+ doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME,
+ SERVICE, currentActiveRequest);
+ doReturn(false).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest);
+
+ resumeReq.checkForInProgressRequest(currentActiveRequest, instanceIdMap, SERVICE, SERVICE_INSTANCE_NAME,
+ action);
+ verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, SERVICE,
+ currentActiveRequest);
+ verify(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest);
+ }
+
+ @Test
+ public void setInstanceIdMapServiceTest() {
+ HashMap<String, String> expected = new HashMap<>();
+ expected.put("serviceInstanceId", SERVICE_INSTANCE_ID);
+ HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, SERVICE);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void setInstanceIdMapRequestScopeNotValidTest() {
+ HashMap<String, String> expected = new HashMap<>();
+ HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, "test");
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void setInstanceIdMapVnfTest() {
+ HashMap<String, String> expected = new HashMap<>();
+ expected.put("vnfInstanceId", VNF_ID);
+ HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VNF);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void setInstanceIdMapVfModuleTest() {
+ HashMap<String, String> expected = new HashMap<>();
+ expected.put("vfModuleInstanceId", VFMODULE_ID);
+ HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VFMODULE);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void setInstanceIdMapNetworkTest() {
+ HashMap<String, String> expected = new HashMap<>();
+ expected.put("networkInstanceId", NETWORK_ID);
+ HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, NETWORK);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void setInstanceIdMapVolumeGroupTest() {
+ HashMap<String, String> expected = new HashMap<>();
+ expected.put("volumeGroupInstanceId", VOLUME_GROUP_ID);
+ HashMap<String, String> result = resumeReq.setInstanceIdMap(infraActiveRequest, VOLUME_GROUP);
+ assertEquals(result, expected);
+ }
+
+ @Test
+ public void setInstanceNameServiceTest() throws ValidateException, RequestDbFailureException {
+ String result = resumeReq.getInstanceName(infraActiveRequest, SERVICE, currentActiveRequest);
+ assertEquals(result, SERVICE_INSTANCE_NAME);
+ }
+
+ @Test
+ public void setInstanceNameRequestScopeNotValidTest() throws ValidateException, RequestDbFailureException {
+ thrown.expect(ValidateException.class);
+ thrown.expectMessage(
+ "requestScope: \"test\" from request: 00032ab7-na18-42e5-965d-8ea592502019 does not match a ModelType enum.");
+
+ resumeReq.getInstanceName(infraActiveRequest, "test", currentActiveRequest);
+ }
+
+ @Test
+ public void setInstanceNameVnfTest() throws ValidateException, RequestDbFailureException {
+ String result = resumeReq.getInstanceName(infraActiveRequest, VNF, currentActiveRequest);
+ assertEquals(result, VNF_NAME);
+ }
+
+ @Test
+ public void setInstanceNameVfModuleTest() throws ValidateException, RequestDbFailureException {
+ String result = resumeReq.getInstanceName(infraActiveRequest, VFMODULE, currentActiveRequest);
+ assertEquals(result, VFMODULE_NAME);
+ }
+
+ @Test
+ public void setInstanceNameNetworkTest() throws ValidateException, RequestDbFailureException {
+ String result = resumeReq.getInstanceName(infraActiveRequest, NETWORK, currentActiveRequest);
+ assertEquals(result, NETWORK_NAME);
+ }
+
+ @Test
+ public void setInstanceNameVolumeGroupTest() throws ValidateException, RequestDbFailureException {
+ String result = resumeReq.getInstanceName(infraActiveRequest, VOLUME_GROUP, currentActiveRequest);
+ assertEquals(result, VOLUME_GROUP_NAME);
+ }
+
+ @Test
+ public void setALaCarteFlagIfNullTest() {
+ Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(SERVICE, action);
+ assertEquals(aLaCarteFlag, false);
+ }
+
+ @Test
+ public void setALaCarteFlagIfNullVnfTest() {
+ Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, action);
+ assertEquals(aLaCarteFlag, true);
+ }
+
+ @Test
+ public void setALaCarteFlagIfNullRecreateTest() {
+ Boolean aLaCarteFlag = resumeReq.setALaCarteFlagIfNull(VNF, Action.recreateInstance);
+ assertEquals(aLaCarteFlag, false);
+ }
+}
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 db6273dc4a..48a5343104 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.
@@ -28,11 +28,14 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID;
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;
@@ -41,7 +44,6 @@ 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.HttpHeadersConstants.TRANSACTION_ID;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -57,12 +59,18 @@ import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
+import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
import org.onap.so.db.catalog.beans.Service;
import org.onap.so.db.catalog.beans.ServiceRecipe;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.onap.so.logger.HttpHeadersConstants;
import org.onap.so.serviceinstancebeans.CloudConfiguration;
+import org.onap.so.serviceinstancebeans.ModelInfo;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
import org.onap.so.serviceinstancebeans.RequestError;
+import org.onap.so.serviceinstancebeans.RequestInfo;
import org.onap.so.serviceinstancebeans.RequestParameters;
import org.onap.so.serviceinstancebeans.RequestReferences;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
@@ -75,7 +83,6 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.util.UriComponentsBuilder;
-import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -84,7 +91,6 @@ 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();
@@ -93,6 +99,9 @@ public class ServiceInstancesTest extends BaseTest {
@Autowired
private ServiceInstances servInstances;
+ @Autowired
+ private RequestHandlerUtils requestHandlerUtils;
+
@Value("${wiremock.server.port}")
private String wiremockPort;
@@ -276,14 +285,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
@@ -887,7 +895,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
@@ -2239,14 +2247,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
@@ -2389,7 +2395,7 @@ public class ServiceInstancesTest extends BaseTest {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals(
- "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error",
realResponse.getServiceException().getText());
}
@@ -2434,7 +2440,7 @@ public class ServiceInstancesTest extends BaseTest {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals(
- "Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ "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());
}
@@ -2451,7 +2457,7 @@ public class ServiceInstancesTest extends BaseTest {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals(
- "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error",
realResponse.getServiceException().getText());
}
@@ -2483,7 +2489,7 @@ public class ServiceInstancesTest extends BaseTest {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals(
- "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error",
realResponse.getServiceException().getText());
}
@@ -2503,7 +2509,7 @@ public class ServiceInstancesTest extends BaseTest {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals(
- "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error",
realResponse.getServiceException().getText());
}
@@ -2520,7 +2526,7 @@ public class ServiceInstancesTest extends BaseTest {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value());
RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class);
assertEquals(
- "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error",
+ "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Server Error",
realResponse.getServiceException().getText());
}
@@ -2748,5 +2754,182 @@ public class ServiceInstancesTest extends BaseTest {
"No valid modelCustomizationId for networkResourceCustomization lookup is specified");
}
+ @Test
+ public void setServiceTypeTestALaCarte() throws JsonProcessingException {
+ String requestScope = ModelType.service.toString();
+ Boolean aLaCarteFlag = true;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setSource("VID");
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+ Service defaultService = new Service();
+ defaultService.setServiceType("testServiceTypeALaCarte");
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "testServiceTypeALaCarte");
+ }
+
+ @Test
+ public void setServiceTypeTest() throws JsonProcessingException {
+ String requestScope = ModelType.service.toString();
+ Boolean aLaCarteFlag = false;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a");
+ requestInfo.setSource("VID");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+ Service defaultService = new Service();
+ defaultService.setServiceType("testServiceType");
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "testServiceType");
+ }
+
+ @Test
+ public void setServiceTypeTestDefault() throws JsonProcessingException {
+ String requestScope = ModelType.service.toString();
+ Boolean aLaCarteFlag = false;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a");
+ requestInfo.setSource("VID");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+ Service defaultService = new Service();
+ defaultService.setServiceType("testServiceType");
+
+ wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withStatus(HttpStatus.SC_NOT_FOUND)));
+ wireMockServer.stubFor(get(urlMatching(".*/service/search/.*"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK)));
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "testServiceType");
+ }
+
+ @Test
+ public void setServiceTypeTestNetwork() throws JsonProcessingException {
+ String requestScope = ModelType.network.toString();
+ Boolean aLaCarteFlag = null;
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelName("networkModelName");
+ requestInfo.setSource("VID");
+ requestDetails.setModelInfo(modelInfo);
+ requestDetails.setRequestInfo(requestInfo);
+ sir.setRequestDetails(requestDetails);
+
+ String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag);
+ assertEquals(serviceType, "networkModelName");
+ }
+ @Test
+ public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException {
+ String requestScope = "instanceGroup";
+ ServiceInstancesRequest sir =
+ mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class);
+ assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc",
+ requestHandlerUtils.setServiceInstanceId(requestScope, sir));
+ }
+
+ @Test
+ public void setServiceInstanceIdTest() {
+ String requestScope = "vnf";
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f",
+ requestHandlerUtils.setServiceInstanceId(requestScope, sir));
+ }
+
+ @Test
+ public void setServiceInstanceIdReturnNullTest() {
+ String requestScope = "vnf";
+ ServiceInstancesRequest sir = new ServiceInstancesRequest();
+ assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir));
+ }
+
+ @Test
+ public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException {
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/HistoryCheckResponse.json")
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ InfraActiveRequests duplicateRecord = new InfraActiveRequests();
+ duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ boolean inProgress = false;
+ inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
+ assertTrue(inProgress);
+ }
+
+ @Test
+ public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException {
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ InfraActiveRequests duplicateRecord = new InfraActiveRequests();
+ duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ boolean inProgress = false;
+ inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
+ assertFalse(inProgress);
+ }
+
+ @Test
+ public void camundaHistoryCheckNotInProgressTest() throws ContactCamundaException, RequestDbFailureException {
+ wireMockServer.stubFor(get(
+ ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f"))
+ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
+ .withBodyFile("Camunda/HistoryCheckResponseCompleted.json")
+ .withStatus(org.apache.http.HttpStatus.SC_OK)));
+
+ InfraActiveRequests duplicateRecord = new InfraActiveRequests();
+ duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f");
+ boolean inProgress = false;
+ inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null);
+ assertFalse(inProgress);
+ }
+
+ @Test
+ public void handleReplaceInstance_Test() throws JsonParseException, JsonMappingException, IOException {
+ String replaceVfModule = inputStream("/ReplaceVfModule.json");
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(replaceVfModule, ServiceInstancesRequest.class);
+ Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir);
+ assertEquals(Action.replaceInstance, action);
+ }
+
+ @Test
+ public void handleReplaceInstance_retainAssignments_Test()
+ throws JsonParseException, JsonMappingException, IOException {
+ String replaceVfModule = inputStream("/ReplaceVfModuleRetainAssignments.json");
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(replaceVfModule, ServiceInstancesRequest.class);
+ Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir);
+ assertEquals(Action.replaceInstanceRetainAssignments, action);
+ }
}
+
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
new file mode 100644
index 0000000000..f73da49e0d
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java
@@ -0,0 +1,147 @@
+/*-
+ * ============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;
+
+import static com.shazam.shazamcrest.MatcherAssert.assertThat;
+import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import java.io.File;
+import java.util.Optional;
+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.junit.MockitoJUnitRunner;
+import org.onap.aai.domain.yang.GenericVnf;
+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.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.db.request.client.RequestsDbClient;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class BpmnRequestBuilderTest {
+
+ private static final String RESOURCE_PATH = "src/test/resources/__files/infra/";
+
+ @Rule
+ public ExpectedException exceptionRule = ExpectedException.none();
+
+
+ @Mock
+ private AAIResourcesClient aaiResourcesClient;
+
+ @InjectMocks
+ private AAIDataRetrieval aaiData = spy(AAIDataRetrieval.class);
+
+ @Mock
+ private RequestsDbClient requestDBClient;
+
+ @InjectMocks
+ private BpmnRequestBuilder reqBuilder = spy(BpmnRequestBuilder.class);
+
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ private GraphInventoryCommonObjectMapperProvider provider = new GraphInventoryCommonObjectMapperProvider();
+
+ @Before
+ public void setup() {
+ // aaiData.setAaiResourcesClient(aaiResourcesClient);
+ }
+
+ @Test
+ public void test_buildServiceInstanceDeleteRequest() throws Exception {
+ ServiceInstance service =
+ provider.getMapper().readValue(new File(RESOURCE_PATH + "ServiceInstance.json"), ServiceInstance.class);
+
+ 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
+ ServiceInstancesRequest actualRequest = reqBuilder.buildServiceDeleteRequest("serviceId");
+ assertThat(actualRequest, sameBeanAs(expectedRequest));
+ }
+
+ @Test
+ public void test_buildVnfDeleteRequest() throws Exception {
+ 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"));
+
+ ServiceInstancesRequest expectedRequest =
+ mapper.readValue(new File(RESOURCE_PATH + "ExpectedVnfRequest.json"), ServiceInstancesRequest.class);
+ ServiceInstancesRequest actualRequest = reqBuilder.buildVnfDeleteRequest("vnfId");
+ assertThat(actualRequest, sameBeanAs(expectedRequest));
+ }
+
+ @Test
+ public void test_buildVFModuleDeleteRequest() throws Exception {
+ 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"));
+ VfModule vfModule = provider.getMapper().readValue(new File(RESOURCE_PATH + "VfModule.json"), VfModule.class);
+
+ doReturn(Optional.of(vfModule)).when(aaiResourcesClient).get(VfModule.class,
+ AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, "vnfId", "vfModuleId"));
+
+ ServiceInstancesRequest expectedRequest = mapper
+ .readValue(new File(RESOURCE_PATH + "ExpectedVfModuleRequest.json"), ServiceInstancesRequest.class);
+ ServiceInstancesRequest actualRequest =
+ reqBuilder.buildVFModuleDeleteRequest("vnfId", "vfModuleId", ModelType.vfModule);
+ assertThat(actualRequest, sameBeanAs(expectedRequest));
+ }
+
+ @Test
+ public void test_buildVolumeGroupDeleteRequest() throws Exception {
+ 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"));
+ VolumeGroup volumeGroup =
+ provider.getMapper().readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class);
+ 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));
+ }
+
+}
+
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java
new file mode 100644
index 0000000000..d39192cdf0
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandlerTest.java
@@ -0,0 +1,64 @@
+/*-
+ * ============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.handler;
+
+import static com.shazam.shazamcrest.MatcherAssert.assertThat;
+import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
+import static org.mockito.Mockito.doReturn;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Optional;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler;
+import org.onap.so.serviceinstancebeans.RequestReferences;
+import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AbstractRestHandlerTest {
+
+ @Spy
+ AbstractRestHandler restHandler;
+
+ @Mock
+ ContainerRequestContext mockRequestContext;
+
+ @Test
+ public void test_createResponse() throws MalformedURLException {
+ ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse();
+ RequestReferences requestReferences = new RequestReferences();
+ URL selfLinkURL = new URL("http://localhost:8080/v1");
+ requestReferences.setInstanceId("instanceId");
+ requestReferences.setRequestId("requestId");
+ requestReferences.setRequestSelfLink(selfLinkURL);
+ expectedResponse.setRequestReferences(requestReferences);
+
+ doReturn("http://localhost:8080/v1").when(restHandler).getRequestUri(mockRequestContext);
+ doReturn(Optional.of(selfLinkURL)).when(restHandler).buildSelfLinkUrl("http://localhost:8080/v1", "requestId");
+ ServiceInstancesResponse actualResponse =
+ restHandler.createResponse("instanceId", "requestId", mockRequestContext);
+ assertThat(actualResponse, sameBeanAs(expectedResponse));
+ }
+}
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
new file mode 100644
index 0000000000..59308215ac
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/NetworkRestHandlerTest.java
@@ -0,0 +1,143 @@
+/*-
+ * ============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.handler;
+
+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.eq;
+import java.net.MalformedURLException;
+import java.util.HashMap;
+import java.util.Map;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+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.apihandlerinfra.infra.rest.handler.NetworkRestHandler;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class NetworkRestHandlerTest {
+
+ @Rule
+ public ExpectedException exceptionRule = ExpectedException.none();
+
+ @InjectMocks
+ NetworkRestHandler restHandler;
+
+ @Mock
+ ContainerRequestContext mockRequestContext;
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @Mock
+ private RequestsDbClient infraActiveRequestsClient;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException {
+ ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class);
+ restHandler.checkDuplicateRequest("serviceInstanceId", "networkId", "instanceName", "requestId");
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate(
+ instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.network.toString()));
+ Map actualMap = instanceIdCaptor.getValue();
+ assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId"));
+ assertEquals("NetworkId should exit in map", "networkId", actualMap.get("networkInstanceId"));
+ }
+
+ @Test
+ public void test_saveInstanceName() throws MalformedURLException, NoRecipeException {
+ ServiceInstancesRequest request = createTestRequest();
+ InfraActiveRequests dbRequest = createDatabaseRecord();
+ restHandler.saveInstanceName(request, dbRequest);
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest);
+ assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getNetworkName());
+ }
+
+ @Test
+ public void test_buildRequestParams() throws Exception {
+ RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId")
+ .setServiceInstanceId("serviceInstanceId").setNetworkId("networkId").setALaCarte(true)
+ .setRequestDetails(mapper.writeValueAsString(createTestRequest()))
+ .setRequestAction(Action.deleteInstance.toString())
+ .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build();
+ RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(),
+ "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "networkId");
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ 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");
+ expected.setRequestorId("userId");
+ expected.setSource("VID");
+ expected.setRequestStatus(Status.IN_PROGRESS.toString());
+ expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ expected.setRequestScope(ModelType.network.toString());
+ expected.setRequestUrl("http://localhost:9090");
+ InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "serviceInstanceId",
+ "networkId", "userId", "VID", "http://localhost:9090");
+ assertThat(actual, sameBeanAs(expected).ignoring("startTime"));
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual);
+ }
+
+ private ServiceInstancesRequest createTestRequest() {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("instanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ private InfraActiveRequests createDatabaseRecord() {
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setRequestId("requestId");
+ return request;
+ }
+
+}
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
new file mode 100644
index 0000000000..c1e6347943
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/ServiceInstanceRestHandlerTest.java
@@ -0,0 +1,189 @@
+/*-
+ * ============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.handler;
+
+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.eq;
+import static org.mockito.Mockito.doReturn;
+import java.net.MalformedURLException;
+import java.util.HashMap;
+import java.util.Map;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+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.apihandlerinfra.infra.rest.exception.RequestConflictedException;
+import org.onap.so.apihandlerinfra.infra.rest.handler.ServiceInstanceRestHandler;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.catalog.beans.ServiceRecipe;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ServiceInstanceRestHandlerTest {
+
+ @Rule
+ public ExpectedException exceptionRule = ExpectedException.none();
+
+ @InjectMocks
+ ServiceInstanceRestHandler restHandler;
+
+ @Mock
+ ContainerRequestContext mockRequestContext;
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @Mock
+ private RequestsDbClient infraActiveRequestsClient;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void test_find_service_recipe() throws MalformedURLException, NoRecipeException {
+ ServiceRecipe expected = new ServiceRecipe();
+ expected.setAction("createInstance");
+ doReturn(expected).when(catalogDbClient)
+ .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId");
+ Recipe actual = restHandler.findServiceRecipe("testModelId", Action.createInstance.toString());
+ assertThat(actual, sameBeanAs(expected));
+ Mockito.verify(catalogDbClient, Mockito.times(1))
+ .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId");
+ }
+
+ @Test
+ public void test_find_service_recipe_default_recipe() throws MalformedURLException, NoRecipeException {
+ ServiceRecipe expected = new ServiceRecipe();
+ expected.setAction("createInstance");
+ doReturn(null).when(catalogDbClient)
+ .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId");
+ doReturn(expected).when(catalogDbClient).findServiceRecipeByActionAndServiceModelUUID(
+ Action.createInstance.toString(), "d88da85c-d9e8-4f73-b837-3a72a431622b");
+ Recipe actual = restHandler.findServiceRecipe("testModelId", Action.createInstance.toString());
+ assertThat(actual, sameBeanAs(expected));
+ Mockito.verify(catalogDbClient, Mockito.times(1))
+ .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId");
+ Mockito.verify(catalogDbClient, Mockito.times(1)).findServiceRecipeByActionAndServiceModelUUID(
+ Action.createInstance.toString(), "d88da85c-d9e8-4f73-b837-3a72a431622b");
+ }
+
+ @Test
+ public void test_find_service_recipe_not_found() throws MalformedURLException, NoRecipeException {
+ ServiceRecipe expected = new ServiceRecipe();
+ expected.setAction("createInstance");
+ doReturn(null).when(catalogDbClient)
+ .findServiceRecipeByActionAndServiceModelUUID(Action.createInstance.toString(), "testModelId");
+ doReturn(null).when(catalogDbClient).findServiceRecipeByActionAndServiceModelUUID(
+ Action.createInstance.toString(), "d88da85c-d9e8-4f73-b837-3a72a431622b");
+ exceptionRule.expect(NoRecipeException.class);
+ exceptionRule.expectMessage(
+ "Unable to locate custom or default recipe for, Action: createInstance, Model UUID: testModelId");
+ restHandler.findServiceRecipe("testModelId", Action.createInstance.toString());
+ }
+
+ @Test
+ public void test_checkDuplicateRequest()
+ throws MalformedURLException, NoRecipeException, RequestConflictedException {
+ ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class);
+ restHandler.checkDuplicateRequest("serviceInstanceId", "instanceName", "requestId");
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate(
+ instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.service.toString()));
+ Map actualMap = instanceIdCaptor.getValue();
+ assertEquals("serviceInstanceId", actualMap.get("serviceInstanceId"));
+ }
+
+ @Test
+ public void test_saveInstanceName() throws MalformedURLException, NoRecipeException {
+ ServiceInstancesRequest request = createTestRequest();
+ InfraActiveRequests dbRequest = createDatabaseRecord();
+ restHandler.saveInstanceName(request, dbRequest);
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest);
+ assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getServiceInstanceName());
+ }
+
+ @Test
+ public void test_buildRequestParams() throws Exception {
+ RequestClientParameter expected =
+ new RequestClientParameter.Builder().setRequestId("requestId").setServiceInstanceId("serviceInstanceId")
+ .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(createTestRequest()))
+ .setRequestAction(Action.deleteInstance.toString())
+ .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build();
+ RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(),
+ "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId");
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ 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");
+ expected.setSource("VID");
+ expected.setRequestStatus(Status.IN_PROGRESS.toString());
+ expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ expected.setRequestUrl("http://localhost:9090");
+ expected.setRequestScope(ModelType.service.toString());
+ InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "serviceInstanceId",
+ "userId", "VID", "http://localhost:9090");
+ assertThat(actual, sameBeanAs(expected).ignoring("startTime"));
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual);
+ }
+
+ private ServiceInstancesRequest createTestRequest() {
+
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("instanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ private InfraActiveRequests createDatabaseRecord() {
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setRequestId("requestId");
+ return request;
+ }
+
+}
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
new file mode 100644
index 0000000000..7d146791fe
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VfModuleRestHandlerTest.java
@@ -0,0 +1,190 @@
+/*-
+ * ============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.handler;
+
+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.eq;
+import static org.mockito.Mockito.doReturn;
+import java.net.MalformedURLException;
+import java.util.HashMap;
+import java.util.Map;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+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.apihandlerinfra.infra.rest.handler.VFModuleRestHandler;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.catalog.beans.VnfComponentsRecipe;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class VfModuleRestHandlerTest {
+
+ @Rule
+ public ExpectedException exceptionRule = ExpectedException.none();
+
+ @InjectMocks
+ VFModuleRestHandler restHandler;
+
+ @Mock
+ ContainerRequestContext mockRequestContext;
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @Mock
+ private RequestsDbClient infraActiveRequestsClient;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void test_find_vf_module_recipe() throws MalformedURLException, NoRecipeException {
+ VnfComponentsRecipe expected = new VnfComponentsRecipe();
+ expected.setAction("createInstance");
+ doReturn(expected).when(catalogDbClient)
+ .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("testModelId",
+ ModelType.vfModule.toString(), Action.createInstance.toString());
+ Recipe actual = restHandler.findVfModuleRecipe("testModelId", ModelType.vfModule.toString(),
+ Action.createInstance.toString());
+ assertThat(actual, sameBeanAs(expected));
+ Mockito.verify(catalogDbClient, Mockito.times(1))
+ .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("testModelId",
+ ModelType.vfModule.toString(), Action.createInstance.toString());
+ }
+
+ @Test
+ public void test_find_vf_module_recipe_default_recipe() throws MalformedURLException, NoRecipeException {
+ VnfComponentsRecipe expected = new VnfComponentsRecipe();
+ expected.setAction("createInstance");
+ doReturn(null).when(catalogDbClient).getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+ "testModelId", ModelType.vfModule.toString(), Action.createInstance.toString());
+ doReturn(expected).when(catalogDbClient)
+ .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("GR-API-DEFAULT",
+ ModelType.vfModule.toString(), Action.createInstance.toString());
+ Recipe actual = restHandler.findVfModuleRecipe("testModelId", ModelType.vfModule.toString(),
+ Action.createInstance.toString());
+ assertThat(actual, sameBeanAs(expected));
+ Mockito.verify(catalogDbClient, Mockito.times(1))
+ .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction("testModelId",
+ ModelType.vfModule.toString(), Action.createInstance.toString());
+ }
+
+ @Test
+ public void test_find_vf_module_recipe_not_found() throws MalformedURLException, NoRecipeException {
+ VnfComponentsRecipe expected = new VnfComponentsRecipe();
+ expected.setAction("createInstance");
+ exceptionRule.expect(NoRecipeException.class);
+ exceptionRule.expectMessage(
+ "Unable to locate custom or default recipe for ModelType: vfModule , Action: createInstance, CustomizationId: testModelId");
+ restHandler.findVfModuleRecipe("testModelId", ModelType.vfModule.toString(), Action.createInstance.toString());
+ }
+
+ @Test
+ public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException {
+ ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class);
+ restHandler.checkDuplicateRequest("serviceInstanceId", "vnfId", "vfModuleId", "instanceName", "requestId");
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate(
+ instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.vfModule.toString()));
+ Map actualMap = instanceIdCaptor.getValue();
+ assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId"));
+ assertEquals("VnfId should exit in map", "vnfId", actualMap.get("vnfInstanceId"));
+ assertEquals("VFModuleId should exit in map", "vfModuleId", actualMap.get("vfModuleInstanceId"));
+ }
+
+ @Test
+ public void test_saveInstanceName() throws MalformedURLException, NoRecipeException {
+ ServiceInstancesRequest request = createTestRequest();
+ InfraActiveRequests dbRequest = createDatabaseRecord();
+ restHandler.saveInstanceName(request, dbRequest);
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest);
+ assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getVfModuleName());
+ }
+
+ @Test
+ public void test_buildRequestParams() throws Exception {
+ RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId")
+ .setServiceInstanceId("serviceInstanceId").setVnfId("vnfId").setVfModuleId("vfModuleId")
+ .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(createTestRequest()))
+ .setRequestAction(Action.deleteInstance.toString())
+ .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build();
+ RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(),
+ "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "vnfId", "vfModuleId");
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ 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");
+ expected.setRequestId("requestId");
+ expected.setRequestorId("userId");
+ expected.setSource("VID");
+ expected.setRequestStatus(Status.IN_PROGRESS.toString());
+ expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ expected.setRequestUrl("http://localhost:9090");
+ expected.setRequestScope(ModelType.vfModule.toString());
+ InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "vfModuleId",
+ "serviceInstanceId", "vnfId", "userId", "VID", "http://localhost:9090");
+ assertThat(actual, sameBeanAs(expected).ignoring("startTime"));
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual);
+ }
+
+ private ServiceInstancesRequest createTestRequest() {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("instanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ private InfraActiveRequests createDatabaseRecord() {
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setRequestId("requestId");
+ return request;
+ }
+
+}
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
new file mode 100644
index 0000000000..03725ec85b
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VnfRestHandlerTest.java
@@ -0,0 +1,154 @@
+/*-
+ * ============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.handler;
+
+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.eq;
+import java.net.MalformedURLException;
+import java.util.HashMap;
+import java.util.Map;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+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.apihandlerinfra.infra.rest.handler.VnfRestHandler;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.catalog.beans.ServiceRecipe;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class VnfRestHandlerTest {
+
+ @Rule
+ public ExpectedException exceptionRule = ExpectedException.none();
+
+ @InjectMocks
+ VnfRestHandler restHandler;
+
+ @Mock
+ ContainerRequestContext mockRequestContext;
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @Mock
+ private RequestsDbClient infraActiveRequestsClient;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void test_find_vnf_recipe() throws MalformedURLException, NoRecipeException {
+ ServiceRecipe expected = new ServiceRecipe();
+ expected.setOrchestrationUri("/mso/async/services/WorkflowActionBB");
+ Recipe actual = restHandler.findVnfModuleRecipe("testModelId", ModelType.vnf.toString(),
+ Action.createInstance.toString());
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException {
+ ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class);
+ restHandler.checkDuplicateRequest("serviceInstanceId", "vnfId", "instanceName", "requestId");
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate(
+ instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.vnf.toString()));
+ Map actualMap = instanceIdCaptor.getValue();
+ assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId"));
+ assertEquals("VnfId should exit in map", "vnfId", actualMap.get("vnfInstanceId"));
+ }
+
+ @Test
+ public void test_saveInstanceName() throws MalformedURLException, NoRecipeException {
+ ServiceInstancesRequest request = createTestRequest();
+ InfraActiveRequests dbRequest = createDatabaseRecord();
+ restHandler.saveInstanceName(request, dbRequest);
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest);
+ assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getVnfName());
+ }
+
+ @Test
+ public void test_buildRequestParams() throws Exception {
+ RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId")
+ .setServiceInstanceId("serviceInstanceId").setVnfId("vnfId").setALaCarte(true)
+ .setRequestDetails(mapper.writeValueAsString(createTestRequest()))
+ .setRequestAction(Action.deleteInstance.toString())
+ .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build();
+ RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(),
+ "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "vnfId");
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ 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");
+ expected.setRequestorId("userId");
+ expected.setSource("VID");
+ expected.setRequestStatus(Status.IN_PROGRESS.toString());
+ expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ expected.setRequestUrl("http://localhost:9090");
+ expected.setRequestScope(ModelType.vnf.toString());
+ InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "serviceInstanceId",
+ "vnfId", "userId", "VID", "http://localhost:9090");
+ assertThat(actual, sameBeanAs(expected).ignoring("startTime"));
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual);
+ }
+
+ private ServiceInstancesRequest createTestRequest() {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("instanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ private InfraActiveRequests createDatabaseRecord() {
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setRequestId("requestId");
+ return request;
+ }
+
+}
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
new file mode 100644
index 0000000000..efa27743ef
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/handler/VolumeRestHandlerTest.java
@@ -0,0 +1,145 @@
+/*-
+ * ============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.handler;
+
+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.eq;
+import java.net.MalformedURLException;
+import java.util.HashMap;
+import java.util.Map;
+import javax.ws.rs.container.ContainerRequestContext;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+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.apihandlerinfra.infra.rest.handler.VolumeRestHandler;
+import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.client.CatalogDbClient;
+import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.db.request.client.RequestsDbClient;
+import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.RequestDetails;
+import org.onap.so.serviceinstancebeans.RequestInfo;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+@RunWith(MockitoJUnitRunner.class)
+public class VolumeRestHandlerTest {
+
+ @Rule
+ public ExpectedException exceptionRule = ExpectedException.none();
+
+ @InjectMocks
+ VolumeRestHandler restHandler;
+
+ @Mock
+ ContainerRequestContext mockRequestContext;
+
+ @Mock
+ private CatalogDbClient catalogDbClient;
+
+ @Mock
+ private RequestsDbClient infraActiveRequestsClient;
+
+ private ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ public void test_checkDuplicateRequest() throws MalformedURLException, NoRecipeException {
+ ArgumentCaptor<HashMap> instanceIdCaptor = ArgumentCaptor.forClass(HashMap.class);
+ restHandler.checkDuplicateRequest("serviceInstanceId", "vnfId", "volumeGroupId", "instanceName", "requestId");
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).checkInstanceNameDuplicate(
+ instanceIdCaptor.capture(), eq("instanceName"), eq(ModelType.volumeGroup.toString()));
+ Map actualMap = instanceIdCaptor.getValue();
+ assertEquals("ServiceInstanceID should exist in map", "serviceInstanceId", actualMap.get("serviceInstanceId"));
+ assertEquals("VnfId should exit in map", "vnfId", actualMap.get("vnfInstanceId"));
+ assertEquals("VolumeGroupId should exit in map", "volumeGroupId", actualMap.get("volumeGroupInstanceId"));
+ }
+
+ @Test
+ public void test_saveInstanceName() throws MalformedURLException, NoRecipeException {
+ ServiceInstancesRequest request = createTestRequest();
+ InfraActiveRequests dbRequest = createDatabaseRecord();
+ restHandler.saveInstanceName(request, dbRequest);
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).updateInfraActiveRequests(dbRequest);
+ assertEquals("InstanceName Should Be Equal", "instanceName", dbRequest.getVolumeGroupName());
+ }
+
+ @Test
+ public void test_buildRequestParams() throws Exception {
+ RequestClientParameter expected = new RequestClientParameter.Builder().setRequestId("requestId")
+ .setServiceInstanceId("serviceInstanceId").setVnfId("vnfId").setVolumeGroupId("volumeGroupId")
+ .setALaCarte(true).setRequestDetails(mapper.writeValueAsString(createTestRequest()))
+ .setRequestAction(Action.deleteInstance.toString())
+ .setRequestUri("http://localhost:8080/serviceInstances").setApiVersion("v8").build();
+ RequestClientParameter actual = restHandler.buildRequestParams(createTestRequest(),
+ "http://localhost:8080/serviceInstances", "requestId", "serviceInstanceId", "vnfId", "volumeGroupId");
+ assertThat(actual, sameBeanAs(expected));
+ }
+
+ @Test
+ 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");
+ expected.setRequestId("requestId");
+ expected.setRequestorId("userId");
+ expected.setSource("VID");
+ expected.setRequestStatus(Status.IN_PROGRESS.toString());
+ expected.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
+ expected.setRequestScope(ModelType.volumeGroup.toString());
+ expected.setRequestUrl("http://localhost:9090");
+ InfraActiveRequests actual = restHandler.createInfraActiveRequestForDelete("requestId", "volumeGroupId",
+ "serviceInstanceId", "vnfId", "userId", "VID", "http://localhost:9090");
+ assertThat(actual, sameBeanAs(expected).ignoring("startTime"));
+ Mockito.verify(infraActiveRequestsClient, Mockito.times(1)).save(actual);
+ }
+
+ private ServiceInstancesRequest createTestRequest() {
+ ServiceInstancesRequest request = new ServiceInstancesRequest();
+ RequestDetails requestDetails = new RequestDetails();
+ RequestInfo requestInfo = new RequestInfo();
+ requestInfo.setInstanceName("instanceName");
+ requestDetails.setRequestInfo(requestInfo);
+ request.setRequestDetails(requestDetails);
+ return request;
+ }
+
+ private InfraActiveRequests createDatabaseRecord() {
+ InfraActiveRequests request = new InfraActiveRequests();
+ request.setRequestId("requestId");
+ return request;
+ }
+
+}
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 9ae1e5b232..a74c11c08b 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
@@ -35,9 +35,9 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.onap.so.apihandlerinfra.BaseTest;
-import org.onap.so.apihandlerinfra.Status;
import org.onap.so.apihandlerinfra.tenantisolationbeans.Action;
import org.onap.so.apihandlerinfra.tenantisolationbeans.TenantIsolationRequest;
+import org.onap.so.constants.Status;
import org.onap.so.db.request.beans.InfraActiveRequests;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java
index 54da0baa92..93a19a9531 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java
@@ -25,15 +25,38 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
import org.onap.so.apihandlerinfra.Action;
import org.onap.so.apihandlerinfra.BaseTest;
import org.onap.so.exceptions.ValidationException;
+import org.onap.so.serviceinstancebeans.RelatedInstanceList;
import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RelatedInstancesValidationTest extends BaseTest {
+ RelatedInstancesValidation validation = new RelatedInstancesValidation();
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ public ValidationInformation setupValidationInformation(String path) throws IOException {
+ String jsonInput = new String(Files.readAllBytes(Paths.get(path)));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false,
+ sir.getRequestDetails().getRequestParameters());
+
+ info.setRequestScope("service");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ sir.getRequestDetails().getModelInfo().setModelCustomizationName("name");
+
+ info.setRequestInfo(sir.getRequestDetails().getRequestInfo());
+ return info;
+ }
+
@Test
public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException {
String requestJson = new String(Files.readAllBytes(
@@ -50,4 +73,64 @@ public class RelatedInstancesValidationTest extends BaseTest {
assertEquals(info.getVnfType(), "Test/name");
}
+
+ @Test
+ public void testCreateSIVpnBonding() throws IOException, ValidationException {
+ String requestJson = new String(Files.readAllBytes(
+ Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json")));
+ ObjectMapper mapper = new ObjectMapper();
+ ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class);
+ ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(),
+ Action.createInstance, 7, false, sir.getRequestDetails().getRequestParameters());
+ info.setRequestScope("service");
+ sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b");
+ sir.getRequestDetails().getModelInfo().setModelCustomizationName("name");
+ RelatedInstancesValidation validation = new RelatedInstancesValidation();
+ validation.validate(info);
+ RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
+
+ assertEquals(info.getRequestScope(), "service");
+ assertEquals(instanceList[0].getRelatedInstance().getModelInfo().getModelType().toString(), "vpnBinding");
+ assertEquals(instanceList[1].getRelatedInstance().getModelInfo().getModelType().toString(), "network");
+ }
+
+ @Test
+ public void validateModelTypeExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid modelType in relatedInstance is specified");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/VpnBondingValidation/NoModelType.json"));
+ }
+
+ @Test
+ public void validateInstanceNameVpnBindingExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid instanceName in relatedInstance for vpnBinding modelType is specified");
+ validation.validate(setupValidationInformation(
+ "src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json"));
+ }
+
+ @Test
+ public void validateInstanceNameNetworkExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid instanceName in relatedInstance for network modelType is specified");
+ validation.validate(setupValidationInformation(
+ "src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json"));
+ }
+
+ @Test
+ public void validateInstanceIdExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid instanceId in relatedInstance is specified");
+ validation.validate(
+ setupValidationInformation("src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json"));
+ }
+
+ @Test
+ public void validatemodelInvariantIdExceptionTest() throws IOException, ValidationException {
+ thrown.expect(ValidationException.class);
+ thrown.expectMessage("No valid modelInvariantId in relatedInstance is specified");
+ validation.validate(setupValidationInformation(
+ "src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json"));
+ }
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json
new file mode 100644
index 0000000000..573b7a3ebb
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/RelatedInstances/ServiceInstanceVpnBondingService.json
@@ -0,0 +1,57 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "vpn-name",
+ "modelInfo": {
+ "modelType": "vpnBinding"
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "network-name",
+ "modelInfo": {
+ "modelType": "network"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json
new file mode 100644
index 0000000000..efd80f3347
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json
@@ -0,0 +1,48 @@
+[
+ {
+ "id":"Call_BBToExecute:c4f603e4-a26e-11e9-b144-0242ac14000b",
+ "parentActivityInstanceId":"c4c6b647-a26e-11e9-b144-0242ac14000b",
+ "activityId":"Call_BBToExecute",
+ "activityName":"BB to Execute",
+ "activityType":"callActivity",
+ "processDefinitionKey":"ExecuteBuildingBlock",
+ "processDefinitionId":"ExecuteBuildingBlock:1:a46566de-a26b-11e9-b144-0242ac14000b",
+ "processInstanceId":"c4c6b647-a26e-11e9-b144-0242ac14000b",
+ "executionId":"c4f603e3-a26e-11e9-b144-0242ac14000b",
+ "taskId":null,
+ "calledProcessInstanceId":"c4f603e6-a26e-11e9-b144-0242ac14000b",
+ "calledCaseInstanceId":null,
+ "assignee":null,
+ "startTime":"2019-07-09T17:27:04.607+0000",
+ "endTime":"2019-07-09T17:27:05.545+0000",
+ "durationInMillis":938,
+ "canceled":true,
+ "completeScope":false,
+ "tenantId":null,
+ "removalTime":null,
+ "rootProcessInstanceId":"c2fd4066-a26e-11e9-b144-0242ac14000b"
+ },
+ {
+ "id":"EndEvent_0mvmk3i:c59b1d39-a26e-11e9-b144-0242ac14000b",
+ "parentActivityInstanceId":"SubProcess_0tv8zda:c5852427-a26e-11e9-b144-0242ac14000b",
+ "activityId":"EndEvent_0mvmk3i",
+ "activityName":null,
+ "activityType":"noneEndEvent",
+ "processDefinitionKey":"ExecuteBuildingBlock",
+ "processDefinitionId":"ExecuteBuildingBlock:1:a46566de-a26b-11e9-b144-0242ac14000b",
+ "processInstanceId":"c4c6b647-a26e-11e9-b144-0242ac14000b",
+ "executionId":"c5852426-a26e-11e9-b144-0242ac14000b",
+ "taskId":null,
+ "calledProcessInstanceId":null,
+ "calledCaseInstanceId":null,
+ "assignee":null,
+ "startTime":"2019-07-09T17:27:05.689+0000",
+ "endTime":"2019-07-09T17:27:05.689+0000",
+ "durationInMillis":0,
+ "canceled":false,
+ "completeScope":true,
+ "tenantId":null,
+ "removalTime":null,
+ "rootProcessInstanceId":"c2fd4066-a26e-11e9-b144-0242ac14000b"
+ }
+ ] \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json
index 3b2eca7ce2..96fed36d45 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json
@@ -61,7 +61,7 @@
},
"requestStatus": {
"requestState": "COMPLETE",
- "statusMessage": "STATUS: Vf Module has been deleted successfully. FLOW STATUS: Building blocks 1 of 3 completed. ROLLBACK STATUS: Rollback has been completed successfully.",
+ "statusMessage": "STATUS: Vf Module has been deleted successfully. FLOW STATUS: Building blocks 1 of 3 completed. TASK INFORMATION: Last task executed: BB to Execute ROLLBACK STATUS: Rollback has been completed successfully.",
"percentProgress": 100,
"timestamp": "Thu, 22 Dec 2016 08:30:28 GMT"
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json
index 90089c0c7e..801841313a 100644
--- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/OrchestrationList.json
@@ -34,7 +34,7 @@
},
{
"request":{
- "requestId":"00032ab7-na18-42e5-965d-8ea592502018",
+ "requestId":"00032ab7-1a18-42e5-965d-8ea592502018",
"requestScope":"vfModule",
"requestType":"deleteInstance",
"requestDetails":{
@@ -58,7 +58,7 @@
},
"requestStatus":{
"requestState":"PENDING",
- "statusMessage":"FLOW STATUS: Building blocks 1 of 3 completed. RETRY STATUS: Retry 2/5 will be started in 8 min. ROLLBACK STATUS: Rollback has been completed successfully.",
+ "statusMessage":"FLOW STATUS: Building blocks 1 of 3 completed. TASK INFORMATION: Last task executed: BB to Execute RETRY STATUS: Retry 2/5 will be started in 8 min. ROLLBACK STATUS: Rollback has been completed successfully.",
"percentProgress":0,
"timestamp": "Thu, 22 Dec 2016 08:30:28 GMT"
}
@@ -298,7 +298,7 @@
},
{
"request":{
- "requestId":"00032ab7-na18-42e5-965d-8ea592502018",
+ "requestId":"00032ab7-1a18-42e5-965d-8ea592502018",
"requestScope":"instanceGroup",
"requestType":"addMembers",
"requestDetails":{
@@ -321,7 +321,7 @@
},
"requestStatus":{
"requestState":"PENDING",
- "statusMessage":"STATUS: Adding members. FLOW STATUS: Building blocks 1 of 3 completed. RETRY STATUS: Retry 2/5 will be started in 8 min. ROLLBACK STATUS: Rollback has been completed successfully.",
+ "statusMessage":"STATUS: Adding members. FLOW STATUS: Building blocks 1 of 3 completed. TASK INFORMATION: Last task executed: BB to Execute RETRY STATUS: Retry 2/5 will be started in 8 min. ROLLBACK STATUS: Rollback has been completed successfully.",
"percentProgress":0,
"timestamp": "Thu, 22 Dec 2016 08:30:28 GMT"
}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json
new file mode 100644
index 0000000000..faa283463b
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json
@@ -0,0 +1,44 @@
+[
+ {
+ "id":"c2fd4066-a26e-11e9-b144-0242ac14000b",
+ "businessKey":"84eacc7b-b046-4333-9272-5e8513bdd4cc",
+ "processDefinitionId":"WorkflowActionBB:1:a461210d-a26b-11e9-b144-0242ac14000b",
+ "processDefinitionKey":"WorkflowActionBB",
+ "processDefinitionName":"WorkflowActionBB",
+ "processDefinitionVersion":1,
+ "startTime":"2019-07-09T17:27:01.299+0000",
+ "endTime":"2019-07-09T17:27:06.585+0000",
+ "removalTime":null,
+ "durationInMillis":5286,
+ "startUserId":null,
+ "startActivityId":"Start_WorkflowActionBB",
+ "deleteReason":null,
+ "rootProcessInstanceId":"c2fd4066-a26e-11e9-b144-0242ac14000b",
+ "superProcessInstanceId":null,
+ "superCaseInstanceId":null,
+ "caseInstanceId":null,
+ "tenantId":null,
+ "state":"COMPLETED"
+ },
+ {
+ "id":"c4c6b647-a26e-11e9-b144-0242ac14000b",
+ "businessKey":null,
+ "processDefinitionId":"ExecuteBuildingBlock:1:a46566de-a26b-11e9-b144-0242ac14000b",
+ "processDefinitionKey":"ExecuteBuildingBlock",
+ "processDefinitionName":"ExecuteBuildingBlock",
+ "processDefinitionVersion":1,
+ "startTime":"2019-07-09T17:27:04.298+0000",
+ "endTime":"2019-07-09T17:27:05.690+0000",
+ "removalTime":null,
+ "durationInMillis":1392,
+ "startUserId":null,
+ "startActivityId":"Start_ExecuteBuildingBlock",
+ "deleteReason":null,
+ "rootProcessInstanceId":"c2fd4066-a26e-11e9-b144-0242ac14000b",
+ "superProcessInstanceId":"c2fd4066-a26e-11e9-b144-0242ac14000b",
+ "superCaseInstanceId":null,
+ "caseInstanceId":null,
+ "tenantId":null,
+ "state":"COMPLETED"
+ }
+ ] \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json
new file mode 100644
index 0000000000..41d7e4d706
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/OrchestrationRequest/getOrchestrationOpenstackRequestDetails.json
@@ -0,0 +1,62 @@
+{
+ "clientRequestId": "00032ab7-3fb3-42e5-965d-8ea592502016",
+ "action": "deleteInstance",
+ "requestStatus": "COMPLETE",
+ "statusMessage": "Vf Module has been deleted successfully.",
+ "progress": 100,
+ "startTime": "2016-12-22T13:29:54.000+0000",
+ "endTime": "2016-12-22T13:30:28.000+0000",
+ "source": "VID",
+ "vnfId": "b92f60c8-8de3-46c1-8dc1-e4390ac2b005",
+ "vnfName": null,
+ "vnfType": null,
+ "serviceType": null,
+ "aicNodeClli": null,
+ "tenantId": "6accefef3cb442ff9e644d589fb04107",
+ "provStatus": null,
+ "vnfParams": null,
+ "vnfOutputs": null,
+ "requestBody": "{\"modelInfo\":{\"modelType\":\"vfModule\",\"modelName\":\"test::base::module-0\"},\"requestInfo\":{\"source\":\"VID\"},\"cloudConfiguration\":{\"tenantId\":\"6accefef3cb442ff9e644d589fb04107\",\"lcpCloudRegionId\":\"n6\"}}",
+ "responseBody": null,
+ "lastModifiedBy": "BPMN",
+ "modifyTime": "2016-12-22T13:30:28.000+0000",
+ "requestType": null,
+ "volumeGroupId": null,
+ "volumeGroupName": null,
+ "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992",
+ "vfModuleName": null,
+ "vfModuleModelName": "test::base::module-0",
+ "aaiServiceId": null,
+ "aicCloudRegion": "n6",
+ "callBackUrl": null,
+ "correlator": null,
+ "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc",
+ "serviceInstanceName": null,
+ "requestScope": "vfModule",
+ "requestAction": "deleteInstance",
+ "networkId": null,
+ "networkName": null,
+ "networkType": null,
+ "requestorId": null,
+ "configurationId": null,
+ "configurationName": null,
+ "operationalEnvId": null,
+ "operationalEnvName": null,
+ "cloudApiRequests":[
+ {
+ "id": 1,
+ "cloudIdentifier": "heatstackName/123123",
+ "requestBody":"{\r\n \"test\": \"00032ab7-3fb3-42e5-965d-8ea592502016\",\r\n \"test2\": \"deleteInstance\",\r\n \"test3\": \"COMPLETE\",\r\n \"test4\": \"Vf Module has been deleted successfully.\",\r\n \"test5\": 100\r\n}",
+ "created": "2016-12-22T13:29:54.000+0000"
+ }
+ ],
+ "requestURI": "00032ab7-3fb3-42e5-965d-8ea592502017",
+ "_links": {
+ "self": {
+ "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017"
+ },
+ "infraActiveRequests": {
+ "href": "http://localhost:8087/infraActiveRequests/00032ab7-3fb3-42e5-965d-8ea592502017"
+ }
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json
new file mode 100644
index 0000000000..5da139e711
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json
@@ -0,0 +1,13 @@
+{
+ "requestDetails":{
+ "requestInfo":{
+ "source":"VID",
+ "requestorId":"xxxxxx",
+ "instanceName":"testService",
+ "productFamilyId":"test"
+ },
+ "requestParameters":{
+ "usePreload": "false"
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json
new file mode 100644
index 0000000000..d6406338a0
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json
@@ -0,0 +1,19 @@
+{
+ "requestDetails":{
+ "modelInfo":{
+ "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965",
+ "modelVersion": "1.0",
+ "modelType":"service",
+ "modelName":"serviceModel"
+ },
+ "requestInfo":{
+ "source":"VID",
+ "requestorId":"xxxxxx",
+ "instanceName":"testService",
+ "productFamilyId":"test"
+ },
+ "requestParameters":{
+ "aLaCarte":"false"
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json
new file mode 100644
index 0000000000..740d4e2ec2
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBodyNewRequestorId.json
@@ -0,0 +1,19 @@
+{
+ "requestDetails":{
+ "modelInfo":{
+ "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965",
+ "modelVersion": "1.0",
+ "modelType":"service",
+ "modelName":"serviceModel"
+ },
+ "requestInfo":{
+ "source":"VID",
+ "requestorId":"yyyyyy",
+ "instanceName":"testService",
+ "productFamilyId":"test"
+ },
+ "requestParameters":{
+ "aLaCarte":"false"
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/CustomWorkflowRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/CustomWorkflowRequest.json
new file mode 100644
index 0000000000..6c59ec5f1f
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/CustomWorkflowRequest.json
@@ -0,0 +1,21 @@
+{
+ "requestDetails": {
+ "requestInfo": {
+ "source": "VID",
+ "requestorId": "xxxxxx",
+ "instanceName": "inPlaceSoftwareUpdateTest"
+ },
+ "cloudConfiguration": {
+ "lcpCloudRegionId": "mdt1",
+ "tenantId": "88a6ca3ee0394ade9403f075db23167e"
+ },
+ "requestParameters": {
+ "payload": "{\"request-parameters\":{\"host-ip-address\":\"10.10.10.10\"},\"configuration-parameters\":{\"name1\":\"value1\",\"name2\":\"value2\"}}",
+ "userParams": [{
+ "name": "vnf-id",
+ "value": "4603ad6d-dbfb-4899-a8bd-bc1dd0d74914"
+ }
+ ]
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json
new file mode 100644
index 0000000000..166f7ccce8
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ReplaceVfModuleRetainAssignments.json
@@ -0,0 +1,33 @@
+{
+ "requestDetails": {
+ "requestInfo": {
+ "source": "VID",
+ "requestorId": "xxxxxx",
+ "instanceName": "testService60"
+ },
+ "requestParameters": {
+ "aLaCarte": true,
+ "autoBuildVfModules": false,
+ "retainAssignments": true,
+ "subscriptionServiceType": "test"
+ },
+ "cloudConfiguration": {
+ "lcpCloudRegionId": "mdt1",
+ "tenantId": "88a6ca3ee0394ade9403f075db23167e"
+ },
+ "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"
+ }
+ }
+}
+
+ \ No newline at end of file
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/ServiceInstanceTest/ServiceInstanceVpnBondingService.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json
new file mode 100644
index 0000000000..573b7a3ebb
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceVpnBondingService.json
@@ -0,0 +1,57 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "vpn-name",
+ "modelInfo": {
+ "modelType": "vpnBinding"
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "network-name",
+ "modelInfo": {
+ "modelType": "network"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json
new file mode 100644
index 0000000000..97e480c8d8
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceId.json
@@ -0,0 +1,56 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceName": "vpn-name",
+ "modelInfo": {
+ "modelType": "vpnBinding"
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "network-name",
+ "modelInfo": {
+ "modelType": "network"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json
new file mode 100644
index 0000000000..f7ba4761b6
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameNetwork.json
@@ -0,0 +1,56 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "vpn-name",
+ "modelInfo": {
+ "modelType": "vpnBinding"
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "modelInfo": {
+ "modelType": "network"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json
new file mode 100644
index 0000000000..ac570b3830
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoInstanceNameVpnBinding.json
@@ -0,0 +1,56 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "modelInfo": {
+ "modelType": "vpnBinding"
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "network-name",
+ "modelInfo": {
+ "modelType": "network"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json
new file mode 100644
index 0000000000..ca02c5371a
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelInvariantId.json
@@ -0,0 +1,57 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "vpn-name",
+ "modelInfo": {
+ "modelType": "vnf"
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "network-name",
+ "modelInfo": {
+ "modelType": "service"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json
new file mode 100644
index 0000000000..1d46ce2ccd
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/Validation/VpnBondingValidation/NoModelType.json
@@ -0,0 +1,56 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelInvariantId": "1710f6e8-1c29-4990-9aea-e943a2ec3d21",
+ "modelVersionId": "1710966e-097c-4d63-afda-e0d3bb7015fb",
+ "modelName": "Test",
+ "modelVersion": "1.0"
+ },
+ "cloudConfiguration": {
+ "cloudOwner": "test-mgr",
+ "lcpCloudRegionId": "abc1",
+ "tenantId": "19123c2924c648eb8e42a3c1f14b7682"
+ },
+ "owningEntity": {
+ "owningEntityId": "038d99af-0427-42c2-9d15-971b99b9b489",
+ "owningEntityName": "PACKET CORE"
+ },
+ "project": {
+ "projectName": "projectName"
+ },
+ "subscriberInfo": {
+ "globalSubscriberId": "TEST_123",
+ "subscriberName": "TEST_123"
+ },
+ "requestInfo": {
+ "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb",
+ "requestorId": "xxxxxx",
+ "source": "VID",
+ "suppressRollback": false
+ },
+ "relatedInstanceList": [
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "vpn-name",
+ "modelInfo": {
+ }
+ }
+ },
+ {
+ "relatedInstance": {
+ "instanceId": "ff305d54-75b4-431b-adb2-eb6b9e5ff000",
+ "instanceName": "network-name",
+ "modelInfo": {
+ "modelType": "network"
+ }
+ }
+ }
+ ],
+ "requestParameters": {
+ "subscriptionServiceType": "dev-service-type",
+ "aLaCarte": false
+ }
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json
new file mode 100644
index 0000000000..3ad3d1efec
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedServiceRequest.json
@@ -0,0 +1,20 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "service",
+ "modelVersionId": "bad955c3-29b2-4a27-932e-28e942cc6480",
+ "modelUuid": "bad955c3-29b2-4a27-932e-28e942cc6480"
+ },
+ "requestInfo": {
+ "instanceName": "Robot_SI_For_VolumeGroup",
+ "suppressRollback": false
+ },
+ "requestParameters": {
+ "userParams": [],
+ "aLaCarte": true,
+ "testApi": "GR_API"
+ },
+ "instanceName": [],
+ "configurationParameters": []
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json
new file mode 100644
index 0000000000..9670c3b645
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVfModuleRequest.json
@@ -0,0 +1,25 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "vfModule",
+ "modelCustomizationUuid": "074c64d0-7e13-4bcc-8bdb-ea922331102d",
+ "modelCustomizationId": "074c64d0-7e13-4bcc-8bdb-ea922331102d"
+ },
+ "requestInfo": {
+ "instanceName": "dummy_id",
+ "suppressRollback": false
+ },
+ "cloudConfiguration": {
+ "tenantId": "0422ffb57ba042c0800a29dc85ca70f8",
+ "cloudOwner": "cloudOwner",
+ "lcpCloudRegionId": "regionOne"
+ },
+ "requestParameters": {
+ "userParams": [],
+ "aLaCarte": true,
+ "testApi": "GR_API"
+ },
+ "instanceName": [],
+ "configurationParameters": []
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json
new file mode 100644
index 0000000000..59602f7ac2
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVnfRequest.json
@@ -0,0 +1,20 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "vnf",
+ "modelCustomizationUuid": "96c23a4a-6887-4b2c-9cce-1e4ea35eaade",
+ "modelCustomizationId": "96c23a4a-6887-4b2c-9cce-1e4ea35eaade"
+ },
+ "requestInfo": {
+ "instanceName": "Robot_VNF_For_Volume_Group",
+ "suppressRollback": false
+ },
+ "requestParameters": {
+ "userParams": [],
+ "aLaCarte": true,
+ "testApi": "GR_API"
+ },
+ "instanceName": [],
+ "configurationParameters": []
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json
new file mode 100644
index 0000000000..ec7acf1e41
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ExpectedVolumeGroupRequest.json
@@ -0,0 +1,25 @@
+{
+ "requestDetails": {
+ "modelInfo": {
+ "modelType": "volumeGroup",
+ "modelCustomizationUuid": "e38906fa-717c-49b0-b391-e6ec12b50c4a",
+ "modelCustomizationId": "e38906fa-717c-49b0-b391-e6ec12b50c4a"
+ },
+ "requestInfo": {
+ "instanceName": "VolumeGroup",
+ "suppressRollback": false
+ },
+ "cloudConfiguration": {
+ "tenantId": "0422ffb57ba042c0800a29dc85ca70f8",
+ "cloudOwner": "cloudOwner",
+ "lcpCloudRegionId": "regionOne"
+ },
+ "requestParameters": {
+ "userParams": [],
+ "aLaCarte": true,
+ "testApi": "GR_API"
+ },
+ "instanceName": [],
+ "configurationParameters": []
+ }
+} \ No newline at end of file
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json
new file mode 100644
index 0000000000..7d7a103123
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/ServiceInstance.json
@@ -0,0 +1,35 @@
+{
+ "service-instance-id": "e9fbfab4-d91c-4508-a429-2046c8751371",
+ "service-instance-name": "Robot_SI_For_VolumeGroup",
+ "environment-context": "General_Revenue-Bearing",
+ "model-invariant-id": "b16a9398-ffa3-4041-b78c-2956b8ad9c7b",
+ "model-version-id": "bad955c3-29b2-4a27-932e-28e942cc6480",
+ "resource-version": "1560538276937",
+ "orchestration-status": "Active",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "project",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v15/business/projects/project/GR_API_OE_MSO_Test200",
+ "relationship-data": [
+ {
+ "relationship-key": "project.project-name",
+ "relationship-value": "GR_API_OE_MSO_Test200"
+ }
+ ]
+ },
+ {
+ "related-to": "owning-entity",
+ "relationship-label": "org.onap.relationships.inventory.BelongsTo",
+ "related-link": "/aai/v15/business/owning-entities/owning-entity/c3f57fa8-ac7d-11e8-98d0-529269fb1459",
+ "relationship-data": [
+ {
+ "relationship-key": "owning-entity.owning-entity-id",
+ "relationship-value": "c3f57fa8-ac7d-11e8-98d0-529269fb1459"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json
new file mode 100644
index 0000000000..cfd9eb3e3c
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VfModule.json
@@ -0,0 +1,37 @@
+{
+ "vf-module-id": "b70060b7-0031-4065-9462-3cd5b753d2db",
+ "vf-module-name": "dummy_id",
+ "heat-stack-id": "dummy_id/stackId",
+ "orchestration-status": "Active",
+ "is-base-vf-module": true,
+ "automated-assignment": false,
+ "resource-version": "1560538368229",
+ "model-invariant-id": "f7a867f2-596b-4f4a-a128-421e825a6190",
+ "model-version-id": "eb5de6fb-9ecf-4009-b922-fae3a9ae7d46",
+ "model-customization-id": "074c64d0-7e13-4bcc-8bdb-ea922331102d",
+ "module-index": 0,
+ "selflink": "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/e9fbfab4-d91c-4508-a429-2046c8751371/service-data/vnfs/vnf/829924cc-8932-4875-b0af-d7a02799da9a/vnf-data//vf-modules/vf-module/dummy_id/vf-module-data/vf-module-topology/",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "volume-group",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/volume-groups/volume-group/18b220c8-af84-4b82-a8c0-41bbea6328a6",
+ "relationship-data": [
+ {
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "cloudOwner"
+ },
+ {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "regionOne"
+ },
+ {
+ "relationship-key": "volume-group.volume-group-id",
+ "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6"
+ }
+ ]
+ }
+ ]
+ }
+}
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
new file mode 100644
index 0000000000..0b03f56caa
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json
@@ -0,0 +1,131 @@
+{
+ "vnf-id": "829924cc-8932-4875-b0af-d7a02799da9a",
+ "vnf-name": "Robot_VNF_For_Volume_Group",
+ "vnf-type": "Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0",
+ "service-id": "06f76284-8710-11e6-ae22-56b6b6499611",
+ "prov-status": "PREPROV",
+ "orchestration-status": "Active",
+ "in-maint": false,
+ "is-closed-loop-disabled": false,
+ "resource-version": "1560538316260",
+ "model-invariant-id": "23122c9b-dd7f-483f-bf0a-e069303db2f7",
+ "model-version-id": "d326f424-2312-4dd6-b7fe-364fadbd1ef5",
+ "model-customization-id": "96c23a4a-6887-4b2c-9cce-1e4ea35eaade",
+ "selflink": "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/e9fbfab4-d91c-4508-a429-2046c8751371/service-data/vnfs/vnf/829924cc-8932-4875-b0af-d7a02799da9a/vnf-data/vnf-topology/",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "service-instance",
+ "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+ "related-link": "/aai/v15/business/customers/customer/Robot_Test_Subscriber_ID/service-subscriptions/service-subscription/Robot_Test_Service_Type/service-instances/service-instance/e9fbfab4-d91c-4508-a429-2046c8751371",
+ "relationship-data": [
+ {
+ "relationship-key": "customer.global-customer-id",
+ "relationship-value": "Robot_Test_Subscriber_ID"
+ },
+ {
+ "relationship-key": "service-subscription.service-type",
+ "relationship-value": "Robot_Test_Service_Type"
+ },
+ {
+ "relationship-key": "service-instance.service-instance-id",
+ "relationship-value": "e9fbfab4-d91c-4508-a429-2046c8751371"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "service-instance.service-instance-name",
+ "property-value": "Robot_SI_For_VolumeGroup"
+ }
+ ]
+ },
+ {
+ "related-to": "platform",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v15/business/platforms/platform/vSAMP12_14-2XXX-Aug18-9001%20-%20Platform",
+ "relationship-data": [
+ {
+ "relationship-key": "platform.platform-name",
+ "relationship-value": "vSAMP12_14-2XXX-Aug18-9001 - Platform"
+ }
+ ]
+ },
+ {
+ "related-to": "line-of-business",
+ "relationship-label": "org.onap.relationships.inventory.Uses",
+ "related-link": "/aai/v15/business/lines-of-business/line-of-business/vSAMP12_14-2XXX-Aug18-9001%20-%20LOB",
+ "relationship-data": [
+ {
+ "relationship-key": "line-of-business.line-of-business-name",
+ "relationship-value": "vSAMP12_14-2XXX-Aug18-9001 - LOB"
+ }
+ ]
+ },
+ {
+ "related-to": "tenant",
+ "relationship-label": "org.onap.relationships.inventory.BelongsTo",
+ "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/tenants/tenant/0422ffb57ba042c0800a29dc85ca70f8",
+ "relationship-data": [
+ {
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "cloudOwner"
+ },
+ {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "regionOne"
+ },
+ {
+ "relationship-key": "tenant.tenant-id",
+ "relationship-value": "0422ffb57ba042c0800a29dc85ca70f8"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "tenant.tenant-name",
+ "property-value": "tenantName"
+ }
+ ]
+ },
+ {
+ "related-to": "volume-group",
+ "relationship-label": "org.onap.relationships.inventory.DependsOn",
+ "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/volume-groups/volume-group/volumeGroupId",
+ "relationship-data": [
+ {
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "cloudOwner"
+ },
+ {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "regionOne"
+ },
+ {
+ "relationship-key": "volume-group.volume-group-id",
+ "relationship-value": "volumeGroupId"
+ }
+ ]
+ },
+ {
+ "related-to": "cloud-region",
+ "relationship-label": "org.onap.relationships.inventory.LocatedIn",
+ "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne",
+ "relationship-data": [
+ {
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "cloudOwner"
+ },
+ {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "regionOne"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "cloud-region.owner-defined-type",
+ "property-value": "LCP"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json
new file mode 100644
index 0000000000..328b82ed55
--- /dev/null
+++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VolumeGroup.json
@@ -0,0 +1,56 @@
+{
+ "volume-group-id": "5e6bca5b-8e14-4bdd-a419-820f68019b19",
+ "volume-group-name": "VolumeGroup",
+ "heat-stack-id": "VolumeGroup/stackId",
+ "vnf-type": "Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0",
+ "orchestration-status": "Active",
+ "model-customization-id": "e38906fa-717c-49b0-b391-e6ec12b50c4a",
+ "vf-module-model-customization-id": "e38906fa-717c-49b0-b391-e6ec12b50c4a",
+ "resource-version": "1560526466219",
+ "relationship-list": {
+ "relationship": [
+ {
+ "related-to": "tenant",
+ "relationship-label": "org.onap.relationships.inventory.DependsOn",
+ "related-link": "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/regionOne/tenants/tenant/0422ffb57ba042c0800a29dc85ca70f8",
+ "relationship-data": [
+ {
+ "relationship-key": "cloud-region.cloud-owner",
+ "relationship-value": "cloudOwner"
+ },
+ {
+ "relationship-key": "cloud-region.cloud-region-id",
+ "relationship-value": "regionOne"
+ },
+ {
+ "relationship-key": "tenant.tenant-id",
+ "relationship-value": "0422ffb57ba042c0800a29dc85ca70f8"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "tenant.tenant-name",
+ "property-value": "tenantName"
+ }
+ ]
+ },
+ {
+ "related-to": "generic-vnf",
+ "relationship-label": "org.onap.relationships.inventory.DependsOn",
+ "related-link": "/aai/v15/network/generic-vnfs/generic-vnf/82035634-1878-4fd9-ab14-04b819bea24b",
+ "relationship-data": [
+ {
+ "relationship-key": "generic-vnf.vnf-id",
+ "relationship-value": "82035634-1878-4fd9-ab14-04b819bea24b"
+ }
+ ],
+ "related-to-property": [
+ {
+ "property-key": "generic-vnf.vnf-name",
+ "property-value": "Robot_VNF_For_Volume_Group"
+ }
+ ]
+ }
+ ]
+ }
+}
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 712fbf54ca..27e1ae90d2 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,20 @@ 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}
infra-requests:
archived:
period: 180
@@ -83,6 +89,8 @@ mso:
spring:
+ jersey:
+ type: filter
datasource:
jdbcUrl: jdbc:mariadb://localhost:3307/catalogdb
username: root
@@ -97,11 +105,10 @@ spring:
naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
enable-lazy-load-no-trans: true
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
- jersey:
- type: filter
+
security:
usercredentials:
- -
+ -
username: test
password: '$2a$12$Zi3AuYcZoZO/gBQyUtST2.F5N6HqcTtaNci2Et.ufsQhski56srIu'
role: InfraPortal-Client
@@ -117,7 +124,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/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql
index bc9003f5d0..ee53e491a4 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
@@ -806,6 +806,9 @@ CREATE TABLE `service` (
`WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL,
`SERVICE_CATEGORY` varchar(200) DEFAULT NULL,
`RESOURCE_ORDER` varchar(200) default NULL,
+ `OVERALL_DISTRIBUTION_STATUS` varchar(45),
+ `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL,
+ `NAMING_POLICY` varchar(200) DEFAULT NULL,
PRIMARY KEY (`MODEL_UUID`),
KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`),
CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE
@@ -1108,6 +1111,8 @@ 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,
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`),
@@ -1134,6 +1139,8 @@ CREATE TABLE `vnfc_customization` (
`MODEL_NAME` varchar(200) NOT NULL,
`TOSCA_NODE_TYPE` varchar(200) NOT NULL,
`DESCRIPTION` varchar(1200) DEFAULT NULL,
+ `RESOURCE_INPUT` varchar(20000) DEFAULT NULL,
+ `VNFC_INSTANCE_GROUP_CUSTOMIZATION_ID` integer DEFAULT NULL,
`CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -1284,7 +1291,10 @@ CREATE TABLE `infra_active_requests` (
`CONFIGURATION_NAME` varchar(200) DEFAULT NULL,
`OPERATIONAL_ENV_ID` varchar(45) DEFAULT NULL,
`OPERATIONAL_ENV_NAME` varchar(200) DEFAULT NULL,
- `REQUEST_URL` varchar(500) DEFAULT NULL,
+ `REQUEST_URL` varchar(500) DEFAULT NULL,
+ `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`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
@@ -1460,6 +1470,16 @@ create table if not exists model (
FOREIGN KEY (`RECIPE`) REFERENCES `model_recipe` (`MODEL_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+CREATE TABLE IF NOT EXISTS `requestdb`.`cloud_api_requests` (
+`ID` INT(13) NOT NULL AUTO_INCREMENT,
+`REQUEST_BODY` LONGTEXT NOT NULL,
+`CLOUD_IDENTIFIER` VARCHAR(200) NULL,
+`SO_REQUEST_ID` VARCHAR(45) NOT NULL,
+`CREATE_TIME` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+PRIMARY KEY (`ID`),
+INDEX `fk_cloud_api_requests__so_request_id_idx` (`SO_REQUEST_ID` ASC))
+ENGINE = InnoDB DEFAULT CHARSET=latin1;
+
CREATE TABLE IF NOT EXISTS `workflow` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ARTIFACT_UUID` varchar(200) NOT NULL,
@@ -1477,8 +1497,3 @@ CREATE TABLE IF NOT EXISTS `workflow` (
PRIMARY KEY (`ID`),
UNIQUE KEY `UK_workflow` (`ARTIFACT_UUID`,`NAME`,`VERSION`,`SOURCE`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-
-
-
-
-