diff options
48 files changed, 1755 insertions, 972 deletions
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java b/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java index 354c3d07f7..691ae60afd 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/db/migration/R__CloudConfigMigration.java @@ -128,8 +128,8 @@ public class R__CloudConfigMigration implements JdbcMigration, MigrationInfoProv private void migrateCloudIdentity(Collection<CloudIdentity> entities, Connection connection) throws SQLException { logger.debug("Starting migration for CloudConfig-->IdentityService"); String insert = - "INSERT INTO `identity_services` (`ID`, `IDENTITY_URL`, `MSO_ID`, `MSO_PASS`, `ADMIN_TENANT`, `MEMBER_ROLE`, `TENANT_METADATA`, `IDENTITY_SERVER_TYPE`, `IDENTITY_AUTHENTICATION_TYPE`, `LAST_UPDATED_BY`) " - + "VALUES (?,?,?,?,?,?,?,?,?,?);"; + "INSERT INTO `identity_services` (`ID`, `IDENTITY_URL`, `MSO_ID`, `MSO_PASS`, `ADMIN_TENANT`, `MEMBER_ROLE`, `TENANT_METADATA`, `IDENTITY_SERVER_TYPE`, `IDENTITY_AUTHENTICATION_TYPE`, `LAST_UPDATED_BY`, `PROJECT_DOMAIN_NAME`, `USER_DOMAIN_NAME`) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?);"; try (Statement stmt = connection.createStatement(); PreparedStatement ps = connection.prepareStatement(insert)) { @@ -157,6 +157,8 @@ public class R__CloudConfigMigration implements JdbcMigration, MigrationInfoProv ? cloudIdentity.getIdentityAuthenticationType().name() : null); ps.setString(10, FLYWAY); + ps.setString(11, cloudIdentity.getProjectDomainName()); + ps.setString(12, cloudIdentity.getUserDomainName()); ps.executeUpdate(); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java index c1cc7428ee..5261f8ae19 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java @@ -23,8 +23,6 @@ package org.onap.so.adapters.inventory.create; import javax.annotation.PostConstruct; import org.camunda.bpm.client.ExternalTaskClient; import org.onap.so.utils.ExternalTaskServiceUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; @@ -34,8 +32,6 @@ import org.springframework.stereotype.Component; @Profile("!test") public class CreateInventoryService { - private static final Logger logger = LoggerFactory.getLogger(CreateInventoryService.class); - @Autowired public Environment env; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index 2c78e593a1..9adcdcb47a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java @@ -414,34 +414,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { return new HashMap<>(stringInputs); } - protected boolean callHeatbridge(String heatStackId) { - String executionDir = "/usr/local/lib/python2.7/dist-packages/heatbridge"; - String openstackIdentityUrl = "", username = "", password = "", tenant = "", region = "", owner = ""; - long waitTimeMs = 10000L; - try { - String[] cmdarray = {"/usr/bin/python", "HeatBridgeMain.py", openstackIdentityUrl, username, password, - tenant, region, owner, heatStackId}; - String[] envp = null; - File dir = new File(executionDir); - logger.debug("Calling HeatBridgeMain.py in {} with arguments {}", dir, Arrays.toString(cmdarray)); - Runtime r = Runtime.getRuntime(); - Process p = r.exec(cmdarray, envp, dir); - boolean wait = p.waitFor(waitTimeMs, TimeUnit.MILLISECONDS); - - logger.debug(" HeatBridgeMain.py returned {} with code {}", wait, p.exitValue()); - return wait && p.exitValue() == 0; - } catch (IOException e) { - logger.debug(" HeatBridgeMain.py failed with IO Exception! {}", e); - return false; - } catch (RuntimeException e) { - logger.debug(" HeatBridgeMain.py failed during runtime! {}", e); - return false; - } catch (Exception e) { - logger.debug(" HeatBridgeMain.py failed for unknown reasons! {}", e); - return false; - } - } - private void heatbridge(StackInfo heatStack, String cloudOwner, String cloudSiteId, String tenantId, String genericVnfName, String vfModuleId) { try { @@ -632,11 +604,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { vfRollback.setIsBase(isBaseRequest); vfRollback.setModelCustomizationUuid(mcu); - // Put data into A&AI through Heatstack - if (enableBridge != null && enableBridge) { - callHeatbridge(baseVfHeatStackId); - } - // handle a nestedStackId if sent- this one would be for the volume - so applies to both Vf and Vnf StackInfo nestedHeatStack = null; Map<String, Object> nestedVolumeOutputs = null; @@ -1107,6 +1074,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (backout == null) { backout = true; } + if (failIfExists == null) { + failIfExists = false; + } if (msoHeatUtils != null) { heatStack = msoHeatUtils.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, @@ -1156,8 +1126,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } logger.debug("VF Module {} successfully created", vfModuleName); - // call heatbridge - heatbridge(heatStack, cloudOwner, cloudSiteId, tenantId, genericVnfName, vfModuleId); + if (enableBridge != null && enableBridge) { + // call heatbridge + heatbridge(heatStack, cloudOwner, cloudSiteId, tenantId, genericVnfName, vfModuleId); + } } catch (Exception e) { logger.debug("unhandled exception in create VF", e); throw new VnfException("Exception during create VF " + e.getMessage()); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java index 0d972bb4d2..f3cad76c9d 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java @@ -85,6 +85,20 @@ public class MsoVnfAdapterImplTest extends BaseRestTestUtils { } @Test + public void createVnfTest_NullFailIfExists() throws Exception { + mockOpenStackResponseAccess(wireMockServer, wireMockPort); + mockOpenStackGetStackVfModule_200(wireMockServer); + + MsoRequest msoRequest = getMsoRequest(); + + Map<String, Object> map = new HashMap<>(); + map.put("key1", "value1"); + instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", + "VFMOD", null, null, "b4ea86b4-253f-11e7-93ae-92361f002671", map, null, Boolean.TRUE, Boolean.FALSE, + msoRequest, new Holder<>(), new Holder<Map<String, String>>(), new Holder<VnfRollback>()); + } + + @Test public void createVnfTest_HeatStatusFailed() throws Exception { mockOpenStackResponseAccess(wireMockServer, wireMockPort); wireMockServer.stubFor(get( diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java index f6a0aec86f..28e931a3e1 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomController.java @@ -74,4 +74,9 @@ public class InfraActiveRequestsRepositoryCustomController { @RequestParam(value = "maxResult", required = false) Integer maxResult) { return infraActiveRequestsRepository.getInfraActiveRequests(filters, startTime, endTime, maxResult); } + + @RequestMapping(method = RequestMethod.GET, value = "/infraActiveRequests/getInProgressVolumeGroupsAndVfModules") + public List<InfraActiveRequests> getInProgressVolumeGroupsAndVfModules() { + return infraActiveRequestsRepository.getInProgressVolumeGroupsAndVfModules(); + } } diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java index 4ed3285a70..896138f955 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java @@ -21,8 +21,13 @@ package org.onap.so.adapters.requestsdb; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -33,6 +38,7 @@ import org.junit.Before; import org.junit.Test; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.data.controller.InstanceNameDuplicateCheckRequest; +import org.onap.so.serviceinstancebeans.ModelType; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; @@ -91,14 +97,6 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA @Before public void setup() { - - headers = new HttpHeaders(); - restTemplate = new TestRestTemplate("test", "test"); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - headers.set("Authorization", msoAdaptersAuth); - infraActiveRequests = new InfraActiveRequests(); infraActiveRequests.setRequestId(UUID.randomUUID().toString()); @@ -126,12 +124,22 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA infraActiveRequests .setRequestUrl("http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances"); - HttpEntity<String> entity = new HttpEntity(infraActiveRequests, headers); + saveInfraActiveRequest(infraActiveRequests); + } + + public void saveInfraActiveRequest(InfraActiveRequests request) { + headers = new HttpHeaders(); + restTemplate = new TestRestTemplate("test", "test"); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set("Authorization", msoAdaptersAuth); + + HttpEntity<String> entity = new HttpEntity(request, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort("/infraActiveRequests")); ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); - assertEquals(201, response.getStatusCodeValue()); } @@ -297,4 +305,38 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA assertEquals(200, response.getStatusCodeValue()); assertEquals(null, response.getBody()); } + + @Test + public void getInProgressVolumeGroupsAndVfModulesTest() { + boolean expectedReturned = false; + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId(UUID.randomUUID().toString()); + request.setVfModuleId(UUID.randomUUID().toString()); + request.setRequestStatus("IN_PROGRESS"); + request.setRequestScope(ModelType.vfModule.toString()); + Instant startInstant = Instant.now().minus(3, ChronoUnit.MINUTES); + request.setStartTime(Timestamp.from(startInstant)); + request.setRequestAction("create"); + saveInfraActiveRequest(request); + + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/infraActiveRequests/getInProgressVolumeGroupsAndVfModules")); + + HttpEntity<String> entity = new HttpEntity<String>(headers); + + ResponseEntity<List<InfraActiveRequests>> response = restTemplate.exchange(builder.toUriString(), + HttpMethod.GET, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {}); + + List<InfraActiveRequests> responseList = response.getBody(); + + assertEquals(200, response.getStatusCodeValue()); + + for (InfraActiveRequests result : responseList) { + if (result.getRequestId().equals(request.getRequestId())) { + assertThat(request, sameBeanAs(result).ignoring("modifyTime")); + expectedReturned = true; + } + } + assertTrue(expectedReturned); + } } diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java index 49291b6863..67887378ef 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java @@ -27,6 +27,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.sql.Timestamp; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -41,6 +43,7 @@ import org.onap.so.db.request.beans.OperationStatus; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; import org.onap.so.db.request.beans.RequestProcessingData; +import org.onap.so.serviceinstancebeans.ModelType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.server.LocalServerPort; @@ -314,4 +317,20 @@ public class RequestsDbClientTest extends RequestsAdapterBase { verifyInfraActiveRequests(infraActiveRequestsResponse.get(0)); } + + @Test + public void getInProgressVolumeGroupsAndVfModulesTest() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId(UUID.randomUUID().toString()); + request.setVfModuleId(UUID.randomUUID().toString()); + request.setRequestStatus("IN_PROGRESS"); + request.setRequestScope(ModelType.vfModule.toString()); + Instant startInstant = Instant.now().minus(3, ChronoUnit.MINUTES); + request.setStartTime(Timestamp.from(startInstant)); + request.setRequestAction("create"); + requestsDbClient.save(request); + + List<InfraActiveRequests> infraActiveRequests = requestsDbClient.getInProgressVolumeGroupsAndVfModules(); + assertThat(request, sameBeanAs(infraActiveRequests.get(0)).ignoring("modifyTime")); + } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java index 3bdba368b2..d898de3ad0 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderImpl.java @@ -136,15 +136,9 @@ public class VnfmServiceProviderImpl implements VnfmServiceProvider { logger.error(errorMessage, exception); throw new VnfmRequestFailureException(errorMessage, exception); } - if (response.getStatusCode() != HttpStatus.ACCEPTED) { - final String errorMessage = "Terminate request to " + vnfSelfLink + " returned status code: " - + response.getStatusCode() + ", request: " + terminateVnfRequest; - logger.error(errorMessage); - throw new VnfmRequestFailureException(errorMessage); - } + checkIfResponseIsAcceptable(response, vnfSelfLink, terminateVnfRequest); final String locationHeader = response.getHeaders().get("Location").iterator().next(); return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); - } @Override @@ -177,6 +171,22 @@ public class VnfmServiceProviderImpl implements VnfmServiceProvider { } } + private void checkIfResponseIsAcceptable(ResponseEntity<Void> response, String vnfSelfLink, + TerminateVnfRequest terminateVnfRequest) { + if (response == null) { + final String errorMessage = + "Terminate request to " + vnfSelfLink + ", response is null, " + "request: " + terminateVnfRequest; + logger.error(errorMessage); + throw new VnfmRequestFailureException(errorMessage); + } + if (response.getStatusCode() != HttpStatus.ACCEPTED) { + final String errorMessage = "Terminate request to " + vnfSelfLink + ", returned status code: " + + response.getStatusCode() + ", request: " + terminateVnfRequest; + logger.error(errorMessage); + throw new VnfmRequestFailureException(errorMessage); + } + } + private HttpRestServiceProvider getHttpServiceProvider(final EsrVnfm vnfm) { return vnfmServiceProviderConfiguration.getHttpRestServiceProvider(vnfm); } diff --git a/asdc-controller/pom.xml b/asdc-controller/pom.xml index 60c517d944..c3b2c739c3 100644 --- a/asdc-controller/pom.xml +++ b/asdc-controller/pom.xml @@ -16,7 +16,7 @@ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <antlr.version>4.7.1</antlr.version> <java.version>1.8</java.version> - <sdc.tosca.version>1.5.1</sdc.tosca.version> + <sdc.tosca.version>1.6.5</sdc.tosca.version> <jtosca.version>1.5.1</jtosca.version> </properties> diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java index 00ca74b5f4..3f9e52779d 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java @@ -714,24 +714,24 @@ public class ToscaResourceInstaller { } - protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) { - Metadata metadata = nodeTemplate.getMetaData(); + protected ConfigurationResource getConfigurationResource(IEntityDetails configEntity) { + Metadata metadata = configEntity.getMetadata(); ConfigurationResource configResource = new ConfigurationResource(); configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - configResource.setToscaNodeType(nodeTemplate.getType()); + configResource.setToscaNodeType(configEntity.getToscaType()); return configResource; } - protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate, + protected ConfigurationResourceCustomization getConfigurationResourceCustomization(IEntityDetails configEntity, ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization, Service service) { - Metadata metadata = nodeTemplate.getMetaData(); + Metadata metadata = configEntity.getMetadata(); - ConfigurationResource configResource = getConfigurationResource(nodeTemplate); + ConfigurationResource configResource = getConfigurationResource(configEntity); ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization(); @@ -739,14 +739,12 @@ public class ToscaResourceInstaller { configCustomizationResource .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - configCustomizationResource.setModelInstanceName(nodeTemplate.getName()); - - configCustomizationResource.setFunction( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "function")); - configCustomizationResource.setRole( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "role")); - configCustomizationResource.setType( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, "type")); + configCustomizationResource.setModelInstanceName(configEntity.getName()); + + configCustomizationResource.setFunction(getLeafPropertyValue(configEntity, "function")); + configCustomizationResource.setRole(getLeafPropertyValue(configEntity, "role")); + configCustomizationResource.setType(getLeafPropertyValue(configEntity, "type")); + configCustomizationResource.setServiceProxyResourceCustomization(spResourceCustomization); configCustomizationResource.setConfigurationResource(configResource); @@ -758,37 +756,39 @@ public class ToscaResourceInstaller { return configCustomizationResource; } - protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) { - List<NodeTemplate> serviceProxyResourceList = - toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY); + List<IEntityDetails> spEntityList = + getEntityDetails(toscaResourceStruct, EntityQuery.newBuilder(SdcTypes.SERVICE_PROXY), + TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false); - List<NodeTemplate> configurationNodeTemplatesList = - toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); + List<IEntityDetails> configEntityList = + getEntityDetails(toscaResourceStruct, EntityQuery.newBuilder(SdcTypes.CONFIGURATION), + TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE), false); List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<>(); List<ConfigurationResourceCustomization> configurationResourceList = new ArrayList<>(); ServiceProxyResourceCustomization serviceProxy = null; - if (serviceProxyResourceList != null) { - for (NodeTemplate spNode : serviceProxyResourceList) { - serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct); + if (spEntityList != null) { + for (IEntityDetails spEntity : spEntityList) { + serviceProxy = createServiceProxy(spEntity, service, toscaResourceStruct); serviceProxyList.add(serviceProxy); - for (NodeTemplate configNode : configurationNodeTemplatesList) { + for (IEntityDetails configEntity : configEntityList) { - List<RequirementAssignment> requirementsList = - toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll(); - for (RequirementAssignment requirement : requirementsList) { - if (requirement.getNodeTemplateName().equals(spNode.getName())) { - ConfigurationResourceCustomization configurationResource = createConfiguration(configNode, + List<RequirementAssignment> requirements = configEntity.getRequirements(); + + for (RequirementAssignment requirement : requirements) { + + if (requirement.getNodeTemplateName().equals(spEntity.getName())) { + ConfigurationResourceCustomization configurationResource = createConfiguration(configEntity, toscaResourceStruct, serviceProxy, service, configurationResourceList); Optional<ConfigurationResourceCustomization> matchingObject = configurationResourceList.stream() - .filter(configurationResourceCustomization -> configNode.getMetaData() + .filter(configurationResourceCustomization -> configEntity.getMetadata() .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID) .equals(configurationResource.getModelCustomizationUUID())) .filter(configurationResourceCustomization -> configurationResourceCustomization @@ -1110,7 +1110,7 @@ public class ToscaResourceInstaller { boolean hasRequirements = false; for (IEntityDetails vnfcDetails : vnfcMemberNodes) { - Map<String, RequirementAssignment> requirements = vnfcDetails.getRequirements(); + List<RequirementAssignment> requirements = vnfcDetails.getRequirements(); if (requirements != null && !requirements.isEmpty()) { hasRequirements = true; @@ -1146,15 +1146,14 @@ public class ToscaResourceInstaller { boolean isAllExists = true; - Map<String, RequirementAssignment> requirements = memberNode.getRequirements(); + List<RequirementAssignment> requirements = memberNode.getRequirements(); if (requirements == null || requirements.isEmpty()) { continue; } - for (Map.Entry<String, RequirementAssignment> entry : requirements.entrySet()) { - RequirementAssignment rqa = entry.getValue(); + for (RequirementAssignment rqa : requirements) { String name = rqa.getNodeTemplateName(); for (IEntityDetails node : vnfcMemberNodes) { if (name.equals(node.getName())) { @@ -1439,10 +1438,10 @@ public class ToscaResourceInstaller { return service; } - protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service, + protected ServiceProxyResourceCustomization createServiceProxy(IEntityDetails spEntity, Service service, ToscaResourceStructure toscaResourceStructure) { - Metadata spMetadata = nodeTemplate.getMetaData(); + Metadata spMetadata = spEntity.getMetadata(); ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization(); @@ -1457,15 +1456,15 @@ public class ToscaResourceInstaller { spCustomizationResource .setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - spCustomizationResource.setModelInstanceName(nodeTemplate.getName()); - spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); + spCustomizationResource.setModelInstanceName(spEntity.getName()); + spCustomizationResource.setToscaNodeType(spEntity.getToscaType()); String sourceServiceUUID = spMetadata.getValue("sourceModelUuid"); Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID); spCustomizationResource.setSourceService(sourceService); - spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); + spCustomizationResource.setToscaNodeType(spEntity.getToscaType()); serviceProxyCustomizationSet.add(spCustomizationResource); @@ -1474,20 +1473,20 @@ public class ToscaResourceInstaller { return spCustomizationResource; } - protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate, + protected ConfigurationResourceCustomization createConfiguration(IEntityDetails configEntity, ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization, Service service, List<ConfigurationResourceCustomization> configurationResourceList) { ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization( - nodeTemplate, toscaResourceStructure, spResourceCustomization, service); + configEntity, toscaResourceStructure, spResourceCustomization, service); ConfigurationResource configResource = null; ConfigurationResource existingConfigResource = findExistingConfiguration(service, - nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID), configurationResourceList); + configEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_UUID), configurationResourceList); if (existingConfigResource == null) { - configResource = getConfigurationResource(nodeTemplate); + configResource = getConfigurationResource(configEntity); } else { configResource = existingConfigResource; } @@ -2192,9 +2191,9 @@ public class ToscaResourceInstaller { for (IEntityDetails fabricEntity : fabricEntityList) { - Map<String, RequirementAssignment> requirements = fabricEntity.getRequirements(); + List<RequirementAssignment> requirements = fabricEntity.getRequirements(); - for (RequirementAssignment requirement : requirements.values()) { + for (RequirementAssignment requirement : requirements) { if (requirement.getNodeTemplateName().equals(cvfcEntity.getName())) { @@ -2417,8 +2416,7 @@ public class ToscaResourceInstaller { Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream() .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID() - .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, - SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))) + .equalsIgnoreCase(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))) .findFirst(); if (matchingObject.isPresent()) { @@ -2575,20 +2573,26 @@ public class ToscaResourceInstaller { vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger( entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT))); - entityDetails.getCapabilities().get(SCALABLE); + List<CapabilityAssignment> capAssignList = entityDetails.getCapabilities(); + if (capAssignList != null) { - if (entityDetails.getCapabilities() != null) { + for (CapabilityAssignment capAssign : capAssignList) { - CapabilityAssignment capAssign = entityDetails.getCapabilities().get(SCALABLE); - if (capAssign != null) { - vnfResourceCustomization.setMinInstances(Integer - .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - vnfResourceCustomization.setMaxInstances(Integer - .getInteger(getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - } + if (capAssign != null) { + String capabilityName = capAssign.getName(); + + if (capabilityName.equalsIgnoreCase(SCALABLE)) { + vnfResourceCustomization.setMinInstances(Integer.getInteger( + getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + vnfResourceCustomization.setMaxInstances(Integer.getInteger( + getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + } + } + + } } if (vnfResourceCustomization.getMinInstances() == null && vnfResourceCustomization.getMaxInstances() == null) { @@ -2695,12 +2699,11 @@ public class ToscaResourceInstaller { } } - Map<String, CapabilityAssignment> capAssignmentList = arEntity.getCapabilities(); + List<CapabilityAssignment> capAssignmentList = arEntity.getCapabilities(); if (capAssignmentList != null) { - for (Map.Entry<String, CapabilityAssignment> entry : capAssignmentList.entrySet()) { - CapabilityAssignment arCapability = entry.getValue(); + for (CapabilityAssignment arCapability : capAssignmentList) { if (arCapability != null) { diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java index 07eca567d5..6908fe4eda 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java @@ -714,6 +714,9 @@ public class ASDCNotificationLogging { if ("Allotted Resource".equalsIgnoreCase(category)) { + buffer.append(System.lineSeparator()); + buffer.append("Allotted Resource Properties:"); + buffer.append(System.lineSeparator()); buffer.append("Model Name:"); buffer.append(testNull(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); buffer.append(System.lineSeparator()); @@ -739,6 +742,7 @@ public class ASDCNotificationLogging { buffer.append("Model Description:"); buffer.append(arEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); buffer.append("Allotted Resource Customization Properties:"); @@ -784,6 +788,9 @@ public class ASDCNotificationLogging { if ("Allotted Resource".equalsIgnoreCase(category)) { + buffer.append(System.lineSeparator()); + buffer.append("Allotted Resource Properties:"); + buffer.append(System.lineSeparator()); buffer.append("Model Name:"); buffer.append(testNull(pnfAREntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); buffer.append(System.lineSeparator()); @@ -809,7 +816,7 @@ public class ASDCNotificationLogging { buffer.append("Model Description:"); buffer.append(pnfAREntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); buffer.append(System.lineSeparator()); - + buffer.append(System.lineSeparator()); buffer.append("Allotted Resource Customization Properties:"); buffer.append(System.lineSeparator()); diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java index ffad137ad7..958519f879 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInstallerTest.java @@ -622,8 +622,8 @@ public class ToscaResourceInstallerTest extends BaseTest { } private void prepareConfigurationResource() { - doReturn(metadata).when(nodeTemplate).getMetaData(); - doReturn(MockConstants.TEMPLATE_TYPE).when(nodeTemplate).getType(); + doReturn(metadata).when(entityDetails).getMetadata(); + doReturn(MockConstants.TEMPLATE_TYPE).when(entityDetails).getToscaType(); doReturn(MockConstants.MODEL_NAME).when(metadata).getValue(SdcPropertyNames.PROPERTY_NAME_NAME); doReturn(MockConstants.MODEL_INVARIANT_UUID).when(metadata) @@ -639,7 +639,7 @@ public class ToscaResourceInstallerTest extends BaseTest { public void getConfigurationResourceTest() { prepareConfigurationResource(); - ConfigurationResource configResource = toscaInstaller.getConfigurationResource(nodeTemplate); + ConfigurationResource configResource = toscaInstaller.getConfigurationResource(entityDetails); assertNotNull(configResource); assertEquals(MockConstants.MODEL_NAME, configResource.getModelName()); @@ -647,7 +647,7 @@ public class ToscaResourceInstallerTest extends BaseTest { assertEquals(MockConstants.MODEL_UUID, configResource.getModelUUID()); assertEquals(MockConstants.MODEL_VERSION, configResource.getModelVersion()); assertEquals(MockConstants.MODEL_DESCRIPTION, configResource.getDescription()); - assertEquals(MockConstants.TEMPLATE_TYPE, nodeTemplate.getType()); + assertEquals(MockConstants.TEMPLATE_TYPE, entityDetails.getToscaType()); } private void prepareConfigurationResourceCustomization() { @@ -655,13 +655,11 @@ public class ToscaResourceInstallerTest extends BaseTest { doReturn(MockConstants.MODEL_CUSTOMIZATIONUUID).when(metadata) .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); doReturn(csarHelper).when(toscaResourceStructure).getSdcCsarHelper(); - doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, - SdcPropertyNames.PROPERTY_NAME_NFFUNCTION); - doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, - SdcPropertyNames.PROPERTY_NAME_NFROLE); - doReturn(null).when(csarHelper).getNodeTemplatePropertyLeafValue(nodeTemplate, - SdcPropertyNames.PROPERTY_NAME_NFTYPE); doReturn(MockConstants.MODEL_CUSTOMIZATIONUUID).when(spResourceCustomization).getModelCustomizationUUID(); + doReturn(null).when(toscaInstaller).getLeafPropertyValue(entityDetails, + SdcPropertyNames.PROPERTY_NAME_NFFUNCTION); + doReturn(null).when(toscaInstaller).getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFROLE); + doReturn(null).when(toscaInstaller).getLeafPropertyValue(entityDetails, SdcPropertyNames.PROPERTY_NAME_NFTYPE); } @@ -670,7 +668,7 @@ public class ToscaResourceInstallerTest extends BaseTest { prepareConfigurationResourceCustomization(); ConfigurationResourceCustomization configurationResourceCustomization = - toscaInstaller.getConfigurationResourceCustomization(nodeTemplate, toscaResourceStructure, + toscaInstaller.getConfigurationResourceCustomization(entityDetails, toscaResourceStructure, spResourceCustomization, service); assertNotNull(configurationResourceCustomization); assertNotNull(configurationResourceCustomization.getConfigurationResource()); diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/AsyncTaskExecutor.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/AsyncTaskExecutor.java deleted file mode 100644 index 56526c7f89..0000000000 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/AsyncTaskExecutor.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.onap.so.bpmn.core.plugins; - -import org.camunda.bpm.engine.delegate.ExecutionListener; -import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener; -import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl; -import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl; -import org.camunda.bpm.engine.impl.util.xml.Element; -import org.springframework.stereotype.Component; - -@Component -public class AsyncTaskExecutor extends AbstractBpmnParseListener { - - private void injectTaskExecutorExecutionListener(ActivityImpl activity) { - activity.addListener(ExecutionListener.EVENTNAME_END, new AsyncTaskExecutorListener()); - } - - @Override - public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) { - injectTaskExecutorExecutionListener(activity); - } -} diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/BPMNProcessCompletePlugin.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/BPMNProcessCompletePlugin.java deleted file mode 100644 index 96c6af42ed..0000000000 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/core/plugins/BPMNProcessCompletePlugin.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 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.bpmn.core.plugins; - -import java.util.ArrayList; -import java.util.List; -import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener; -import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin; -import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - - - -@Component -public class BPMNProcessCompletePlugin extends AbstractProcessEnginePlugin { - - @Autowired - private AsyncTaskExecutor asyncTaskExecutor; - - @Override - public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { - List<BpmnParseListener> preParseListeners = processEngineConfiguration.getCustomPreBPMNParseListeners(); - if (preParseListeners == null) { - preParseListeners = new ArrayList<>(); - processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners); - } - preParseListeners.add(asyncTaskExecutor); - } - -} diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn index bb900420e3..e112fdc161 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn @@ -1,6 +1,9 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.1.2"> <bpmn:process id="WorkflowActionBB" name="WorkflowActionBB" isExecutable="true"> + <bpmn:extensionElements> + <camunda:executionListener class="org.onap.so.bpmn.core.plugins.AsyncTaskExecutorListener" event="end" /> + </bpmn:extensionElements> <bpmn:startEvent id="Start_WorkflowActionBB" name="start"> <bpmn:outgoing>SequenceFlow_15s0okp</bpmn:outgoing> </bpmn:startEvent> @@ -46,7 +49,7 @@ <bpmn:outgoing>SequenceFlow_0l7kaba</bpmn:outgoing> </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_1m2eezj" name="Completed = true" sourceRef="ExclusiveGateway_Finished" targetRef="ExclusiveGateway_isTopLevelFlowC"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("completed")==true&&execution.getVariable("isRollback")==false&&execution.getVariable("handlingCode")=="Success"}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("completed")==true&&execution.getVariable("isRollback")==false&&execution.getVariable("handlingCode")=="Success"}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:serviceTask id="Task_RetrieveBBExectuionList" name="Retrieve BB Execution List" camunda:expression="${WorkflowAction.selectExecutionList(execution)}"> <bpmn:incoming>SequenceFlow_15s0okp</bpmn:incoming> @@ -83,7 +86,7 @@ </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_024g0d1" name="no" sourceRef="ExclusiveGateway_10q79b6" targetRef="Task_UpdateDb" /> <bpmn:sequenceFlow id="SequenceFlow_0vi883o" name="yes" sourceRef="ExclusiveGateway_10q79b6" targetRef="Task_SendSyncAckError"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isTopLevelFlow")==true&&execution.getVariable("sentSyncResponse")==false}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("isTopLevelFlow")==true&&execution.getVariable("sentSyncResponse")==false}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_0eana0l" sourceRef="Task_SendSyncAckError" targetRef="Task_UpdateDb" /> <bpmn:serviceTask id="Task_SendSyncAckError" name="Send Sync Ack API Handler" camunda:asyncAfter="true" camunda:expression="${WorkflowActionBBTasks.sendSyncAck(execution)}"> @@ -92,10 +95,10 @@ </bpmn:serviceTask> </bpmn:subProcess> <bpmn:sequenceFlow id="SequenceFlow_0v588sm" name="Rollback = true" sourceRef="ExclusiveGateway_Finished" targetRef="Task_RollbackExecutionPath"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("handlingCode")=="Rollback"||execution.getVariable("handlingCode")=="RollbackToAssigned"||execution.getVariable("handlingCode")=="RollbackToCreated"}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("handlingCode")=="Rollback"||execution.getVariable("handlingCode")=="RollbackToAssigned"||execution.getVariable("handlingCode")=="RollbackToCreated"}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_1atzsgn" sourceRef="Task_RollbackExecutionPath" targetRef="Task_SelectBB"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isRollbackNeeded")==true}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("isRollbackNeeded")==true}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:serviceTask id="Task_RollbackExecutionPath" name="Rollback Execution Path" camunda:expression="${WorkflowActionBBTasks.rollbackExecutionPath(execution)}"> <bpmn:incoming>SequenceFlow_0v588sm</bpmn:incoming> @@ -104,7 +107,7 @@ </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_0vc9go9" sourceRef="Task_RetrieveBBExectuionList" targetRef="ExclusiveGateway_isTopLevelFlow" /> <bpmn:sequenceFlow id="SequenceFlow_11530ei" name="Abort = true" sourceRef="ExclusiveGateway_Finished" targetRef="ExclusiveGateway_isTopLevelFlowAbort"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("handlingCode")=="Abort"}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("handlingCode")=="Abort"}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:serviceTask id="Task_AbortAndCallErrorHandling" name="Update Request To Failed" camunda:expression="${WorkflowActionBBFailure.updateRequestStatusToFailed(execution)}"> <bpmn:incoming>SequenceFlow_02ksbt0</bpmn:incoming> @@ -127,7 +130,7 @@ </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_0sckerv" name="yes" sourceRef="ExclusiveGateway_isTopLevelFlow" targetRef="Task_SendSync" /> <bpmn:sequenceFlow id="SequenceFlow_0unbew4" name="no" sourceRef="ExclusiveGateway_isTopLevelFlow" targetRef="Task_PreValidateWorkflow"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isTopLevelFlow")==false}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("isTopLevelFlow")==false}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:exclusiveGateway id="ExclusiveGateway_isTopLevelFlowAbort" name="Is Top-Level Flow?" default="SequenceFlow_02ksbt0"> <bpmn:incoming>SequenceFlow_11530ei</bpmn:incoming> @@ -136,7 +139,7 @@ </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_02ksbt0" name="yes" sourceRef="ExclusiveGateway_isTopLevelFlowAbort" targetRef="Task_AbortAndCallErrorHandling" /> <bpmn:sequenceFlow id="SequenceFlow_1r570x3" name="no" sourceRef="ExclusiveGateway_isTopLevelFlowAbort" targetRef="EndEvent_0lzz1ya"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isTopLevelFlow")==false}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("isTopLevelFlow")==false}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:exclusiveGateway id="ExclusiveGateway_isTopLevelFlowC" name="Is Top-Level Flow?" default="SequenceFlow_0kf5sen"> <bpmn:incoming>SequenceFlow_1m2eezj</bpmn:incoming> @@ -144,13 +147,13 @@ <bpmn:outgoing>SequenceFlow_0kf5sen</bpmn:outgoing> </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_0x4urgp" name="no" sourceRef="ExclusiveGateway_isTopLevelFlowC" targetRef="End_WorkflowActionBB"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isTopLevelFlow")==false}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("isTopLevelFlow")==false}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:endEvent id="End_RollbackFailed" name="end"> <bpmn:incoming>SequenceFlow_1ui67mc</bpmn:incoming> </bpmn:endEvent> <bpmn:sequenceFlow id="SequenceFlow_11dlyzt" name="Rollback Not Needed" sourceRef="Task_RollbackExecutionPath" targetRef="Task_UpdateRequestToFailed"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isRollbackNeeded")==false}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("isRollbackNeeded")==false}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:serviceTask id="Task_UpdateRequestToFailed" name="Update Request To Failed" camunda:expression="${WorkflowActionBBFailure.updateRequestStatusToFailedWithRollback(execution)}"> <bpmn:incoming>SequenceFlow_11dlyzt</bpmn:incoming> @@ -158,7 +161,7 @@ <bpmn:outgoing>SequenceFlow_1ui67mc</bpmn:outgoing> </bpmn:serviceTask> <bpmn:sequenceFlow id="SequenceFlow_0l7kaba" name="Rollback Completed" sourceRef="ExclusiveGateway_Finished" targetRef="Task_UpdateRequestToFailed"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("completed")==true&&execution.getVariable("isRollback")==true&&execution.getVariable("handlingCode")=="Success"}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("completed")==true&&execution.getVariable("isRollback")==true&&execution.getVariable("handlingCode")=="Success"}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_1ui67mc" sourceRef="Task_UpdateRequestToFailed" targetRef="End_RollbackFailed" /> <bpmn:subProcess id="SubProcess_0fuugr9" name="Java Exception Handling Sub Process" triggeredByEvent="true"> @@ -202,7 +205,7 @@ </bpmn:exclusiveGateway> <bpmn:sequenceFlow id="SequenceFlow_1lrz41x" sourceRef="Task_SendSync" targetRef="ExclusiveGateway_1dez26n" /> <bpmn:sequenceFlow id="SequenceFlow_0etawv5" name="no" sourceRef="ExclusiveGateway_1dez26n" targetRef="Task_PreValidateWorkflow"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("generateIdsOnly") == null || execution.getVariable("generateIdsOnly")==false}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">${execution.getVariable("generateIdsOnly") == null || execution.getVariable("generateIdsOnly")==false}</bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:endEvent id="EndEvent_12f15tu" name="End"> <bpmn:incoming>SequenceFlow_0ilo6lo</bpmn:incoming> @@ -213,406 +216,406 @@ <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="WorkflowActionBB"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="Start_WorkflowActionBB"> - <dc:Bounds x="-434" y="102" width="36" height="36" /> + <dc:Bounds x="156" y="378" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-426" y="138" width="22" height="12" /> + <dc:Bounds x="164" y="414" width="22" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_1uv6erv_di" bpmnElement="End_WorkflowActionBB"> - <dc:Bounds x="1304" y="147" width="36" height="36" /> + <dc:Bounds x="1894" y="423" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1313" y="127" width="18" height="12" /> + <dc:Bounds x="1903" y="403" width="19" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_15s0okp_di" bpmnElement="SequenceFlow_15s0okp"> - <di:waypoint xsi:type="dc:Point" x="-398" y="120" /> - <di:waypoint xsi:type="dc:Point" x="-365" y="120" /> + <di:waypoint x="192" y="396" /> + <di:waypoint x="225" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="-381" y="99" width="0" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="CallActivity_03m7z4y_di" bpmnElement="Call_ExecuteBB"> - <dc:Bounds x="560" y="80" width="100" height="80" /> + <dc:Bounds x="1150" y="356" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0mqrkxv_di" bpmnElement="SequenceFlow_0mqrkxv"> - <di:waypoint xsi:type="dc:Point" x="339" y="120" /> - <di:waypoint xsi:type="dc:Point" x="400" y="120" /> + <di:waypoint x="929" y="396" /> + <di:waypoint x="990" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="324.5" y="105" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1snenqk_di" bpmnElement="Task_SelectBB"> - <dc:Bounds x="239" y="80" width="100" height="80" /> + <dc:Bounds x="829" y="356" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ExclusiveGateway_0m1zt0q_di" bpmnElement="ExclusiveGateway_Finished" isMarkerVisible="true"> - <dc:Bounds x="911" y="95" width="50" height="50" /> + <dc:Bounds x="1501" y="371" width="50" height="50" /> <bpmndi:BPMNLabel> <dc:Bounds x="850" y="42" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1m2eezj_di" bpmnElement="SequenceFlow_1m2eezj"> - <di:waypoint xsi:type="dc:Point" x="949" y="132" /> - <di:waypoint xsi:type="dc:Point" x="980" y="165" /> - <di:waypoint xsi:type="dc:Point" x="1060" y="165" /> + <di:waypoint x="1539" y="408" /> + <di:waypoint x="1570" y="441" /> + <di:waypoint x="1650" y="441" /> <bpmndi:BPMNLabel> - <dc:Bounds x="968" y="168" width="83" height="12" /> + <dc:Bounds x="1557" y="444" width="85" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0kn8jt8_di" bpmnElement="Task_RetrieveBBExectuionList"> - <dc:Bounds x="-365" y="80" width="100" height="80" /> + <dc:Bounds x="225" y="356" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_0654g3m_di" bpmnElement="Task_SendSync"> - <dc:Bounds x="-100" y="-76" width="100" height="80" /> + <dc:Bounds x="490" y="200" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_0wzh11j_di" bpmnElement="Task_UpdateRequestComplete"> - <dc:Bounds x="1161" y="206" width="100" height="80" /> + <dc:Bounds x="1751" y="482" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1pz6edz_di" bpmnElement="SequenceFlow_1pz6edz"> - <di:waypoint xsi:type="dc:Point" x="1261" y="246" /> - <di:waypoint xsi:type="dc:Point" x="1322" y="246" /> - <di:waypoint xsi:type="dc:Point" x="1322" y="183" /> + <di:waypoint x="1851" y="522" /> + <di:waypoint x="1912" y="522" /> + <di:waypoint x="1912" y="459" /> <bpmndi:BPMNLabel> <dc:Bounds x="1247" y="231" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="SubProcess_18226x4_di" bpmnElement="SubProcess_18226x4" isExpanded="true"> - <dc:Bounds x="498" y="444" width="438" height="297" /> + <dc:Bounds x="1088" y="720" width="438" height="297" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="StartEvent_184g7f3_di" bpmnElement="ErrorStart"> - <dc:Bounds x="520" y="639" width="36" height="36" /> + <dc:Bounds x="1110" y="915" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="526" y="682" width="24" height="12" /> + <dc:Bounds x="1116" y="958" width="24" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_0l4edvr_di" bpmnElement="ErrorEnd"> - <dc:Bounds x="880" y="639" width="36" height="36" /> + <dc:Bounds x="1470" y="915" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="890" y="681" width="18" height="12" /> + <dc:Bounds x="1480" y="957" width="19" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0v588sm_di" bpmnElement="SequenceFlow_0v588sm"> - <di:waypoint xsi:type="dc:Point" x="936" y="145" /> - <di:waypoint xsi:type="dc:Point" x="936" y="262" /> - <di:waypoint xsi:type="dc:Point" x="339" y="262" /> + <di:waypoint x="1526" y="421" /> + <di:waypoint x="1526" y="538" /> + <di:waypoint x="929" y="538" /> <bpmndi:BPMNLabel> - <dc:Bounds x="769.202380952381" y="272" width="73" height="12" /> + <dc:Bounds x="1359" y="548" width="74" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1atzsgn_di" bpmnElement="SequenceFlow_1atzsgn"> - <di:waypoint xsi:type="dc:Point" x="289" y="222" /> - <di:waypoint xsi:type="dc:Point" x="289" y="160" /> + <di:waypoint x="879" y="498" /> + <di:waypoint x="879" y="436" /> <bpmndi:BPMNLabel> <dc:Bounds x="259" y="191" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_19t1oyr_di" bpmnElement="Task_RollbackExecutionPath"> - <dc:Bounds x="239" y="222" width="100" height="80" /> + <dc:Bounds x="829" y="498" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0vc9go9_di" bpmnElement="SequenceFlow_0vc9go9"> - <di:waypoint xsi:type="dc:Point" x="-265" y="120" /> - <di:waypoint xsi:type="dc:Point" x="-228" y="120" /> + <di:waypoint x="325" y="396" /> + <di:waypoint x="362" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="-246" y="105" width="0" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_11530ei_di" bpmnElement="SequenceFlow_11530ei"> - <di:waypoint xsi:type="dc:Point" x="946" y="105" /> - <di:waypoint xsi:type="dc:Point" x="983" y="44" /> - <di:waypoint xsi:type="dc:Point" x="1060" y="45" /> + <di:waypoint x="1536" y="381" /> + <di:waypoint x="1573" y="320" /> + <di:waypoint x="1650" y="321" /> <bpmndi:BPMNLabel> - <dc:Bounds x="975" y="17" width="58" height="12" /> + <dc:Bounds x="1565" y="293" width="58" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0jo36ez_di" bpmnElement="Task_AbortAndCallErrorHandling"> - <dc:Bounds x="1176" y="-76" width="100" height="80" /> + <dc:Bounds x="1766" y="200" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_0lzz1ya_di" bpmnElement="EndEvent_0lzz1ya"> - <dc:Bounds x="1386" y="27" width="36" height="36" /> + <dc:Bounds x="1976" y="303" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1395" y="67" width="18" height="12" /> + <dc:Bounds x="1985" y="343" width="19" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1p8yxu6_di" bpmnElement="SequenceFlow_1p8yxu6"> - <di:waypoint xsi:type="dc:Point" x="1276" y="-36" /> - <di:waypoint xsi:type="dc:Point" x="1359" y="-36" /> - <di:waypoint xsi:type="dc:Point" x="1359" y="45" /> - <di:waypoint xsi:type="dc:Point" x="1386" y="45" /> + <di:waypoint x="1866" y="240" /> + <di:waypoint x="1949" y="240" /> + <di:waypoint x="1949" y="321" /> + <di:waypoint x="1976" y="321" /> <bpmndi:BPMNLabel> <dc:Bounds x="1329" y="5" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_01j184u_di" bpmnElement="SequenceFlow_01j184u"> - <di:waypoint xsi:type="dc:Point" x="936" y="95" /> - <di:waypoint xsi:type="dc:Point" x="936" y="55" /> - <di:waypoint xsi:type="dc:Point" x="936" y="55" /> - <di:waypoint xsi:type="dc:Point" x="936" y="4" /> + <di:waypoint x="1526" y="371" /> + <di:waypoint x="1526" y="331" /> + <di:waypoint x="1526" y="331" /> + <di:waypoint x="1526" y="280" /> <bpmndi:BPMNLabel> <dc:Bounds x="906" y="49" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1c1v3p1_di" bpmnElement="Task_0a31dkf"> - <dc:Bounds x="886" y="-76" width="100" height="80" /> + <dc:Bounds x="1476" y="200" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ExclusiveGateway_0ptb1yi_di" bpmnElement="ExclusiveGateway_isTopLevelFlow" isMarkerVisible="true"> - <dc:Bounds x="-228" y="95" width="50" height="50" /> + <dc:Bounds x="362" y="371" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-235" y="145" width="63" height="24" /> + <dc:Bounds x="357" y="421" width="60" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0sckerv_di" bpmnElement="SequenceFlow_0sckerv"> - <di:waypoint xsi:type="dc:Point" x="-202" y="96" /> - <di:waypoint xsi:type="dc:Point" x="-202" y="-36" /> - <di:waypoint xsi:type="dc:Point" x="-100" y="-36" /> + <di:waypoint x="388" y="372" /> + <di:waypoint x="388" y="240" /> + <di:waypoint x="490" y="240" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-195" y="17.612903225806477" width="19" height="12" /> + <dc:Bounds x="396" y="294" width="18" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0unbew4_di" bpmnElement="SequenceFlow_0unbew4"> - <di:waypoint xsi:type="dc:Point" x="-178" y="120" /> - <di:waypoint xsi:type="dc:Point" x="80" y="120" /> + <di:waypoint x="412" y="396" /> + <di:waypoint x="670" y="396" /> <bpmndi:BPMNLabel> - <dc:Bounds x="-87" y="99.95468180757382" width="12" height="12" /> + <dc:Bounds x="503" y="376" width="13" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ExclusiveGateway_001g41v_di" bpmnElement="ExclusiveGateway_isTopLevelFlowAbort" isMarkerVisible="true"> - <dc:Bounds x="1060" y="20" width="50" height="50" /> + <dc:Bounds x="1650" y="296" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1055" y="70" width="61" height="24" /> + <dc:Bounds x="1646" y="346" width="60" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_02ksbt0_di" bpmnElement="SequenceFlow_02ksbt0"> - <di:waypoint xsi:type="dc:Point" x="1085" y="20" /> - <di:waypoint xsi:type="dc:Point" x="1085" y="-37" /> - <di:waypoint xsi:type="dc:Point" x="1176" y="-37" /> + <di:waypoint x="1675" y="296" /> + <di:waypoint x="1675" y="239" /> + <di:waypoint x="1766" y="239" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1091" y="-8" width="19" height="12" /> + <dc:Bounds x="1682" y="268" width="18" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1r570x3_di" bpmnElement="SequenceFlow_1r570x3"> - <di:waypoint xsi:type="dc:Point" x="1110" y="45" /> - <di:waypoint xsi:type="dc:Point" x="1386" y="45" /> + <di:waypoint x="1700" y="321" /> + <di:waypoint x="1976" y="321" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1242" y="20" width="12" height="12" /> + <dc:Bounds x="1832" y="296" width="13" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ExclusiveGateway_1er1kam_di" bpmnElement="ExclusiveGateway_isTopLevelFlowC" isMarkerVisible="true"> - <dc:Bounds x="1060" y="140" width="50" height="50" /> + <dc:Bounds x="1650" y="416" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1055" y="108" width="61" height="24" /> + <dc:Bounds x="1646" y="384" width="60" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0x4urgp_di" bpmnElement="SequenceFlow_0x4urgp"> - <di:waypoint xsi:type="dc:Point" x="1110" y="165" /> - <di:waypoint xsi:type="dc:Point" x="1220" y="165" /> - <di:waypoint xsi:type="dc:Point" x="1220" y="165" /> - <di:waypoint xsi:type="dc:Point" x="1304" y="165" /> + <di:waypoint x="1700" y="441" /> + <di:waypoint x="1810" y="441" /> + <di:waypoint x="1810" y="441" /> + <di:waypoint x="1894" y="441" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1256" y="140" width="12" height="12" /> + <dc:Bounds x="1846" y="416" width="13" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_1q8eh5e_di" bpmnElement="End_RollbackFailed"> - <dc:Bounds x="1159" y="347" width="36" height="36" /> + <dc:Bounds x="1749" y="623" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1177" y="399" width="18" height="12" /> + <dc:Bounds x="1767" y="675" width="19" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_11dlyzt_di" bpmnElement="SequenceFlow_11dlyzt"> - <di:waypoint xsi:type="dc:Point" x="289" y="302" /> - <di:waypoint xsi:type="dc:Point" x="289" y="368" /> - <di:waypoint xsi:type="dc:Point" x="960" y="368" /> + <di:waypoint x="879" y="578" /> + <di:waypoint x="879" y="644" /> + <di:waypoint x="1550" y="644" /> <bpmndi:BPMNLabel> - <dc:Bounds x="381.45685840707966" y="325" width="63" height="24" /> + <dc:Bounds x="972" y="601" width="63" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_1h154rn_di" bpmnElement="Task_UpdateDb"> - <dc:Bounds x="713" y="617" width="100" height="80" /> + <dc:Bounds x="1303" y="893" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_1t8n9gd_di" bpmnElement="Task_UpdateRequestToFailed"> - <dc:Bounds x="960" y="325" width="100" height="80" /> + <dc:Bounds x="1550" y="601" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0l7kaba_di" bpmnElement="SequenceFlow_0l7kaba"> - <di:waypoint xsi:type="dc:Point" x="942" y="139" /> - <di:waypoint xsi:type="dc:Point" x="976" y="252" /> - <di:waypoint xsi:type="dc:Point" x="1016" y="252" /> - <di:waypoint xsi:type="dc:Point" x="1016" y="325" /> + <di:waypoint x="1532" y="415" /> + <di:waypoint x="1566" y="528" /> + <di:waypoint x="1606" y="528" /> + <di:waypoint x="1606" y="601" /> <bpmndi:BPMNLabel> - <dc:Bounds x="959" y="255" width="52" height="24" /> + <dc:Bounds x="1548" y="531" width="54" height="27" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1edjl5x_di" bpmnElement="SequenceFlow_1edjl5x"> - <di:waypoint xsi:type="dc:Point" x="556" y="657" /> - <di:waypoint xsi:type="dc:Point" x="602" y="657" /> + <di:waypoint x="1146" y="933" /> + <di:waypoint x="1192" y="933" /> <bpmndi:BPMNLabel> <dc:Bounds x="534" y="636" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0wvzfgf_di" bpmnElement="SequenceFlow_0wvzfgf"> - <di:waypoint xsi:type="dc:Point" x="813" y="657" /> - <di:waypoint xsi:type="dc:Point" x="880" y="657" /> + <di:waypoint x="1403" y="933" /> + <di:waypoint x="1470" y="933" /> <bpmndi:BPMNLabel> <dc:Bounds x="801.5" y="636" width="90" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1ui67mc_di" bpmnElement="SequenceFlow_1ui67mc"> - <di:waypoint xsi:type="dc:Point" x="1060" y="365" /> - <di:waypoint xsi:type="dc:Point" x="1134" y="365" /> - <di:waypoint xsi:type="dc:Point" x="1134" y="365" /> - <di:waypoint xsi:type="dc:Point" x="1159" y="365" /> + <di:waypoint x="1650" y="641" /> + <di:waypoint x="1724" y="641" /> + <di:waypoint x="1724" y="641" /> + <di:waypoint x="1749" y="641" /> <bpmndi:BPMNLabel> <dc:Bounds x="1104" y="359" width="90" height="13" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ExclusiveGateway_10q79b6_di" bpmnElement="ExclusiveGateway_10q79b6" isMarkerVisible="true"> - <dc:Bounds x="602" y="632" width="50" height="50" /> + <dc:Bounds x="1192" y="908" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="584" y="686" width="86" height="36" /> + <dc:Bounds x="1174" y="962" width="86" height="40" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_024g0d1_di" bpmnElement="SequenceFlow_024g0d1"> - <di:waypoint xsi:type="dc:Point" x="652" y="657" /> - <di:waypoint xsi:type="dc:Point" x="683" y="657" /> - <di:waypoint xsi:type="dc:Point" x="683" y="657" /> - <di:waypoint xsi:type="dc:Point" x="713" y="657" /> + <di:waypoint x="1242" y="933" /> + <di:waypoint x="1273" y="933" /> + <di:waypoint x="1273" y="933" /> + <di:waypoint x="1303" y="933" /> <bpmndi:BPMNLabel> - <dc:Bounds x="677" y="634" width="12" height="12" /> + <dc:Bounds x="1267" y="910" width="13" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0vi883o_di" bpmnElement="SequenceFlow_0vi883o"> - <di:waypoint xsi:type="dc:Point" x="627" y="632" /> - <di:waypoint xsi:type="dc:Point" x="627" y="548" /> - <di:waypoint xsi:type="dc:Point" x="713" y="548" /> + <di:waypoint x="1217" y="908" /> + <di:waypoint x="1217" y="824" /> + <di:waypoint x="1303" y="824" /> <bpmndi:BPMNLabel> - <dc:Bounds x="633" y="584" width="18" height="12" /> + <dc:Bounds x="1223" y="860" width="18" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0eana0l_di" bpmnElement="SequenceFlow_0eana0l"> - <di:waypoint xsi:type="dc:Point" x="763" y="588" /> - <di:waypoint xsi:type="dc:Point" x="763" y="617" /> + <di:waypoint x="1353" y="864" /> + <di:waypoint x="1353" y="893" /> <bpmndi:BPMNLabel> <dc:Bounds x="778" y="596.5" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_10hs368_di" bpmnElement="Task_SendSyncAckError"> - <dc:Bounds x="713" y="508" width="100" height="80" /> + <dc:Bounds x="1303" y="784" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="SubProcess_0fuugr9_di" bpmnElement="SubProcess_0fuugr9" isExpanded="true"> - <dc:Bounds x="515" y="792" width="404" height="165" /> + <dc:Bounds x="1105" y="1068" width="404" height="165" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="StartEvent_15qkxd7_di" bpmnElement="StartEvent_runtimeError"> - <dc:Bounds x="570" y="857" width="36" height="36" /> + <dc:Bounds x="1160" y="1133" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="577" y="900" width="24" height="12" /> + <dc:Bounds x="1167" y="1176" width="24" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_1p4kxh2_di" bpmnElement="ServiceTask_HandleRuntimeError"> - <dc:Bounds x="690" y="835" width="100" height="80" /> + <dc:Bounds x="1280" y="1111" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="EndEvent_09e3lu5_di" bpmnElement="EndEvent__runtimeError"> - <dc:Bounds x="856" y="857" width="36" height="36" /> + <dc:Bounds x="1446" y="1133" width="36" height="36" /> <bpmndi:BPMNLabel> <dc:Bounds x="784" y="897" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_11d126w_di" bpmnElement="SequenceFlow_11d126w"> - <di:waypoint xsi:type="dc:Point" x="606" y="875" /> - <di:waypoint xsi:type="dc:Point" x="690" y="875" /> + <di:waypoint x="1196" y="1151" /> + <di:waypoint x="1280" y="1151" /> <bpmndi:BPMNLabel> <dc:Bounds x="603" y="854" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0w4sx88_di" bpmnElement="SequenceFlow_0w4sx88"> - <di:waypoint xsi:type="dc:Point" x="790" y="875" /> - <di:waypoint xsi:type="dc:Point" x="856" y="875" /> + <di:waypoint x="1380" y="1151" /> + <di:waypoint x="1446" y="1151" /> <bpmndi:BPMNLabel> <dc:Bounds x="778" y="854" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0e2p0xs_di" bpmnElement="ServiceTask_0e2p0xs"> - <dc:Bounds x="400" y="80" width="100" height="80" /> + <dc:Bounds x="990" y="356" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0mew9im_di" bpmnElement="SequenceFlow_0mew9im"> - <di:waypoint xsi:type="dc:Point" x="500" y="120" /> - <di:waypoint xsi:type="dc:Point" x="560" y="120" /> + <di:waypoint x="1090" y="396" /> + <di:waypoint x="1150" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="530" y="99" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0kf5sen_di" bpmnElement="SequenceFlow_0kf5sen"> - <di:waypoint xsi:type="dc:Point" x="1085" y="190" /> - <di:waypoint xsi:type="dc:Point" x="1085" y="246" /> - <di:waypoint xsi:type="dc:Point" x="1161" y="246" /> + <di:waypoint x="1675" y="466" /> + <di:waypoint x="1675" y="522" /> + <di:waypoint x="1751" y="522" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1091" y="218" width="19" height="12" /> + <dc:Bounds x="1682" y="494" width="18" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1tfizxf_di" bpmnElement="SequenceFlow_1tfizxf"> - <di:waypoint xsi:type="dc:Point" x="180" y="120" /> - <di:waypoint xsi:type="dc:Point" x="211" y="120" /> - <di:waypoint xsi:type="dc:Point" x="211" y="120" /> - <di:waypoint xsi:type="dc:Point" x="239" y="120" /> + <di:waypoint x="770" y="396" /> + <di:waypoint x="801" y="396" /> + <di:waypoint x="801" y="396" /> + <di:waypoint x="829" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="226" y="120" width="0" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ServiceTask_0m5xr0e_di" bpmnElement="Task_PreValidateWorkflow"> - <dc:Bounds x="80" y="80" width="100" height="80" /> + <dc:Bounds x="670" y="356" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="ServiceTask_0lbkcyp_di" bpmnElement="ServiceTask_0lbkcyp"> - <dc:Bounds x="735" y="80" width="100" height="80" /> + <dc:Bounds x="1325" y="356" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1hsqed1_di" bpmnElement="SequenceFlow_1hsqed1"> - <di:waypoint xsi:type="dc:Point" x="660" y="120" /> - <di:waypoint xsi:type="dc:Point" x="735" y="120" /> + <di:waypoint x="1250" y="396" /> + <di:waypoint x="1325" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="697.5" y="99" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1fftixk_di" bpmnElement="SequenceFlow_1fftixk"> - <di:waypoint xsi:type="dc:Point" x="835" y="120" /> - <di:waypoint xsi:type="dc:Point" x="911" y="120" /> + <di:waypoint x="1425" y="396" /> + <di:waypoint x="1501" y="396" /> <bpmndi:BPMNLabel> <dc:Bounds x="873" y="99" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1pnkpim_di" bpmnElement="SequenceFlow_1pnkpim"> - <di:waypoint xsi:type="dc:Point" x="886" y="-36" /> - <di:waypoint xsi:type="dc:Point" x="289" y="-36" /> - <di:waypoint xsi:type="dc:Point" x="289" y="80" /> + <di:waypoint x="1476" y="240" /> + <di:waypoint x="879" y="240" /> + <di:waypoint x="879" y="356" /> <bpmndi:BPMNLabel> <dc:Bounds x="587.5" y="-57" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="ExclusiveGateway_1dez26n_di" bpmnElement="ExclusiveGateway_1dez26n" isMarkerVisible="true"> - <dc:Bounds x="105" y="-61" width="50" height="50" /> + <dc:Bounds x="695" y="215" width="50" height="50" /> <bpmndi:BPMNLabel> - <dc:Bounds x="163" y="-48" width="61" height="24" /> + <dc:Bounds x="745" y="228" width="78" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_1lrz41x_di" bpmnElement="SequenceFlow_1lrz41x"> - <di:waypoint xsi:type="dc:Point" x="0" y="-36" /> - <di:waypoint xsi:type="dc:Point" x="105" y="-36" /> + <di:waypoint x="590" y="240" /> + <di:waypoint x="695" y="240" /> <bpmndi:BPMNLabel> <dc:Bounds x="52.5" y="-57" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_0etawv5_di" bpmnElement="SequenceFlow_0etawv5"> - <di:waypoint xsi:type="dc:Point" x="130" y="-11" /> - <di:waypoint xsi:type="dc:Point" x="130" y="80" /> + <di:waypoint x="720" y="265" /> + <di:waypoint x="720" y="356" /> <bpmndi:BPMNLabel> - <dc:Bounds x="139" y="29" width="12" height="12" /> + <dc:Bounds x="729" y="305" width="13" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_12f15tu_di" bpmnElement="EndEvent_12f15tu"> - <dc:Bounds x="112" y="-169.83592938733125" width="36" height="36" /> + <dc:Bounds x="702" y="106" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="120" y="-195" width="19" height="12" /> + <dc:Bounds x="710" y="81" width="20" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="SequenceFlow_0ilo6lo_di" bpmnElement="SequenceFlow_0ilo6lo"> - <di:waypoint xsi:type="dc:Point" x="130" y="-61" /> - <di:waypoint xsi:type="dc:Point" x="130" y="-134" /> + <di:waypoint x="720" y="215" /> + <di:waypoint x="720" y="142" /> <bpmndi:BPMNLabel> - <dc:Bounds x="136" y="-103" width="19" height="12" /> + <dc:Bounds x="727" y="173" width="18" height="14" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java index c112d200e3..9f85feac07 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java @@ -60,5 +60,8 @@ public class Constants { public static final String OPERATION_STATUS_PARAM_NAME = "operationStatus"; + public static final String EXT_VIRTUAL_LINKS = "extVirtualLinks"; + public static final String ADDITIONAL_PARAMS = "additionalParams"; + private Constants() {} } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java index 661fdb258b..877d065085 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTask.java @@ -21,12 +21,17 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.INPUT_PARAMETER; import static org.onap.so.bpmn.servicedecomposition.entities.ResourceKey.GENERIC_VNF_ID; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParameter; import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParametersProvider; import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.NullInputParameter; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.exception.BBObjectNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -42,14 +47,18 @@ public class InputParameterRetrieverTask { private static final Logger LOGGER = LoggerFactory.getLogger(InputParameterRetrieverTask.class); - private final InputParametersProvider inputParametersProvider; + private final InputParametersProvider<GenericVnf> sdncInputParametersProvider; private final ExtractPojosForBB extractPojosForBB; + private final InputParametersProvider<Map<String, Object>> userParamInputParametersProvider; + @Autowired - public InputParameterRetrieverTask(final InputParametersProvider inputParametersProvider, + public InputParameterRetrieverTask(final InputParametersProvider<GenericVnf> inputParametersProvider, + final InputParametersProvider<Map<String, Object>> userParamInputParametersProvider, final ExtractPojosForBB extractPojosForBB) { - this.inputParametersProvider = inputParametersProvider; + this.sdncInputParametersProvider = inputParametersProvider; + this.userParamInputParametersProvider = userParamInputParametersProvider; this.extractPojosForBB = extractPojosForBB; } @@ -57,17 +66,56 @@ public class InputParameterRetrieverTask { try { LOGGER.debug("Executing getInputParameters ..."); - final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID); - final InputParameter inputParameter = inputParametersProvider.getInputParameter(vnf); + final InputParameter inputParameter = new InputParameter(); + + final InputParameter userParamsInputParameter = getUserParamsInputParameter(execution); + final InputParameter sdncInputParameter = getSdncInputParameter(execution); + + inputParameter.putAdditionalParams(sdncInputParameter.getAdditionalParams()); + inputParameter.addExtVirtualLinks(sdncInputParameter.getExtVirtualLinks()); + + inputParameter.putAdditionalParams(userParamsInputParameter.getAdditionalParams()); + inputParameter.addExtVirtualLinks(userParamsInputParameter.getExtVirtualLinks()); LOGGER.debug("inputParameter: {}", inputParameter); execution.setVariable(INPUT_PARAMETER, inputParameter); LOGGER.debug("Finished executing getInputParameters ..."); } catch (final Exception exception) { - LOGGER.error("Unable to invoke create and instantiation request", exception); + LOGGER.error("Unable to get input parameters", exception); execution.setVariable(INPUT_PARAMETER, NullInputParameter.NULL_INSTANCE); } } + private InputParameter getSdncInputParameter(final BuildingBlockExecution execution) + throws BBObjectNotFoundException { + final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID); + return sdncInputParametersProvider.getInputParameter(vnf); + } + + private InputParameter getUserParamsInputParameter(final BuildingBlockExecution execution) { + final GeneralBuildingBlock generalBuildingBlock = execution.getGeneralBuildingBlock(); + + if (generalBuildingBlock != null && generalBuildingBlock.getRequestContext() != null + && generalBuildingBlock.getRequestContext().getRequestParameters() != null) { + + final List<Map<String, Object>> userParams = + generalBuildingBlock.getRequestContext().getRequestParameters().getUserParams(); + if (userParams != null) { + final Map<String, Object> params = new HashMap<>(); + + userParams.stream().forEach(obj -> { + params.putAll(obj); + }); + LOGGER.info("User params found : {}", params); + if (userParams != null && !userParams.isEmpty()) { + return userParamInputParametersProvider.getInputParameter(params); + } + } + + } + LOGGER.warn("No input parameters found in userparams ..."); + return NullInputParameter.NULL_INSTANCE; + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/AbstractInputParametersProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/AbstractInputParametersProvider.java new file mode 100644 index 0000000000..5cd84a2e11 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/AbstractInputParametersProvider.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; + +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.ADDITIONAL_PARAMS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.EXT_VIRTUAL_LINKS; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Waqas Ikram (waqas.ikram@ericsson.com) + * + */ +public abstract class AbstractInputParametersProvider<T> implements InputParametersProvider<T> { + + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractInputParametersProvider.class); + + protected Map<String, String> parseAdditionalParameters(final String additionalParamsString) { + try { + final ObjectMapper mapper = new ObjectMapper(); + final TypeReference<Map<String, String>> typeRef = new TypeReference<Map<String, String>>() {}; + return mapper.readValue(additionalParamsString, typeRef); + } catch (final Exception exception) { + LOGGER.error("Unable to parse {} ", ADDITIONAL_PARAMS, exception); + } + return Collections.emptyMap(); + + } + + protected List<ExternalVirtualLink> parseExternalVirtualLinks(final String extVirtualLinksString) { + try { + final ObjectMapper mapper = new ObjectMapper(); + final TypeReference<List<ExternalVirtualLink>> extVirtualLinksStringTypeRef = + new TypeReference<List<ExternalVirtualLink>>() {}; + return mapper.readValue(extVirtualLinksString, extVirtualLinksStringTypeRef); + } catch (final Exception exception) { + LOGGER.error("Unable to parse {} ", EXT_VIRTUAL_LINKS, exception); + } + return Collections.emptyList(); + } + + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java index d01d494c58..fde69c7e91 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameter.java @@ -24,6 +24,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; /** @@ -39,6 +41,8 @@ public class InputParameter implements Serializable { private List<ExternalVirtualLink> extVirtualLinks = new ArrayList<>(); + public InputParameter() {} + public InputParameter(final Map<String, String> additionalParams, final List<ExternalVirtualLink> extVirtualLinks) { this.additionalParams = additionalParams; this.extVirtualLinks = extVirtualLinks; @@ -65,6 +69,12 @@ public class InputParameter implements Serializable { this.additionalParams = additionalParams; } + public void putAdditionalParams(final Map<String, String> additionalParams) { + if (additionalParams != null) { + this.additionalParams.putAll(additionalParams); + } + } + /** * @param extVirtualLinks the extVirtualLinks to set */ @@ -72,9 +82,17 @@ public class InputParameter implements Serializable { this.extVirtualLinks = extVirtualLinks; } + public void addExtVirtualLinks(final List<ExternalVirtualLink> extVirtualLinks) { + if (extVirtualLinks != null) { + this.extVirtualLinks = Stream.concat(this.extVirtualLinks.stream(), extVirtualLinks.stream()).distinct() + .collect(Collectors.toList()); + } + } + @Override public String toString() { - return "InputParameter [additionalParams=" + additionalParams + ", extVirtualLinks=" + extVirtualLinks + "]"; + return this.getClass().getSimpleName() + " [additionalParams=" + additionalParams + ", extVirtualLinks=" + + extVirtualLinks + "]"; } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProvider.java index 55203fb7cc..2d11143fff 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProvider.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProvider.java @@ -19,13 +19,11 @@ */ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; -import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; - /** * @author waqas.ikram@est.tech */ -public interface InputParametersProvider { +public interface InputParametersProvider<T> { - InputParameter getInputParameter(final GenericVnf genericVnf); + InputParameter getInputParameter(final T object); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameter.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameter.java index fb877ac55d..2eed224eb7 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameter.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameter.java @@ -20,12 +20,18 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; /** * @author waqas.ikram@est.tech */ public class NullInputParameter extends InputParameter { + private static final String ERROR = + "method should not be called for null object " + NullInputParameter.class.getSimpleName(); + private static final long serialVersionUID = -7261286746726871696L; public static final NullInputParameter NULL_INSTANCE = new NullInputParameter(); @@ -34,4 +40,23 @@ public class NullInputParameter extends InputParameter { super(Collections.emptyMap(), Collections.emptyList()); } + @Override + public void setAdditionalParams(final Map<String, String> additionalParams) { + throw new UnsupportedOperationException("setAdditionalParams() " + ERROR); + } + + @Override + public void setExtVirtualLinks(final List<ExternalVirtualLink> extVirtualLinks) { + throw new UnsupportedOperationException("setExtVirtualLinks() " + ERROR); + } + + @Override + public void addExtVirtualLinks(final List<ExternalVirtualLink> extVirtualLinks) { + throw new UnsupportedOperationException("addExtVirtualLinks() " + ERROR); + } + + @Override + public void putAdditionalParams(final Map<String, String> additionalParams) { + throw new UnsupportedOperationException("putAdditionalParams() " + ERROR); + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/SdncInputParametersProvider.java index bf4f16b355..7d81f4d5c2 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImpl.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/SdncInputParametersProvider.java @@ -19,6 +19,8 @@ */ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.ADDITIONAL_PARAMS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.EXT_VIRTUAL_LINKS; import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.FORWARD_SLASH; import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.PRELOAD_VNFS_URL; import java.io.IOException; @@ -35,8 +37,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import net.minidev.json.JSONArray; @@ -48,18 +48,16 @@ import net.minidev.json.JSONArray; * @author waqas.ikram@est.tech */ @Service -public class InputParametersProviderImpl implements InputParametersProvider { +public class SdncInputParametersProvider extends AbstractInputParametersProvider<GenericVnf> { - private static final Logger LOGGER = LoggerFactory.getLogger(InputParametersProviderImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SdncInputParametersProvider.class); - private static final String EXT_VIRTUAL_LINKS = "extVirtualLinks"; - private static final String ADDITIONAL_PARAMS = "additionalParams"; private static final String VNF_PARAMETERS_PATH = "$..vnf-parameters"; private final SDNCClient sdncClient; @Autowired - public InputParametersProviderImpl(final SDNCClient sdncClient) { + public SdncInputParametersProvider(final SDNCClient sdncClient) { this.sdncClient = sdncClient; } @@ -80,8 +78,11 @@ public class InputParametersProviderImpl implements InputParametersProvider { if (vnfParametersObject instanceof JSONArray) { final JSONArray vnfParameters = (JSONArray) vnfParametersObject; final Map<String, String> vnfParametersMap = getVnfParameterMap(vnfParameters); - return new InputParameter(getAdditionalParameters(vnfParametersMap), - getExtVirtualLinks(vnfParametersMap)); + final Map<String, String> additionalParameters = getAdditionalParameters(vnfParametersMap); + final List<ExternalVirtualLink> extVirtualLinks = getExtVirtualLinks(vnfParametersMap); + final InputParameter inputParameter = new InputParameter(additionalParameters, extVirtualLinks); + LOGGER.info("InputParameter found in sdnc response : {}", inputParameter); + return inputParameter; } } } @@ -93,39 +94,24 @@ public class InputParametersProviderImpl implements InputParametersProvider { } - private List<ExternalVirtualLink> getExtVirtualLinks(final Map<String, String> vnfParametersMap) - throws JsonParseException, IOException { - try { - final String extVirtualLinksString = vnfParametersMap.get(EXT_VIRTUAL_LINKS); - - if (extVirtualLinksString != null && !extVirtualLinksString.isEmpty()) { - final ObjectMapper mapper = new ObjectMapper(); - final TypeReference<List<ExternalVirtualLink>> extVirtualLinksStringTypeRef = - new TypeReference<List<ExternalVirtualLink>>() {}; + private List<ExternalVirtualLink> getExtVirtualLinks(final Map<String, String> vnfParametersMap) { + final String extVirtualLinksString = vnfParametersMap.get(EXT_VIRTUAL_LINKS); - return mapper.readValue(extVirtualLinksString, extVirtualLinksStringTypeRef); - } - } catch (final Exception exception) { - LOGGER.error("Unable to parse {} ", EXT_VIRTUAL_LINKS, exception); + if (extVirtualLinksString != null && !extVirtualLinksString.isEmpty()) { + return parseExternalVirtualLinks(extVirtualLinksString); } return Collections.emptyList(); } - private Map<String, String> getAdditionalParameters(final Map<String, String> vnfParametersMap) - throws JsonParseException, IOException { - try { - final String additionalParamsString = vnfParametersMap.get(ADDITIONAL_PARAMS); - if (additionalParamsString != null && !additionalParamsString.isEmpty()) { - final ObjectMapper mapper = new ObjectMapper(); - final TypeReference<Map<String, String>> typeRef = new TypeReference<Map<String, String>>() {}; - return mapper.readValue(additionalParamsString, typeRef); - } - } catch (final Exception exception) { - LOGGER.error("Unable to parse {} ", ADDITIONAL_PARAMS, exception); + private Map<String, String> getAdditionalParameters(final Map<String, String> vnfParametersMap) { + final String additionalParamsString = vnfParametersMap.get(ADDITIONAL_PARAMS); + if (additionalParamsString != null && !additionalParamsString.isEmpty()) { + return parseAdditionalParameters(additionalParamsString); } return Collections.emptyMap(); } + private Map<String, String> getVnfParameterMap(final JSONArray array) { try { if (array != null) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/UserParamInputParametersProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/UserParamInputParametersProvider.java new file mode 100644 index 0000000000..ac939d04ec --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/UserParamInputParametersProvider.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; + +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.ADDITIONAL_PARAMS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.EXT_VIRTUAL_LINKS; +import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@ericsson.com) + * + */ +@Service +public class UserParamInputParametersProvider extends AbstractInputParametersProvider<Map<String, Object>> { + private static final Logger LOGGER = LoggerFactory.getLogger(UserParamInputParametersProvider.class); + + @Override + public InputParameter getInputParameter(final Map<String, Object> userParams) { + if (userParams != null) { + final InputParameter inputParameter = new InputParameter(); + final Object additionalParams = userParams.get(ADDITIONAL_PARAMS); + + if (additionalParams != null && additionalParams instanceof String) { + inputParameter.setAdditionalParams(parseAdditionalParameters(additionalParams.toString())); + } + + final Object extVirtualLinks = userParams.get(EXT_VIRTUAL_LINKS); + if (extVirtualLinks != null && extVirtualLinks instanceof String) { + inputParameter.setExtVirtualLinks(parseExternalVirtualLinks(extVirtualLinks.toString())); + } + LOGGER.info("InputParameter found in userParams : {}", inputParameter); + return inputParameter; + } + LOGGER.warn("No input parameters found ..."); + return NullInputParameter.NULL_INSTANCE; + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java index 922b721098..30e2c94ac6 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.infrastructure.audit; -import java.util.List; import org.onap.so.audit.beans.AuditInventory; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; @@ -32,10 +31,6 @@ import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.client.exception.ExceptionBuilder; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.db.request.beans.RequestProcessingData; -import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java deleted file mode 100644 index caae90bfff..0000000000 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/InputParameterRetrieverTaskTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.onap.so.bpmn.BaseTaskTest; -import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception; -import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParameter; -import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.InputParametersProvider; -import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils.NullInputParameter; -import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; -import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; -import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; -import org.onap.so.client.exception.BBObjectNotFoundException; - -/** - * @author waqas.ikram@est.tech - */ -public class InputParameterRetrieverTaskTest extends BaseTaskTest { - - private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution(); - - @Mock - private InputParametersProvider inputParametersProvider; - - @Test - public void testGGetInputParameters_inputParameterStoredInExecutionContext() throws BBObjectNotFoundException { - final InputParameterRetrieverTask objUnderTest = - new InputParameterRetrieverTask(inputParametersProvider, extractPojosForBB); - - final InputParameter inputParameter = new InputParameter(Collections.emptyMap(), Collections.emptyList()); - when(inputParametersProvider.getInputParameter(Mockito.any(GenericVnf.class))).thenReturn(inputParameter); - when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(new GenericVnf()); - objUnderTest.getInputParameters(stubbedxecution); - - final Object actual = stubbedxecution.getVariable(Constants.INPUT_PARAMETER); - assertNotNull(actual); - assertTrue(actual instanceof InputParameter); - } - - @Test - public void testGGetInputParameters_ThrowExecption_NullInputParameterStoredInExecutionContext() - throws BBObjectNotFoundException { - final InputParameterRetrieverTask objUnderTest = - new InputParameterRetrieverTask(inputParametersProvider, extractPojosForBB); - - when(inputParametersProvider.getInputParameter(Mockito.any(GenericVnf.class))) - .thenThrow(RuntimeException.class); - when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(new GenericVnf()); - objUnderTest.getInputParameters(stubbedxecution); - - final Object actual = stubbedxecution.getVariable(Constants.INPUT_PARAMETER); - assertNotNull(actual); - assertTrue(actual instanceof NullInputParameter); - } - - - private class StubbedBuildingBlockExecution implements BuildingBlockExecution { - - private final Map<String, Serializable> execution = new HashMap<>(); - - @Override - public GeneralBuildingBlock getGeneralBuildingBlock() { - return null; - } - - @SuppressWarnings("unchecked") - @Override - public <T> T getVariable(final String key) { - return (T) execution.get(key); - } - - @Override - public <T> T getRequiredVariable(final String key) throws RequiredExecutionVariableExeception { - return null; - } - - @Override - public void setVariable(final String key, final Serializable value) { - execution.put(key, value); - } - - @Override - public Map<ResourceKey, String> getLookupMap() { - return Collections.emptyMap(); - } - - @Override - public String getFlowToBeCalled() { - return null; - } - - @Override - public int getCurrentSequence() { - return 0; - } - - } -} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java index 7b63e5f811..686b4f80cc 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java @@ -20,9 +20,11 @@ package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; -import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.DUMMY_URL; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.ADDITIONAL_PARAMS; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.EXT_VIRTUAL_LINKS; +import java.util.HashMap; +import java.util.Map; import java.util.UUID; -import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmBasicHttpConfigProvider; /** * @author waqas.ikram@est.tech @@ -30,6 +32,7 @@ import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmBasicHttpConfigPro */ public class TestConstants { + public static final String EXT_VIRTUAL_LINK_ID = "ac1ed33d-8dc1-4800-8ce8-309b99c38eec"; public static final String DUMMY_GENERIC_VND_ID = "5956a99d-9736-11e8-8caf-022ac9304eeb"; public static final String DUMMY_BASIC_AUTH = "Basic 123abc"; public static final String DUMMY_URL = "http://localhost:30406/so/vnfm-adapter/v1/"; @@ -38,6 +41,19 @@ public class TestConstants { public static final String DUMMY_JOB_ID = UUID.randomUUID().toString(); public static final String JOB_STATUS_EXPECTED_URL = DUMMY_URL + "jobs/" + DUMMY_JOB_ID; + public static final String EXT_VIRTUAL_LINK_VALUE = "{\"id\":\"" + EXT_VIRTUAL_LINK_ID + "\"," + + "\"tenant\":{\"cloudOwner\":\"CloudOwner\",\"regionName\":\"RegionOne\"," + + "\"tenantId\":\"80c26954-2536-4bca-9e20-10f8a2c9c2ad\"},\"resourceId\":\"8ef8cd54-75fd-4372-a6dd-2e05ea8fbd9b\"," + + "\"extCps\":[{\"cpdId\":\"f449292f-2f0f-4656-baa3-a18d86bac80f\"," + + "\"cpConfig\":[{\"cpInstanceId\":\"07876709-b66f-465c-99a7-0f4d026197f2\"," + + "\"linkPortId\":null,\"cpProtocolData\":null}]}],\"extLinkPorts\":null}"; + + public static final String ADDITIONAL_PARAMS_VALUE = "{\"image_id\": \"DUMMYVNF\",\"instance_type\": \"m1.small\"," + + "\"ftp_address\": \"ftp://0.0.0.0:2100/\"}"; + + public static final String EXT_VIRTUAL_LINKS_VALUE = "[" + EXT_VIRTUAL_LINK_VALUE + "]"; + + public static VnfmBasicHttpConfigProvider getVnfmBasicHttpConfigProvider() { return getVnfmBasicHttpConfigProvider(DUMMY_URL, DUMMY_BASIC_AUTH); } @@ -49,6 +65,14 @@ public class TestConstants { return vnfmBasicHttpConfigProvider; } + public static Map<String, Object> getUserParamsMap(final String additionalParams, + final String extVirtualLinksValue) { + final Map<String, Object> userParams = new HashMap<>(); + userParams.put(ADDITIONAL_PARAMS, additionalParams); + userParams.put(EXT_VIRTUAL_LINKS, extVirtualLinksValue); + return userParams; + } + private TestConstants() {} } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameterRetrieverTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameterRetrieverTaskTest.java new file mode 100644 index 0000000000..9003510be7 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameterRetrieverTaskTest.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; + +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.eq; +import static org.mockito.Mockito.when; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.ADDITIONAL_PARAMS_VALUE; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.EXT_VIRTUAL_LINKS_VALUE; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.EXT_VIRTUAL_LINK_ID; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getUserParamsMap; +import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.InputParameterRetrieverTask; +import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; +import org.onap.so.client.exception.BBObjectNotFoundException; +import org.onap.so.client.sdnc.SDNCClient; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLinkCpConfig; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLinkExtCps; + +/** + * @author waqas.ikram@est.tech + */ +public class InputParameterRetrieverTaskTest extends BaseTaskTest { + + private static final String INSTANCE_TYPE_VALUE_1 = "m1.small"; + + private static final String INSTANCE_TYPE_VALUE_2 = "m1.large"; + + private static final String INSTANCE_TYPE = "instance_type"; + + private static final String RANDOM_EXT_VIRTUAL_LINK_ID = UUID.randomUUID().toString(); + + private static final String CPU_INSTANCE_ID = EXT_VIRTUAL_LINK_ID; + + private static final String FLAVOR_VALUE = "ubuntu"; + + private static final String FLAVOR = "flavor_type"; + + private final StubbedBuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution(); + + @Mock + private InputParametersProvider<GenericVnf> sdncInputParametersProvider; + + private final InputParametersProvider<Map<String, Object>> userParamsinputParametersProvider = + new UserParamInputParametersProvider(); + + @Mock + private SDNCClient mockedSdncClient; + + @Test + public void testGetInputParameters_inputParameterStoredInExecutionContext() throws BBObjectNotFoundException { + final InputParameterRetrieverTask objUnderTest = new InputParameterRetrieverTask(sdncInputParametersProvider, + userParamsinputParametersProvider, extractPojosForBB); + + + final GeneralBuildingBlock buildingBlock = + getGeneralBuildingBlock(getUserParamsMap(ADDITIONAL_PARAMS_VALUE, null)); + stubbedxecution.setGeneralBuildingBlock(buildingBlock); + + final InputParameter inputParameter = new InputParameter(Collections.emptyMap(), Collections.emptyList()); + when(sdncInputParametersProvider.getInputParameter(Mockito.any(GenericVnf.class))).thenReturn(inputParameter); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(new GenericVnf()); + objUnderTest.getInputParameters(stubbedxecution); + + final Object actual = stubbedxecution.getVariable(Constants.INPUT_PARAMETER); + assertNotNull(actual); + assertTrue(actual instanceof InputParameter); + final InputParameter actualInputParameter = (InputParameter) actual; + final Map<String, String> actualAdditionalParams = actualInputParameter.getAdditionalParams(); + assertEquals(3, actualAdditionalParams.size()); + + final String actualInstanceType = actualAdditionalParams.get(INSTANCE_TYPE); + assertEquals(INSTANCE_TYPE_VALUE_1, actualInstanceType); + + } + + @Test + public void testGetInputParameters_ThrowExecption_NullInputParameterStoredInExecutionContext() + throws BBObjectNotFoundException { + final InputParameterRetrieverTask objUnderTest = new InputParameterRetrieverTask(sdncInputParametersProvider, + userParamsinputParametersProvider, extractPojosForBB); + + when(sdncInputParametersProvider.getInputParameter(Mockito.any(GenericVnf.class))) + .thenThrow(RuntimeException.class); + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(new GenericVnf()); + objUnderTest.getInputParameters(stubbedxecution); + + final Object actual = stubbedxecution.getVariable(Constants.INPUT_PARAMETER); + assertNotNull(actual); + assertTrue(actual instanceof NullInputParameter); + } + + @Test + public void testGetInputParameters_SdncAndUserParamInputParameterStoredInExecutionContext() + throws BBObjectNotFoundException { + final InputParameterRetrieverTask objUnderTest = new InputParameterRetrieverTask(sdncInputParametersProvider, + userParamsinputParametersProvider, extractPojosForBB); + + + final GeneralBuildingBlock buildingBlock = + getGeneralBuildingBlock(getUserParamsMap(ADDITIONAL_PARAMS_VALUE, EXT_VIRTUAL_LINKS_VALUE)); + stubbedxecution.setGeneralBuildingBlock(buildingBlock); + + final InputParameter inputParameter = new InputParameter(getAdditionalParams(), getExternalVirtualLink()); + when(sdncInputParametersProvider.getInputParameter(Mockito.any(GenericVnf.class))).thenReturn(inputParameter); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(new GenericVnf()); + objUnderTest.getInputParameters(stubbedxecution); + + final Object actual = stubbedxecution.getVariable(Constants.INPUT_PARAMETER); + assertNotNull(actual); + assertTrue(actual instanceof InputParameter); + final InputParameter actualInputParameter = (InputParameter) actual; + final Map<String, String> actualAdditionalParams = actualInputParameter.getAdditionalParams(); + assertEquals(4, actualAdditionalParams.size()); + + final String actualInstanceType = actualAdditionalParams.get(INSTANCE_TYPE); + assertEquals(INSTANCE_TYPE_VALUE_1, actualInstanceType); + + assertEquals(FLAVOR_VALUE, actualAdditionalParams.get(FLAVOR)); + final List<ExternalVirtualLink> actualExtVirtualLinks = actualInputParameter.getExtVirtualLinks(); + assertEquals(2, actualExtVirtualLinks.size()); + + final Optional<ExternalVirtualLink> externalVirtualLink0 = actualExtVirtualLinks.stream() + .filter(extVirtualLink -> EXT_VIRTUAL_LINK_ID.equals(extVirtualLink.getId())).findAny(); + assertTrue(externalVirtualLink0.isPresent()); + assertEquals(EXT_VIRTUAL_LINK_ID, externalVirtualLink0.get().getId()); + + final Optional<ExternalVirtualLink> externalVirtualLink1 = actualExtVirtualLinks.stream() + .filter(extVirtualLink -> RANDOM_EXT_VIRTUAL_LINK_ID.equals(extVirtualLink.getId())).findAny(); + assertTrue(externalVirtualLink1.isPresent()); + assertEquals(RANDOM_EXT_VIRTUAL_LINK_ID, externalVirtualLink1.get().getId()); + + + } + + private List<ExternalVirtualLink> getExternalVirtualLink() { + return Arrays.asList( + new ExternalVirtualLink().id(RANDOM_EXT_VIRTUAL_LINK_ID).addExtCpsItem(new ExternalVirtualLinkExtCps() + .addCpConfigItem(new ExternalVirtualLinkCpConfig().cpInstanceId(CPU_INSTANCE_ID)))); + } + + private Map<String, String> getAdditionalParams() { + final Map<String, String> additionalParams = new HashMap<>(); + additionalParams.put(FLAVOR, FLAVOR_VALUE); + additionalParams.put(INSTANCE_TYPE, INSTANCE_TYPE_VALUE_2); + return additionalParams; + } + + + private GeneralBuildingBlock getGeneralBuildingBlock(final Map<String, Object> userParams) { + final GeneralBuildingBlock buildingBlock = new GeneralBuildingBlock(); + final RequestContext requestContext = new RequestContext(); + final RequestParameters requestParameters = new RequestParameters(); + requestParameters.setUserParams(Arrays.asList(userParams)); + requestContext.setRequestParameters(requestParameters); + buildingBlock.setRequestContext(requestContext); + return buildingBlock; + + } + + private class StubbedBuildingBlockExecution implements BuildingBlockExecution { + + private final Map<String, Serializable> execution = new HashMap<>(); + private GeneralBuildingBlock buildingBlock; + + private void setGeneralBuildingBlock(final GeneralBuildingBlock buildingBlock) { + this.buildingBlock = buildingBlock; + } + + @Override + public GeneralBuildingBlock getGeneralBuildingBlock() { + return buildingBlock; + } + + @SuppressWarnings("unchecked") + @Override + public <T> T getVariable(final String key) { + return (T) execution.get(key); + } + + @Override + public <T> T getRequiredVariable(final String key) throws RequiredExecutionVariableExeception { + return null; + } + + @Override + public void setVariable(final String key, final Serializable value) { + execution.put(key, value); + } + + @Override + public Map<ResourceKey, String> getLookupMap() { + return Collections.emptyMap(); + } + + @Override + public String getFlowToBeCalled() { + return null; + } + + @Override + public int getCurrentSequence() { + return 0; + } + + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameterTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameterTest.java new file mode 100644 index 0000000000..6dee904fde --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParameterTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.Test; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; + +/** + * @author Waqas Ikram (waqas.ikram@ericsson.com) + * + */ +public class InputParameterTest { + @Test + public void test_putAdditionalParams_addsEntryToExistingMap() { + final InputParameter objUnderTest = new InputParameter(); + objUnderTest.setAdditionalParams(getMap("name", "value")); + objUnderTest.putAdditionalParams(getMap("name1", "value1")); + + final Map<String, String> additionalParams = objUnderTest.getAdditionalParams(); + assertEquals(2, additionalParams.size()); + assertTrue(additionalParams.containsKey("name")); + assertTrue(additionalParams.containsKey("name1")); + + } + + @Test + public void test_addExtVirtualLinks_adddistinctEntriesToExistingList() { + final InputParameter objUnderTest = new InputParameter(); + String firstId = UUID.randomUUID().toString(); + String secondId = UUID.randomUUID().toString(); + objUnderTest.setExtVirtualLinks(getExternalVirtualLinkList(firstId)); + objUnderTest.addExtVirtualLinks(getExternalVirtualLinkList(secondId)); + objUnderTest.addExtVirtualLinks(getExternalVirtualLinkList(secondId)); + objUnderTest.addExtVirtualLinks(getExternalVirtualLinkList(secondId)); + + final List<ExternalVirtualLink> externalVirtualLinks = objUnderTest.getExtVirtualLinks(); + assertEquals(2, externalVirtualLinks.size()); + + } + + private List<ExternalVirtualLink> getExternalVirtualLinkList(final String id) { + final ExternalVirtualLink externalVirtualLink = new ExternalVirtualLink(); + externalVirtualLink.setId(id); + final List<ExternalVirtualLink> list = new ArrayList<>(); + list.add(externalVirtualLink); + return list; + } + + private Map<String, String> getMap(final String name, final String value) { + final Map<String, String> map = new HashMap<>(); + map.put(name, value); + return map; + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameterTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameterTest.java new file mode 100644 index 0000000000..e076df7a9b --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/NullInputParameterTest.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; + +import static org.junit.Assert.assertTrue; +import java.util.Collections; +import org.junit.Test; + +/** + * @author Waqas Ikram (waqas.ikram@ericsson.com) + * + */ +public class NullInputParameterTest { + + @Test(expected = UnsupportedOperationException.class) + public void test_addExtVirtualLinks_throwException() { + NullInputParameter.NULL_INSTANCE.addExtVirtualLinks(Collections.emptyList()); + } + + @Test(expected = UnsupportedOperationException.class) + public void test_setAdditionalParams_throwException() { + NullInputParameter.NULL_INSTANCE.setAdditionalParams(Collections.emptyMap()); + } + + @Test(expected = UnsupportedOperationException.class) + public void test_setExtVirtualLinks_throwException() { + NullInputParameter.NULL_INSTANCE.setExtVirtualLinks(Collections.emptyList()); + } + + @Test(expected = UnsupportedOperationException.class) + public void test_putAdditionalParams_throwException() { + NullInputParameter.NULL_INSTANCE.putAdditionalParams(Collections.emptyMap()); + } + + @Test + public void test_getAdditionalParams_ReturnEmptyCollection() { + assertTrue(NullInputParameter.NULL_INSTANCE.getAdditionalParams().isEmpty()); + } + + @Test + public void test_getExtVirtualLinks_ReturnEmptyCollection() { + assertTrue(NullInputParameter.NULL_INSTANCE.getExtVirtualLinks().isEmpty()); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/SdncInputParametersProviderImplTest.java index 51e86c1fea..e2e37ac6e4 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/InputParametersProviderImplTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/SdncInputParametersProviderImplTest.java @@ -48,7 +48,7 @@ import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; * @author waqas.ikram@est.tech */ @RunWith(MockitoJUnitRunner.class) -public class InputParametersProviderImplTest { +public class SdncInputParametersProviderImplTest { private static final String BASE_DIR = "src/test/resources/__files/"; @@ -89,7 +89,7 @@ public class InputParametersProviderImplTest { @Test public void testGetInputParameter_ValidResponseFromSdncInvalidData_EmptyInputParameter() throws Exception { when(mockedSdncClient.get(Mockito.eq(URL))).thenReturn(getReponseAsString(INVALID_PRE_LOAD_SDNC_RESPONSE)); - final InputParametersProvider objUnderTest = new InputParametersProviderImpl(mockedSdncClient); + final InputParametersProvider<GenericVnf> objUnderTest = new SdncInputParametersProvider(mockedSdncClient); final InputParameter actual = objUnderTest.getInputParameter(getGenericVnf()); assertNotNull(actual); assertTrue(actual.getAdditionalParams().isEmpty()); @@ -99,7 +99,7 @@ public class InputParametersProviderImplTest { @Test public void testGetInputParameter_ExceptionThrownFromSdnc_EmptyInputParameter() throws Exception { when(mockedSdncClient.get(Mockito.eq(URL))).thenThrow(RuntimeException.class); - final InputParametersProvider objUnderTest = new InputParametersProviderImpl(mockedSdncClient); + final InputParametersProvider<GenericVnf> objUnderTest = new SdncInputParametersProvider(mockedSdncClient); final InputParameter actual = objUnderTest.getInputParameter(getGenericVnf()); assertNotNull(actual); assertTrue(actual instanceof NullInputParameter); @@ -110,7 +110,7 @@ public class InputParametersProviderImplTest { @Test public void testGetInputParameter_InvalidResponseData_EmptyInputParameter() throws Exception { when(mockedSdncClient.get(Mockito.eq(URL))).thenReturn(getReponseAsString(INVALID_ADDITIONAL_AND_EXT_VM_DATA)); - final InputParametersProvider objUnderTest = new InputParametersProviderImpl(mockedSdncClient); + final InputParametersProvider<GenericVnf> objUnderTest = new SdncInputParametersProvider(mockedSdncClient); final InputParameter actual = objUnderTest.getInputParameter(getGenericVnf()); assertNotNull(actual); assertTrue(actual.getAdditionalParams().isEmpty()); @@ -120,7 +120,7 @@ public class InputParametersProviderImplTest { @Test public void testGetInputParameter_EmptyResponseData_EmptyInputParameter() throws Exception { when(mockedSdncClient.get(Mockito.eq(URL))).thenReturn(""); - final InputParametersProvider objUnderTest = new InputParametersProviderImpl(mockedSdncClient); + final InputParametersProvider<GenericVnf> objUnderTest = new SdncInputParametersProvider(mockedSdncClient); final InputParameter actual = objUnderTest.getInputParameter(getGenericVnf()); assertNotNull(actual); assertTrue(actual instanceof NullInputParameter); @@ -131,7 +131,7 @@ public class InputParametersProviderImplTest { @Test public void testGetInputParameter_InvalidVnfParamsResponseData_EmptyInputParameter() throws Exception { when(mockedSdncClient.get(Mockito.eq(URL))).thenReturn(getReponseAsString(INVALID_VNF_PARAMS)); - final InputParametersProvider objUnderTest = new InputParametersProviderImpl(mockedSdncClient); + final InputParametersProvider<GenericVnf> objUnderTest = new SdncInputParametersProvider(mockedSdncClient); final InputParameter actual = objUnderTest.getInputParameter(getGenericVnf()); assertNotNull(actual); assertTrue(actual.getAdditionalParams().isEmpty()); @@ -140,7 +140,7 @@ public class InputParametersProviderImplTest { private void assertValues(final GenericVnf genericVnf) throws MapperException, BadResponseException, IOException { when(mockedSdncClient.get(Mockito.eq(URL))).thenReturn(getReponseAsString(PRE_LOAD_SDNC_RESPONSE)); - final InputParametersProvider objUnderTest = new InputParametersProviderImpl(mockedSdncClient); + final InputParametersProvider<GenericVnf> objUnderTest = new SdncInputParametersProvider(mockedSdncClient); final InputParameter actual = objUnderTest.getInputParameter(genericVnf); assertNotNull(actual); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/UserParamInputParametersProviderTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/UserParamInputParametersProviderTest.java new file mode 100644 index 0000000000..e6d4ad056a --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/utils/UserParamInputParametersProviderTest.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.ADDITIONAL_PARAMS_VALUE; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.EXT_VIRTUAL_LINKS_VALUE; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.EXT_VIRTUAL_LINK_VALUE; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getUserParamsMap; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; + +/** + * @author Waqas Ikram (waqas.ikram@ericsson.com) + * + */ +public class UserParamInputParametersProviderTest { + + @Test + public void testGetInputParameter_ValidUserParams_NotEmptyInputParameter() throws Exception { + final InputParametersProvider<Map<String, Object>> objUnderTest = new UserParamInputParametersProvider(); + + final InputParameter actual = + objUnderTest.getInputParameter(getUserParamsMap(ADDITIONAL_PARAMS_VALUE, EXT_VIRTUAL_LINKS_VALUE)); + assertNotNull(actual); + + final Map<String, String> actualAdditionalParams = actual.getAdditionalParams(); + assertEquals(3, actualAdditionalParams.size()); + + final String actualInstanceType = actualAdditionalParams.get("instance_type"); + assertEquals("m1.small", actualInstanceType); + + final List<ExternalVirtualLink> actualExtVirtualLinks = actual.getExtVirtualLinks(); + assertEquals(1, actualExtVirtualLinks.size()); + + final ExternalVirtualLink actualExternalVirtualLink = actualExtVirtualLinks.get(0); + assertEquals("ac1ed33d-8dc1-4800-8ce8-309b99c38eec", actualExternalVirtualLink.getId()); + + } + + @Test + public void testGetInputParameter_EmptyOrNullUserParams_EmptyInputParameter() throws Exception { + final InputParametersProvider<Map<String, Object>> objUnderTest = new UserParamInputParametersProvider(); + + InputParameter actual = objUnderTest.getInputParameter(Collections.emptyMap()); + assertNotNull(actual); + assertTrue(actual.getAdditionalParams().isEmpty()); + assertTrue(actual.getExtVirtualLinks().isEmpty()); + + actual = objUnderTest.getInputParameter(null); + assertNotNull(actual); + assertTrue(actual instanceof NullInputParameter); + assertTrue(actual.getAdditionalParams().isEmpty()); + assertTrue(actual.getExtVirtualLinks().isEmpty()); + + } + + @Test + public void testGetInputParameter_InValidExtVirtualLinks_NotEmptyInputParameter() throws Exception { + final InputParametersProvider<Map<String, Object>> objUnderTest = new UserParamInputParametersProvider(); + + final InputParameter actual = + objUnderTest.getInputParameter(getUserParamsMap(ADDITIONAL_PARAMS_VALUE, EXT_VIRTUAL_LINK_VALUE)); + assertNotNull(actual); + + final Map<String, String> actualAdditionalParams = actual.getAdditionalParams(); + assertEquals(3, actualAdditionalParams.size()); + + final String actualInstanceType = actualAdditionalParams.get("instance_type"); + assertEquals("m1.small", actualInstanceType); + + assertTrue(actual.getExtVirtualLinks().isEmpty()); + + } + +} diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java index 2fd426dec2..b81ee58aa4 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/filters/RequestIdFilter.java @@ -23,6 +23,7 @@ import java.io.IOException; import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; @@ -52,15 +53,20 @@ public class RequestIdFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext context) throws IOException { String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + UriInfo uriInfo = context.getUriInfo(); + String requestURI = uriInfo.getPath(); - logger.info("Checking if requestId: {} already exists in requestDb InfraActiveRequests table", requestId); - InfraActiveRequests infraActiveRequests = infraActiveRequestsClient.getInfraActiveRequestbyRequestId(requestId); + if (!requestURI.contains("orchestrationRequests")) { + logger.info("Checking if requestId: {} already exists in requestDb InfraActiveRequests table", requestId); + InfraActiveRequests infraActiveRequests = + infraActiveRequestsClient.getInfraActiveRequestbyRequestId(requestId); - if (infraActiveRequests != null) { - logger.error( - "RequestId: {} already exists in RequestDB InfraActiveRequests table, throwing DuplicateRequestIdException", - requestId); - throw new DuplicateRequestIdException(createRequestError(requestId, "InfraActiveRequests")); + if (infraActiveRequests != null) { + logger.error( + "RequestId: {} already exists in RequestDB InfraActiveRequests table, throwing DuplicateRequestIdException", + requestId); + throw new DuplicateRequestIdException(createRequestError(requestId, "InfraActiveRequests")); + } } } diff --git a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java index 8716047603..421136d402 100644 --- a/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java +++ b/mso-api-handlers/mso-api-handler-common/src/test/java/org/onap/so/apihandler/filters/RequestIdFilterTest.java @@ -23,9 +23,13 @@ package org.onap.so.apihandler.filters; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import java.io.IOException; +import java.net.URI; import java.util.Collections; import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.UriInfo; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -53,6 +57,9 @@ public class RequestIdFilterTest { @Mock private RequestsDbClient requestsDbClient; + @Mock + private UriInfo uriInfo; + @InjectMocks @Spy private RequestIdFilter requestIdFilter; @@ -87,12 +94,35 @@ public class RequestIdFilterTest { doReturn(infraActiveRequests).when(requestsDbClient).getInfraActiveRequestbyRequestId(requestId); doReturn(error).when(requestIdFilter).createRequestError(REQUEST_ID, "InfraActiveRequests"); + doReturn("/onap/so/infra/serviceInstantiation/v7/serviceInstances").when(uriInfo).getPath(); + doReturn(uriInfo).when(mockContext).getUriInfo(); thrown.expect(DuplicateRequestIdException.class); thrown.expectMessage("HTTP 400 Bad Request"); + + requestIdFilter.filter(mockContext); } + + @Test + public void filterTestInfraSkipRequestIdLookup() throws IOException { + String requestId = REQUEST_ID; + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + + // ExpectedRecord InfraActiveRequests + InfraActiveRequests infraActiveRequests = new InfraActiveRequests(); + infraActiveRequests.setRequestId(REQUEST_ID); + + doReturn("onap/so/infra/orchestrationRequests/v7/" + REQUEST_ID).when(uriInfo).getPath(); + doReturn(uriInfo).when(mockContext).getUriInfo(); + + verify(requestsDbClient, never()).getInfraActiveRequestbyRequestId(REQUEST_ID); + + requestIdFilter.filter(mockContext); + } + + @Test public void createRequestErrorTest() throws IOException { RequestError requestError = getRequestError(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index e56eb422d8..fb7ab3a61e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -7,11 +7,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.DatatypeConverter; -import org.apache.http.HttpStatus; import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; -import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,6 +21,8 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.stereotype.Component; @@ -33,15 +34,16 @@ import org.springframework.web.client.RestTemplate; public class CamundaRequestHandler { private static Logger logger = LoggerFactory.getLogger(CamundaRequestHandler.class); - - @Autowired - private RestTemplate restTemplate; + private static final String TIMEOUT = "30000"; + private static final String RETRY_TIMEOUT = "15000"; + private static final String TIMEOUT_PROPERTY = "mso.camunda.request.timeout"; + private static final String RETRY_TIMEOUT_PROPERTY = "mso.camunda.request.timeout.retry"; @Autowired private Environment env; - public ResponseEntity<List<HistoricProcessInstanceEntity>> getCamundaProcessInstanceHistory(String requestId) { - RetryTemplate retryTemplate = setRetryTemplate(); + public ResponseEntity<List<HistoricProcessInstanceEntity>> getCamundaProcessInstanceHistory(String requestId, + boolean retry) { String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; String targetUrl = env.getProperty("mso.camundaURL") + path; HttpHeaders headers = @@ -49,86 +51,90 @@ public class CamundaRequestHandler { HttpEntity<?> requestEntity = new HttpEntity<>(headers); - return retryTemplate.execute(context -> { - if (context.getLastThrowable() != null) { - logger.error("Retrying: Last call resulted in exception: ", context.getLastThrowable()); - } - if (context.getRetryCount() == 0) { - logger.info("Querying Camunda for process-instance history for requestId: {}", requestId); - } else { - logger.info("Retry: {} of 3. Querying Camunda for process-instance history for requestId: {}", - context.getRetryCount(), requestId); - } - return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); - }); - } - - protected ResponseEntity<List<HistoricActivityInstanceEntity>> getCamundaActivityHistory(String processInstanceId, - String requestId) throws ContactCamundaException { - RetryTemplate retryTemplate = setRetryTemplate(); - String path = env.getProperty("mso.camunda.rest.activity.uri") + processInstanceId; - String targetUrl = env.getProperty("mso.camundaURL") + path; - HttpHeaders headers = - setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - try { + if (retry) { + RestTemplate restTemplate = getRestTemplate(retry); + RetryTemplate retryTemplate = getRetryTemplate(); return retryTemplate.execute(context -> { if (context.getLastThrowable() != null) { logger.error("Retrying: Last call resulted in exception: ", context.getLastThrowable()); } if (context.getRetryCount() == 0) { - logger.info( - "Querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}", - processInstanceId, requestId); + logger.info("Querying Camunda for process-instance history for requestId: {}", requestId); } else { - logger.info( - "Retry: {} of 3. Querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}", - context.getRetryCount(), processInstanceId, requestId); + logger.info("Retry: Querying Camunda for process-instance history for requestId: {}", + context.getRetryCount(), requestId); } - return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, - new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); }); - - } catch (RestClientException e) { - logger.error( - "Error querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}, exception: {}", - processInstanceId, requestId, e.getMessage()); - throw new ContactCamundaException.Builder("activity-instance", requestId, e.toString(), - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); + } else { + RestTemplate restTemplate = getRestTemplate(retry); + return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); } } - protected String getTaskName(String requestId) throws ContactCamundaException { + protected ResponseEntity<List<HistoricActivityInstanceEntity>> getCamundaActivityHistory(String processInstanceId) { + RestTemplate restTemplate = getRestTemplate(false); + String path = env.getProperty("mso.camunda.rest.activity.uri") + processInstanceId; + String targetUrl = env.getProperty("mso.camundaURL") + path; + HttpHeaders headers = + setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + + return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + } + + protected String getTaskName(String requestId) { ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; - ResponseEntity<List<HistoricActivityInstanceEntity>> activityResponse = null; - String processInstanceId = null; + + String taskInformation = null; try { - response = getCamundaProcessInstanceHistory(requestId); + response = getCamundaProcessInstanceHistory(requestId, false); } catch (RestClientException e) { - logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}", + logger.warn("Error querying Camunda for process-instance history for requestId: {}, exception: {}", requestId, e.getMessage()); - throw new ContactCamundaException.Builder("process-instance", requestId, e.toString(), - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); } + if (response != null) { + taskInformation = getTaskInformation(response, requestId); + } + return taskInformation; + } + + protected String getTaskInformation(ResponseEntity<List<HistoricProcessInstanceEntity>> response, + String requestId) { List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody(); + ResponseEntity<List<HistoricActivityInstanceEntity>> activityResponse = null; + String processInstanceId = null; + String taskInformation = null; if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) { Collections.reverse(historicProcessInstanceList); processInstanceId = historicProcessInstanceList.get(0).getId(); } else { - return "No processInstances returned for requestId: " + requestId; + logger.warn("No processInstances returned for requestId: {} to get TaskInformation", requestId); } if (processInstanceId != null) { - activityResponse = getCamundaActivityHistory(processInstanceId, requestId); + try { + activityResponse = getCamundaActivityHistory(processInstanceId); + } catch (RestClientException e) { + logger.warn( + "Error querying Camunda for activity-instance history for processInstanceId: {}, for requestId: {}, exception: {}", + processInstanceId, requestId, e.getMessage()); + } } else { - return "No processInstanceId returned for requestId: " + requestId; + logger.warn("No processInstanceId returned for requestId: {} to get TaskInformation", requestId); } - return getActivityName(activityResponse.getBody()); + if (activityResponse != null) { + taskInformation = getActivityName(activityResponse.getBody()); + } else { + logger.warn("No activity history information returned for requestId: {} to get TaskInformation", requestId); + } + return taskInformation; } protected String getActivityName(List<HistoricActivityInstanceEntity> activityInstanceList) { @@ -169,12 +175,31 @@ public class CamundaRequestHandler { return headers; } - protected RetryTemplate setRetryTemplate() { + protected RetryTemplate getRetryTemplate() { RetryTemplate retryTemplate = new RetryTemplate(); Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>(); retryableExceptions.put(ResourceAccessException.class, true); - SimpleRetryPolicy policy = new SimpleRetryPolicy(4, retryableExceptions); + SimpleRetryPolicy policy = new SimpleRetryPolicy(2, retryableExceptions); retryTemplate.setRetryPolicy(policy); return retryTemplate; } + + protected RestTemplate getRestTemplate(boolean retry) { + int timeout; + if (retry) { + timeout = Integer.parseInt(env.getProperty(RETRY_TIMEOUT_PROPERTY, RETRY_TIMEOUT)); + } else { + timeout = Integer.parseInt(env.getProperty(TIMEOUT_PROPERTY, TIMEOUT)); + } + + RestTemplate restTemplate = new RestTemplate(); + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setConnectionRequestTimeout(timeout); + factory.setReadTimeout(timeout); + factory.setConnectTimeout(timeout); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index e4ae80da97..557ae6c619 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 @@ -306,6 +306,22 @@ public class RequestHandlerUtils extends AbstractRestHandler { return requestUri; } + public void checkForDuplicateRequests(Actions action, HashMap<String, String> instanceIdMap, String requestScope, + InfraActiveRequests currentActiveReq, String instanceName) throws ApiException { + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); + + if (dup != null) { + inProgress = camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { + buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, requestScope, dup); + } + } + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; @@ -333,7 +349,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { String requestId = duplicateRecord.getRequestId(); ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; try { - response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId); + response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId, true); } catch (RestClientException e) { logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}", requestId, e.getMessage()); 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 91c62180fc..bb5013085b 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 @@ -846,19 +846,9 @@ public class ServiceInstances extends AbstractRestHandler { currentActiveReq.setNetworkType(networkType); } - InfraActiveRequests dup = null; - boolean inProgress = false; - - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } + requestHandlerUtils.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, + instanceName); - if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, - requestScope, dup); - } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); RequestReferences referencesResponse = new RequestReferences(); @@ -1006,18 +996,7 @@ public class ServiceInstances extends AbstractRestHandler { throw validateException; } - InfraActiveRequests dup = - requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); - boolean inProgress = false; - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } - - if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, - dup); - } + requestHandlerUtils.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, null); ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -1077,18 +1056,8 @@ public class ServiceInstances extends AbstractRestHandler { requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); - InfraActiveRequests dup = null; - - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } - - if (instanceIdMap != null && dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, - requestScope, dup); - } + requestHandlerUtils.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, + instanceName); ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); RequestReferences referencesResponse = new RequestReferences(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java index 830f38f98b..4dc281b3fc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java @@ -17,324 +17,39 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.onap.so.apihandlerinfra; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.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 static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import javax.ws.rs.core.MediaType; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; -import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.core.env.Environment; -import org.springframework.http.HttpEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.ResourceAccessException; -import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(MockitoJUnitRunner.class) -public class CamundaRequestHandlerTest { - - @Mock - private RestTemplate restTemplate; - @Mock - private Environment env; +public class CamundaRequestHandlerTest extends BaseTest { - @InjectMocks - @Spy + @Autowired private CamundaRequestHandler camundaRequestHandler; + @Value("${wiremock.server.port}") + private String wiremockPort; + @Rule public ExpectedException thrown = ExpectedException.none(); - private static final String REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; - private ResponseEntity<List<HistoricActivityInstanceEntity>> activityInstanceResponse = null; - private ResponseEntity<List<HistoricProcessInstanceEntity>> processInstanceResponse = null; - private List<HistoricActivityInstanceEntity> activityInstanceList = null; - private List<HistoricProcessInstanceEntity> processInstanceList = null; - - - - @Before - public void setup() throws IOException { - ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - activityInstanceList = mapper.readValue( - new String(Files.readAllBytes( - Paths.get("src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json"))), - new TypeReference<List<HistoricActivityInstanceEntity>>() {}); - processInstanceList = mapper.readValue( - new String(Files.readAllBytes( - Paths.get("src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json"))), - new TypeReference<List<HistoricProcessInstanceEntity>>() {}); - processInstanceResponse = - new ResponseEntity<List<HistoricProcessInstanceEntity>>(processInstanceList, HttpStatus.ACCEPTED); - activityInstanceResponse = - new ResponseEntity<List<HistoricActivityInstanceEntity>>(activityInstanceList, HttpStatus.ACCEPTED); - - doReturn("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_").when(env) - .getProperty("mso.camunda.rest.history.uri"); - doReturn("/sobpmnengine/history/activity-instance?processInstanceId=").when(env) - .getProperty("mso.camunda.rest.activity.uri"); - doReturn("auth").when(env).getRequiredProperty("mso.camundaAuth"); - doReturn("key").when(env).getRequiredProperty("mso.msoKey"); - doReturn("http://localhost:8089").when(env).getProperty("mso.camundaURL"); - } - - public HttpHeaders setHeaders() { - HttpHeaders headers = new HttpHeaders(); - List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); - acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); - headers.setAccept(acceptableMediaTypes); - headers.add(HttpHeaders.AUTHORIZATION, "auth"); - - return headers; - } - - @Test - public void getActivityNameTest() { - 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=="; + public void timeoutTest() { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_6718de35-b9a5-4670-b19f-a0f4ac22bfaf")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK).withFixedDelay(40000))); - assertEquals(expectedBasicAuth, basicAuth); + thrown.expect(ResourceAccessException.class); + camundaRequestHandler.getCamundaProcessInstanceHistory("6718de35-b9a5-4670-b19f-a0f4ac22bfaf", false); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerUnitTest.java new file mode 100644 index 0000000000..261b64f2e6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerUnitTest.java @@ -0,0 +1,378 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class CamundaRequestHandlerUnitTest { + + @Mock + private RestTemplate restTemplate; + + @Mock + private RestTemplate restTemplateRetry; + + @Mock + private Environment env; + + @InjectMocks + @Spy + private CamundaRequestHandler camundaRequestHandler; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private ResponseEntity<List<HistoricActivityInstanceEntity>> activityInstanceResponse = null; + private ResponseEntity<List<HistoricProcessInstanceEntity>> processInstanceResponse = null; + private List<HistoricActivityInstanceEntity> activityInstanceList = null; + private List<HistoricProcessInstanceEntity> processInstanceList = null; + + + + @Before + public void setup() throws IOException { + ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + activityInstanceList = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/ActivityInstanceHistoryResponse.json"))), + new TypeReference<List<HistoricActivityInstanceEntity>>() {}); + processInstanceList = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/ProcessInstanceHistoryResponse.json"))), + new TypeReference<List<HistoricProcessInstanceEntity>>() {}); + processInstanceResponse = + new ResponseEntity<List<HistoricProcessInstanceEntity>>(processInstanceList, HttpStatus.ACCEPTED); + activityInstanceResponse = + new ResponseEntity<List<HistoricActivityInstanceEntity>>(activityInstanceList, HttpStatus.ACCEPTED); + + doReturn("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_").when(env) + .getProperty("mso.camunda.rest.history.uri"); + doReturn("/sobpmnengine/history/activity-instance?processInstanceId=").when(env) + .getProperty("mso.camunda.rest.activity.uri"); + doReturn("auth").when(env).getRequiredProperty("mso.camundaAuth"); + doReturn("key").when(env).getRequiredProperty("mso.msoKey"); + doReturn("http://localhost:8089").when(env).getProperty("mso.camundaURL"); + + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setReadTimeout(30000); + factory.setConnectTimeout(30000); + restTemplate.setRequestFactory(factory); + doReturn(restTemplate).when(camundaRequestHandler).getRestTemplate(false); + + HttpComponentsClientHttpRequestFactory factoryRetry = new HttpComponentsClientHttpRequestFactory(); + factoryRetry.setReadTimeout(15000); + factoryRetry.setConnectTimeout(15000); + restTemplate.setRequestFactory(factoryRetry); + doReturn(restTemplateRetry).when(camundaRequestHandler).getRestTemplate(true); + } + + public HttpHeaders setHeaders() { + HttpHeaders headers = new HttpHeaders(); + List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + headers.add(HttpHeaders.AUTHORIZATION, "auth"); + + return headers; + } + + @Test + public void getActivityNameTest() throws IOException { + String expectedActivityName = "Last task executed: BB to Execute"; + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getActivityNameNullActivityNameTest() throws IOException { + String expectedActivityName = "Task name is null."; + HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity(); + List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); + activityInstanceList.add(activityInstance); + + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getActivityNameNullListTest() throws IOException { + String expectedActivityName = "No results returned on activityInstance history lookup."; + List<HistoricActivityInstanceEntity> activityInstanceList = null; + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getActivityNameEmptyListTest() throws IOException { + String expectedActivityName = "No results returned on activityInstance history lookup."; + List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); + String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); + + assertEquals(expectedActivityName, actualActivityName); + } + + @Test + public void getCamundActivityHistoryNullTest() throws IOException, ContactCamundaException { + HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); + processInstance.setId("c4c6b647-a26e-11e9-b144-0242ac14000b"); + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + processInstanceList.add(processInstance); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + doReturn(null).when(camundaRequestHandler).getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + + String actualTaskName = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actualTaskName); + } + + @Test + public void getCamundActivityHistoryErrorTest() throws IOException, ContactCamundaException { + HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); + processInstance.setId("c4c6b647-a26e-11e9-b144-0242ac14000b"); + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + processInstanceList.add(processInstance); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + doThrow(RestClientException.class).when(camundaRequestHandler) + .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + + String actualTaskName = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actualTaskName); + } + + @Test + public void getTaskName() throws IOException, ContactCamundaException { + doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID, + false); + doReturn(activityInstanceResponse).when(camundaRequestHandler) + .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + doReturn("Last task executed: BB to Execute").when(camundaRequestHandler).getActivityName(activityInstanceList); + String expectedTaskName = "Last task executed: BB to Execute"; + + String actualTaskName = camundaRequestHandler.getTaskName(REQUEST_ID); + + assertEquals(expectedTaskName, actualTaskName); + } + + @Test + public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException { + ResponseEntity<List<HistoricProcessInstanceEntity>> response = new ResponseEntity<>(null, HttpStatus.OK); + + String actual = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actual); + } + + @Test + public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException { + HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + processInstanceList.add(processInstance); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + + String actual = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actual); + } + + @Test + public void getTaskNameEmptyProcessInstanceListTest() throws IOException, ContactCamundaException { + List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = + new ResponseEntity<>(processInstanceList, HttpStatus.OK); + + String actual = camundaRequestHandler.getTaskInformation(response, REQUEST_ID); + + assertNull(actual); + } + + @Test + public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException { + doThrow(HttpClientErrorException.class).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID, + false); + + String result = camundaRequestHandler.getTaskName(REQUEST_ID); + assertNull(result); + } + + @Test + public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" + + "c4c6b647-a26e-11e9-b144-0242ac14000b"; + doReturn(activityInstanceResponse).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + ResponseEntity<List<HistoricActivityInstanceEntity>> actualResponse = + camundaRequestHandler.getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + assertEquals(activityInstanceResponse, actualResponse); + } + + @Test + public void getCamundaActivityHistoryErrorTest() { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" + + "c4c6b647-a26e-11e9-b144-0242ac14000b"; + doThrow(new ResourceAccessException("IOException")).when(restTemplate).exchange(targetUrl, HttpMethod.GET, + requestEntity, new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + thrown.expect(ResourceAccessException.class); + camundaRequestHandler.getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b"); + + verify(restTemplate, times(1)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricActivityInstanceEntity>>() {}); + } + + @Test + public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + doReturn(processInstanceResponse).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + ResponseEntity<List<HistoricProcessInstanceEntity>> actualResponse = + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, false); + assertEquals(processInstanceResponse, actualResponse); + } + + @Test + public void getCamundaProccesInstanceHistoryRetryTest() { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + doThrow(new ResourceAccessException("I/O error")).when(restTemplateRetry).exchange(targetUrl, HttpMethod.GET, + requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + thrown.expect(ResourceAccessException.class); + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, true); + + verify(restTemplateRetry, times(2)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } + + @Test + public void getCamundaProccesInstanceHistoryNoRetryTest() { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + doThrow(HttpClientErrorException.class).when(restTemplate).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + thrown.expect(HttpStatusCodeException.class); + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, false); + + verify(restTemplate, times(1)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } + + @Test + public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException { + HttpHeaders headers = setHeaders(); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + String targetUrl = + "http://localhost:8089/sobpmnengine/history/process-instance?variables=mso-request-id_eq_" + REQUEST_ID; + when(restTemplateRetry.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {})) + .thenThrow(new ResourceAccessException("I/O Exception")).thenReturn(processInstanceResponse); + doReturn(headers).when(camundaRequestHandler).setCamundaHeaders("auth", "key"); + + ResponseEntity<List<HistoricProcessInstanceEntity>> actualResponse = + camundaRequestHandler.getCamundaProcessInstanceHistory(REQUEST_ID, true); + + assertEquals(processInstanceResponse, actualResponse); + verify(restTemplateRetry, times(2)).exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } + + @Test + public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + + HttpHeaders headers = camundaRequestHandler.setCamundaHeaders(encryptedAuth, key); + List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); + + String expectedAcceptedType = "application/json"; + assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); + String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); + String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; + + assertEquals(expectedBasicAuth, basicAuth); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java index d4b0c3aad1..d0b16cffe6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -25,10 +25,12 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Timestamp; +import java.util.HashMap; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -441,4 +443,28 @@ public class RequestHandlerUtilsUnitTest { assertEquals(expected, result); } + @Test + public void checkForDuplicateRequestsTest() throws ApiException { + InfraActiveRequests currentActiveReq = new InfraActiveRequests(); + currentActiveReq.setAicCloudRegion("testRegion"); + currentActiveReq.setRequestId("792a3158-d9a3-49fd-b3ac-ab09842d6a1a"); + Action action = Action.createInstance; + String requestScope = ModelType.service.toString(); + + InfraActiveRequests duplicate = new InfraActiveRequests(); + + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + String instanceName = "instanceName"; + + doReturn(duplicate).when(requestHandler).duplicateCheck(action, instanceIdMap, instanceName, requestScope, + currentActiveReq); + doReturn(true).when(requestHandler).camundaHistoryCheck(duplicate, currentActiveReq); + doNothing().when(requestHandler).buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, + instanceName, requestScope, duplicate); + + requestHandler.checkForDuplicateRequests(action, instanceIdMap, requestScope, currentActiveReq, instanceName); + verify(requestHandler).buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, duplicate); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java index 3114f91096..8d8f4969d7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java @@ -95,7 +95,7 @@ public class CreateEcompOperationalEnvironmentTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(containing( - "{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100")) + "{\"requestId\":\"123\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"progress\":100")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); @@ -127,7 +127,7 @@ public class CreateEcompOperationalEnvironmentTest extends BaseTest { .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + uuid - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) + + "\",\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java index ebed4fa16b..6c00f8db27 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java @@ -151,7 +151,7 @@ public class CreateVnfOperationalEnvironmentTest extends BaseTest { ObjectMapper mapper = new ObjectMapper(); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + + "\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); @@ -188,7 +188,7 @@ public class CreateVnfOperationalEnvironmentTest extends BaseTest { ObjectMapper mapper = new ObjectMapper(); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + + "\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java index 16738e9799..9911bb8cb8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java @@ -64,7 +64,7 @@ public class DeactivateVnfOperationalEnvironmentTest extends BaseTest { public void init() { wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + + "\",\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); } @@ -129,7 +129,7 @@ public class DeactivateVnfOperationalEnvironmentTest extends BaseTest { .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) .withRequestBody(containing("{\"requestId\":\"" + requestId - + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) + + "\",\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java index a14699827d..e2c7aef4f4 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java @@ -25,6 +25,7 @@ import java.util.List; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @@ -47,4 +48,8 @@ public interface InfraActiveRequestsRepository List<InfraActiveRequests> findByEndTimeLessThan(Date endTime, Pageable request); List<InfraActiveRequests> findByStartTimeLessThanAndEndTime(Date startTime, Date endTime, Pageable request); + + @Query(value = "SELECT * FROM infra_active_requests WHERE request_status = 'IN_PROGRESS' AND (request_scope = 'volumeGroup' OR request_scope = 'vfModule') AND start_time < (NOW() - INTERVAL 2 MINUTE)", + nativeQuery = true) + List<InfraActiveRequests> getInProgressVolumeGroupsAndVfModules(); } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 1f5fb8f77e..84eaf38da7 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -25,6 +25,8 @@ import javax.persistence.Entity; import javax.persistence.Table; import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * InfraActiveRequests generated by hbm2java @@ -32,6 +34,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) @Entity @Table(name = "infra_active_requests") +@JsonInclude(Include.NON_NULL) public class InfraActiveRequests extends InfraRequests { private static final long serialVersionUID = -6818265918910035170L; diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java index 99c1d1ea72..132ec28e31 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java @@ -115,6 +115,8 @@ public class RequestsDbClient { private String getInfraActiveRequests = "/infraActiveRequests/v1/getInfraActiveRequests"; + private String getInProgressVolumeGroupsAndVfModules = "/infraActiveRequests/getInProgressVolumeGroupsAndVfModules"; + private static final String findBySoRequestIdAndGroupIdAndName = "/requestProcessingData/search/findOneBySoRequestIdAndGroupingIdAndName"; @@ -185,6 +187,15 @@ public class RequestsDbClient { } } + public List<InfraActiveRequests> getInProgressVolumeGroupsAndVfModules() { + HttpHeaders headers = getHttpHeaders(); + URI uri = getUri(endpoint + getInProgressVolumeGroupsAndVfModules); + HttpEntity<Map<String, List<String>>> entity = new HttpEntity<>(headers); + return restTemplate + .exchange(uri, HttpMethod.GET, entity, new ParameterizedTypeReference<List<InfraActiveRequests>>() {}) + .getBody(); + } + public InfraActiveRequests getInfraActiveRequestbyRequestId(String requestId) { try { HttpEntity<?> entity = getHttpEntity(); @@ -343,6 +354,14 @@ public class RequestsDbClient { restTemplate.put(uri, entity); } + public void patchInfraActiveRequests(InfraActiveRequests request) { + HttpHeaders headers = getHttpHeaders(); + URI uri = getUri(infraActiveRequestURI + request.getRequestId()); + HttpEntity<InfraActiveRequests> entity = new HttpEntity<>(request, headers); + restTemplate.exchange(uri, HttpMethod.PATCH, new HttpEntity<InfraActiveRequests>(request, headers), + String.class); + } + protected URI getUri(String uri) { return URI.create(uri); } diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/client/RequestDbClientTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/client/RequestDbClientTest.java index fdbc04acb4..fff6ad1013 100644 --- a/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/client/RequestDbClientTest.java +++ b/mso-api-handlers/mso-requests-db/src/test/java/org/onap/so/db/request/client/RequestDbClientTest.java @@ -10,8 +10,10 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.RequestProcessingData; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; import org.springframework.web.client.RestTemplate; @@ -32,4 +34,14 @@ public class RequestDbClientTest { requestsDbClient.updateRequestProcessingData(requestProcessingData); Mockito.verify(restTemplate, times(1)).put(eq(uri), isA(HttpEntity.class)); } + + @Test + public void updateInfraActiveRequestsTest() { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId("1"); + URI uri = URI.create("/infraActiveRequests/1"); + requestsDbClient.patchInfraActiveRequests(request); + Mockito.verify(restTemplate, times(1)).exchange(eq(uri), eq(HttpMethod.PATCH), isA(HttpEntity.class), + eq(String.class)); + } } @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.oparent</groupId> <artifactId>oparent</artifactId> - <version>2.0.0</version> + <version>2.1.0</version> <relativePath /> </parent> <groupId>org.onap.so</groupId> @@ -637,17 +637,17 @@ <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-slf4j</artifactId> - <version>1.5.1</version> + <version>1.6.1</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-base</artifactId> - <version>1.5.1</version> + <version>1.6.1</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-spring</artifactId> - <version>1.5.1</version> + <version>1.6.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> diff --git a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java index 1e5f8780d6..5a5a4143fa 100644 --- a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java +++ b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java @@ -83,7 +83,7 @@ public class SoMonitoringController { return Response.status(Status.OK).entity(processInstanceId.get()).build(); } - LOGGER.error("Unable to find process instance id for : " + requestId); + LOGGER.error("Unable to find process instance id for : {} ", requestId); return Response.status(Status.NO_CONTENT).build(); } catch (final InvalidRestRequestException | HttpResouceNotFoundException extensions) { @@ -112,7 +112,7 @@ public class SoMonitoringController { return Response.status(Status.OK).entity(processInstanceDetail.get()).build(); } - LOGGER.error("Unable to find process instance id for : " + processInstanceId); + LOGGER.error("Unable to find process instance id for : {}", processInstanceId); return Response.status(Status.NO_CONTENT).build(); } catch (final InvalidRestRequestException | HttpResouceNotFoundException extensions) { @@ -141,7 +141,7 @@ public class SoMonitoringController { final ProcessDefinitionDetail definitionDetail = response.get(); return Response.status(Status.OK).entity(definitionDetail).build(); } - LOGGER.error("Unable to find process definition xml for processDefinitionId: " + processDefinitionId); + LOGGER.error("Unable to find process definition xml for processDefinitionId: {}", processDefinitionId); return Response.status(Status.NO_CONTENT).build(); } catch (final InvalidRestRequestException | HttpResouceNotFoundException extensions) { @@ -215,7 +215,7 @@ public class SoMonitoringController { try { final List<SoInfraRequest> requests = databaseServiceProvider.getSoInfraRequest(filters, startTime, endTime, maxResult); - LOGGER.info("result size: " + requests.size()); + LOGGER.info("result size: {}", requests.size()); return Response.status(Status.OK).entity(requests).build(); } catch (final InvalidRestRequestException | HttpResouceNotFoundException extensions) { |