diff options
78 files changed, 2102 insertions, 593 deletions
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java index 79aad1ad1a..b43447f5c4 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java @@ -25,6 +25,7 @@ import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.onap.so.adapters.catalogdb.rest.CatalogDbAdapterRest; import org.onap.so.adapters.catalogdb.rest.ServiceRestImpl; +import org.onap.so.adapters.catalogdb.rest.VnfRestImpl; import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; import org.springframework.context.annotation.Configuration; import io.swagger.jaxrs.config.BeanConfig; @@ -42,6 +43,7 @@ public class JerseyConfiguration extends ResourceConfig { register(SwaggerSerializers.class); register(JaxRsFilterLogging.class); register(ServiceRestImpl.class); + register(VnfRestImpl.class); BeanConfig beanConfig = new BeanConfig(); beanConfig.setVersion("1.0.2"); beanConfig.setSchemes(new String[] {"https"}); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java new file mode 100644 index 0000000000..f8a7ba6da4 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java @@ -0,0 +1,14 @@ +package org.onap.so.adapters.catalogdb.rest; + +public class CatalogEntityNotFoundException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -300157844846680791L; + + public CatalogEntityNotFoundException(String errorMessage) { + super(errorMessage); + } + +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java new file mode 100644 index 0000000000..c42eaabea7 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.catalogdb.rest; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Provider +public class CatalogEntityNotFoundExceptionMapper implements ExceptionMapper<CatalogEntityNotFoundException> { + + private static final Logger logger = LoggerFactory.getLogger(CatalogEntityNotFoundExceptionMapper.class); + + @Override + public Response toResponse(CatalogEntityNotFoundException e) { + return Response.status(Response.Status.NOT_FOUND).entity(e).build(); + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java index dd18767762..e74663dbba 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java @@ -22,9 +22,11 @@ package org.onap.so.adapters.catalogdb.rest; import java.util.ArrayList; import java.util.List; +import org.onap.so.db.catalog.beans.CvnfcCustomization; import org.onap.so.db.catalog.beans.HeatEnvironment; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.rest.catalog.beans.Cvnfc; import org.onap.so.rest.catalog.beans.Service; import org.onap.so.rest.catalog.beans.VfModule; import org.onap.so.rest.catalog.beans.Vnf; @@ -39,16 +41,23 @@ public class ServiceMapper { public Service mapService(org.onap.so.db.catalog.beans.Service service, int depth) { Service restService = new Service(); - restService.setCategory(service.getCategory()); + if (service.getCategory() != null) { + restService.setCategory(service.getCategory()); + } restService.setCreated(service.getCreated()); restService.setDescription(service.getDescription()); - restService.setDistrobutionStatus(service.getDistrobutionStatus()); + + if (service.getDistrobutionStatus() != null) { + restService.setDistrobutionStatus(service.getDistrobutionStatus()); + } restService.setEnvironmentContext(service.getEnvironmentContext()); restService.setModelInvariantId(service.getModelInvariantUUID()); restService.setModelName(service.getModelName()); restService.setModelVersionId(service.getModelUUID()); restService.setModelVersion(service.getModelVersion()); - restService.setServiceRole(service.getServiceRole()); + if (service.getServiceRole() != null) { + restService.setServiceRole(service.getServiceRole()); + } restService.setServiceType(service.getServiceType()); restService.setWorkloadContext(service.getWorkloadContext()); if (depth > 0) @@ -63,7 +72,7 @@ public class ServiceMapper { return vnfs; } - private Vnf mapVnf(org.onap.so.db.catalog.beans.VnfResourceCustomization vnfResourceCustomization, int depth) { + protected Vnf mapVnf(org.onap.so.db.catalog.beans.VnfResourceCustomization vnfResourceCustomization, int depth) { Vnf vnf = new Vnf(); vnf.setAvailabilityZoneMaxCount(vnfResourceCustomization.getAvailabilityZoneMaxCount()); vnf.setCategory(vnfResourceCustomization.getVnfResources().getCategory()); @@ -81,9 +90,12 @@ public class ServiceMapper { vnf.setNfFunction(vnfResourceCustomization.getNfFunction()); vnf.setNfNamingCode(vnfResourceCustomization.getNfNamingCode()); vnf.setNfRole(vnfResourceCustomization.getNfRole()); + vnf.setNfType(vnfResourceCustomization.getNfType()); + vnf.setNfDataValid(vnfResourceCustomization.getNfDataValid()); vnf.setOrchestrationMode(vnfResourceCustomization.getVnfResources().getOrchestrationMode()); vnf.setSubCategory(vnfResourceCustomization.getVnfResources().getSubCategory()); vnf.setToscaNodeType(vnfResourceCustomization.getVnfResources().getToscaNodeType()); + if (depth > 1) { vnf.setVfModule(mapVfModules(vnfResourceCustomization, depth)); } @@ -93,11 +105,11 @@ public class ServiceMapper { private List<VfModule> mapVfModules(VnfResourceCustomization vnfResourceCustomization, int depth) { List<VfModule> vfModules = new ArrayList<>(); vnfResourceCustomization.getVfModuleCustomizations().parallelStream() - .forEach(vfModule -> vfModules.add(mapVfModule(vfModule))); + .forEach(vfModule -> vfModules.add(mapVfModule(vfModule, depth))); return vfModules; } - private VfModule mapVfModule(VfModuleCustomization vfModuleCust) { + private VfModule mapVfModule(VfModuleCustomization vfModuleCust, int depth) { VfModule vfModule = new VfModule(); vfModule.setAvailabilityZoneCount(vfModuleCust.getAvailabilityZoneCount()); vfModule.setCreated(vfModuleCust.getCreated()); @@ -113,9 +125,34 @@ public class ServiceMapper { vfModule.setModelName(vfModuleCust.getVfModule().getModelName()); vfModule.setModelVersionId(vfModuleCust.getVfModule().getModelUUID()); vfModule.setModelVersion(vfModuleCust.getVfModule().getModelVersion()); + if (depth > 3) { + vfModule.setVnfc(mapCvnfcs(vfModuleCust)); + } return vfModule; } + private List<Cvnfc> mapCvnfcs(VfModuleCustomization vfModuleCustomization) { + List<Cvnfc> cvnfcs = new ArrayList<>(); + vfModuleCustomization.getCvnfcCustomization().parallelStream() + .forEach(cvnfcCust -> cvnfcs.add(mapCvnfcCus(cvnfcCust))); + return cvnfcs; + } + + private Cvnfc mapCvnfcCus(CvnfcCustomization cvnfcCust) { + Cvnfc cvnfc = new Cvnfc(); + cvnfc.setCreated(cvnfcCust.getCreated()); + cvnfc.setDescription(cvnfcCust.getDescription()); + cvnfc.setModelCustomizationId(cvnfcCust.getModelCustomizationUUID()); + cvnfc.setModelInstanceName(cvnfcCust.getModelInstanceName()); + cvnfc.setModelInvariantId(cvnfcCust.getModelInvariantUUID()); + cvnfc.setModelName(cvnfcCust.getModelName()); + cvnfc.setModelVersion(cvnfcCust.getModelVersion()); + cvnfc.setModelVersionId(cvnfcCust.getModelUUID()); + cvnfc.setNfcFunction(cvnfcCust.getNfcFunction()); + cvnfc.setNfcNamingCode(cvnfcCust.getNfcNamingCode()); + return cvnfc; + } + private boolean getIsVolumeGroup(VfModuleCustomization vfModuleCust) { boolean isVolumeGroup = false; HeatEnvironment envt = vfModuleCust.getVolumeHeatEnv(); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java index 520de4d38c..6f556edfa1 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java @@ -38,7 +38,7 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -@Api(value = "/v1/services", tags = "model") +@Api(value = "/v1", tags = "model") @Path("/v1/services") @Component public class ServiceRestImpl { @@ -49,18 +49,21 @@ public class ServiceRestImpl { @Autowired private ServiceMapper serviceMapper; + @GET @Path("/{modelUUID}") @Produces({MediaType.APPLICATION_JSON}) @Transactional(readOnly = true) public Service findService(@PathParam("modelUUID") String modelUUID, @QueryParam("depth") int depth) { org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(modelUUID); + if (service == null) { + new CatalogEntityNotFoundException("Unable to find Service " + modelUUID); + } return serviceMapper.mapService(service, depth); } @GET - @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List", - notes = "If no query parameters are sent an empty list will be returned") + @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List") @Produces({MediaType.APPLICATION_JSON}) @Transactional(readOnly = true) public List<Service> queryServices( @@ -74,6 +77,8 @@ public class ServiceRestImpl { serviceFromDB = serviceRepo.findByModelNameAndDistrobutionStatus(modelName, distributionStatus); } else if (!Strings.isNullOrEmpty(modelName)) { serviceFromDB = serviceRepo.findByModelName(modelName); + } else { + serviceFromDB = serviceRepo.findAll(); } serviceFromDB.stream().forEach(serviceDB -> services.add(serviceMapper.mapService(serviceDB, depth))); return services; diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java new file mode 100644 index 0000000000..52a8ccb5a7 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java @@ -0,0 +1,37 @@ +package org.onap.so.adapters.catalogdb.rest; + +import org.onap.so.db.catalog.beans.VnfResource; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.rest.catalog.beans.Vnf; +import org.springframework.stereotype.Component; +import com.google.common.base.Strings; + +@Component +public class VnfMapper { + + public VnfResourceCustomization mapVnf(VnfResourceCustomization vnfCust, Vnf vnf) { + + vnfCust.setAvailabilityZoneMaxCount(vnf.getAvailabilityZoneMaxCount()); + vnfCust.setMaxInstances(vnf.getMaxInstances()); + vnfCust.setMinInstances(vnf.getMinInstances()); + vnfCust.setModelCustomizationUUID(vnf.getModelCustomizationId()); + vnfCust.setModelInstanceName(vnf.getModelInstanceName()); + vnfCust.setMultiStageDesign(vnf.getMultiStageDesign()); + vnfCust.setNfDataValid(vnf.getNfDataValid()); + vnfCust.setNfFunction(Strings.nullToEmpty(vnf.getNfFunction())); + vnfCust.setNfNamingCode(Strings.nullToEmpty(vnf.getNfNamingCode())); + vnfCust.setNfRole(Strings.nullToEmpty(vnf.getNfRole())); + vnfCust.setNfType(Strings.nullToEmpty(vnf.getNfType())); + + VnfResource vnfRes = vnfCust.getVnfResources(); + vnfRes.setOrchestrationMode(Strings.nullToEmpty(vnfRes.getOrchestrationMode())); + vnfRes.setSubCategory(Strings.nullToEmpty(vnfRes.getSubCategory())); + vnfRes.setToscaNodeType(Strings.nullToEmpty(vnfRes.getToscaNodeType())); + vnfRes.setModelInvariantUUID(vnfRes.getModelInvariantId()); + vnfRes.setModelName(vnfRes.getModelName()); + vnfRes.setModelUUID(vnfRes.getModelUUID()); + vnfRes.setModelVersion(vnfRes.getModelVersion()); + return vnfCust; + } + +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java new file mode 100644 index 0000000000..4353526872 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java @@ -0,0 +1,107 @@ +/*- + * ============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.adapters.catalogdb.rest; + +import java.util.List; +import java.util.stream.Collectors; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.catalog.data.repository.VnfCustomizationRepository; +import org.onap.so.rest.catalog.beans.Vnf; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Api(value = "/v1/services/{modelUUID}/vnfs", tags = "model") +@Path("/v1/services/{modelUUID}/vnfs") +@Component +public class VnfRestImpl { + + @Autowired + private ServiceRepository serviceRepo; + + @Autowired + private ServiceMapper serviceMapper; + + @Autowired + private VnfMapper vnfMapper; + + @Autowired + private VnfCustomizationRepository vnfCustRepo; + + @GET + @ApiOperation(value = "Find a VNF model contained within a service", response = Vnf.class) + @Path("/{modelCustomizationUUID}") + @Produces({MediaType.APPLICATION_JSON}) + @Transactional(readOnly = true) + public Vnf findService(@PathParam("modelUUID") String serviceModelUUID, + @PathParam("modelCustomizationUUID") String modelCustomizationUUID, @QueryParam("depth") int depth) { + org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(serviceModelUUID); + if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) { + throw new WebApplicationException("Vnf Not Found", 404); + } + List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream() + .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID)) + .collect(Collectors.toList()); + if (vnfCustom.isEmpty() || vnfCustom == null) { + return null; + } else if (vnfCustom.size() > 1) { + throw new RuntimeException( + "More than one Vnf model returned with model Customization UUID: " + modelCustomizationUUID); + } + return serviceMapper.mapVnf(vnfCustom.get(0), depth); + } + + @PUT + @ApiOperation(value = "Update a VNF model contained within a service", response = Vnf.class) + @Path("/{modelCustomizationUUID}") + @Produces({MediaType.APPLICATION_JSON}) + @Transactional + public Response findService(@PathParam("modelUUID") String serviceModelUUID, + @PathParam("modelCustomizationUUID") String modelCustomizationUUID, Vnf vnf) { + org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(serviceModelUUID); + List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream() + .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID)) + .collect(Collectors.toList()); + if (vnfCustom.isEmpty() || vnfCustom == null) { + throw new RuntimeException("No Vnf Found"); + } else if (vnfCustom.size() > 1) { + throw new RuntimeException( + "More than one Vnf model returned with model Customization UUID: " + modelCustomizationUUID); + } + VnfResourceCustomization vnfCust = vnfMapper.mapVnf(vnfCustom.get(0), vnf); + vnfCustRepo.save(vnfCust); + return Response.ok().build(); + } + +} + diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql new file mode 100644 index 0000000000..93dde1341e --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql @@ -0,0 +1,5 @@ +USE catalogdb; + +ALTER TABLE vnf_resource_customization +ADD IF NOT EXISTS NF_DATA_VALID tinyint(1) DEFAULT 0; + diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java index 8decd77656..d46fd9c7ba 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java @@ -67,6 +67,7 @@ public class ServiceMapperTest { testService.setModelVersion("modelVersion"); testService.setServiceType("serviceType"); testService.setServiceRole("serviceRole"); + testService.getVnfCustomizations().add(getTestVnfCustomization()); return testService; } diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java index a955a2c3ce..f82c7acd38 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -22,15 +22,14 @@ package org.onap.so.db.catalog.client; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.UUID; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.so.adapters.catalogdb.CatalogDBApplication; import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest; import org.onap.so.db.catalog.beans.AuthenticationType; import org.onap.so.db.catalog.beans.CloudIdentity; @@ -56,10 +55,7 @@ import org.onap.so.db.catalog.beans.macro.NorthBoundRequest; import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @@ -74,6 +70,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Autowired CatalogDbClientPortChanger client; + + @Before public void initialize() { client.wiremockPort = String.valueOf(port); @@ -88,7 +86,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetRainyDayHandler_Regex() { RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*", "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found.", "*"); - Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); + assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } @Test @@ -97,105 +95,105 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { "*", "*", "*", "resources.lba_0_dmz_vmi_0: Unknown id: Error: oper 1 url /fqname-to-id body {\"fq_name\": [\"zrdm6bvota05-dmz_sec_group\"], \"type\": \"security-group\"} response Name ['zrdm6bvota05-dmz_sec_group'] not found", "*"); - Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); + assertEquals("Rollback", rainyDayHandlerStatus.getPolicy()); } @Test public void testGetCloudSiteHappyPath() throws Exception { CloudSite cloudSite = client.getCloudSite(MTN13); - Assert.assertNotNull(cloudSite); - Assert.assertNotNull(cloudSite.getIdentityService()); - Assert.assertEquals("MDT13", cloudSite.getClli()); - Assert.assertEquals("mtn13", cloudSite.getRegionId()); - Assert.assertEquals("MTN13", cloudSite.getIdentityServiceId()); + assertNotNull(cloudSite); + assertNotNull(cloudSite.getIdentityService()); + assertEquals("MDT13", cloudSite.getClli()); + assertEquals("mtn13", cloudSite.getRegionId()); + assertEquals("MTN13", cloudSite.getIdentityServiceId()); } @Test public void testGetCloudSiteNotFound() throws Exception { CloudSite cloudSite = client.getCloudSite(UUID.randomUUID().toString()); - Assert.assertNull(cloudSite); + assertNull(cloudSite); } @Test public void testGetCloudifyManagerHappyPath() throws Exception { CloudifyManager cloudifyManager = client.getCloudifyManager("mtn13"); - Assert.assertNotNull(cloudifyManager); - Assert.assertEquals("http://localhost:28090/v2.0", cloudifyManager.getCloudifyUrl()); + assertNotNull(cloudifyManager); + assertEquals("http://localhost:28090/v2.0", cloudifyManager.getCloudifyUrl()); } @Test public void testGetCloudifyManagerNotFound() throws Exception { CloudifyManager cloudifyManager = client.getCloudifyManager(UUID.randomUUID().toString()); - Assert.assertNull(cloudifyManager); + assertNull(cloudifyManager); } @Test public void testGetCloudSiteByClliAndAicVersionHappyPath() throws Exception { CloudSite cloudSite = client.getCloudSiteByClliAndAicVersion("MDT13", "2.5"); - Assert.assertNotNull(cloudSite); + assertNotNull(cloudSite); } @Test public void testGetCloudSiteByClliAndAicVersionNotFound() throws Exception { CloudSite cloudSite = client.getCloudSiteByClliAndAicVersion("MDT13", "232496239746328"); - Assert.assertNull(cloudSite); + assertNull(cloudSite); } @Test public void testGetServiceByID() throws Exception { Service serviceByID = client.getServiceByID("5df8b6de-2083-11e7-93ae-92361f002671"); - Assert.assertNotNull(serviceByID); - Assert.assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName()); - Assert.assertEquals("NA", serviceByID.getServiceType()); - Assert.assertEquals("NA", serviceByID.getServiceRole()); + assertNotNull(serviceByID); + assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName()); + assertEquals("NA", serviceByID.getServiceType()); + assertEquals("NA", serviceByID.getServiceRole()); } @Test public void testGetServiceByIDNotFound() throws Exception { Service serviceByID = client.getServiceByID(UUID.randomUUID().toString()); - Assert.assertNull(serviceByID); + assertNull(serviceByID); } @Test public void testGetVfModuleByModelUUID() throws Exception { VfModule vfModule = client.getVfModuleByModelUUID("20c4431c-246d-11e7-93ae-92361f002671"); - Assert.assertNotNull(vfModule); - Assert.assertNotNull(vfModule.getVfModuleCustomization()); - Assert.assertEquals("78ca26d0-246d-11e7-93ae-92361f002671", vfModule.getModelInvariantUUID()); - Assert.assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); + assertNotNull(vfModule); + assertNotNull(vfModule.getVfModuleCustomization()); + assertEquals("78ca26d0-246d-11e7-93ae-92361f002671", vfModule.getModelInvariantUUID()); + assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); } @Test public void testGetVfModuleByModelUUIDNotFound() throws Exception { VfModule vfModule = client.getVfModuleByModelUUID(UUID.randomUUID().toString()); - Assert.assertNull(vfModule); + assertNull(vfModule); } @Test public void testGetVnfResourceByModelUUID() throws Exception { VnfResource vnfResource = client.getVnfResourceByModelUUID("ff2ae348-214a-11e7-93ae-92361f002671"); - Assert.assertNotNull(vnfResource); - Assert.assertEquals("vSAMP10a", vnfResource.getModelName()); + assertNotNull(vnfResource); + assertEquals("vSAMP10a", vnfResource.getModelName()); } @Test public void testGetVnfResourceByModelUUIDNotFound() throws Exception { VnfResource vnfResource = client.getVnfResourceByModelUUID(UUID.randomUUID().toString()); - Assert.assertNull(vnfResource); + assertNull(vnfResource); } @Test public void testGetVnfResourceCustomizationByModelCustomizationUUID() { VnfResourceCustomization vnfResourceCustomization = client.getVnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002671"); - Assert.assertNotNull(vnfResourceCustomization); - Assert.assertEquals("vSAMP", vnfResourceCustomization.getNfRole()); - Assert.assertNotNull(vnfResourceCustomization.getModelCustomizationUUID()); - Assert.assertNotNull(vnfResourceCustomization.getVnfResources()); - Assert.assertNotNull(vnfResourceCustomization.getVfModuleCustomizations()); - Assert.assertEquals("vSAMP10a", vnfResourceCustomization.getVnfResources().getModelName()); + assertNotNull(vnfResourceCustomization); + assertEquals("vSAMP", vnfResourceCustomization.getNfRole()); + assertNotNull(vnfResourceCustomization.getModelCustomizationUUID()); + assertNotNull(vnfResourceCustomization.getVnfResources()); + assertNotNull(vnfResourceCustomization.getVfModuleCustomizations()); + assertEquals("vSAMP10a", vnfResourceCustomization.getVnfResources().getModelName()); assertTrue("skip post instantiation configuration", vnfResourceCustomization.isSkipPostInstConf()); } @@ -203,15 +201,15 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetVnfResourceCustomizationByModelCustomizationUUINotFound() { VnfResourceCustomization vnfResourceCustomization = client.getVnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(vnfResourceCustomization); + assertNull(vnfResourceCustomization); } @Test public void testGetInstanceGroupByModelUUID() { InstanceGroup instanceGroup = client.getInstanceGroupByModelUUID("0c8692ef-b9c0-435d-a738-edf31e71f38b"); - Assert.assertNotNull(instanceGroup); - Assert.assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName()); - Assert.assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806", + assertNotNull(instanceGroup); + assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName()); + assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806", instanceGroup.getToscaNodeType().toString()); } @@ -219,33 +217,33 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void testGetVfModuleCustomizationByModelCuztomizationUUID() { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCuztomizationUUID("cb82ffd8-252a-11e7-93ae-92361f002671"); - Assert.assertNotNull(vfModuleCustomization); - Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); - Assert.assertEquals("base", vfModuleCustomization.getLabel()); + assertNotNull(vfModuleCustomization); + assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); + assertEquals("base", vfModuleCustomization.getLabel()); } @Test public void testGetVfModuleCustomizationByModelCuztomizationUUIDNotFound() { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCuztomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(vfModuleCustomization); + assertNull(vfModuleCustomization); } @Test public void testGetNetworkResourceCustomizationByModelCustomizationUUID() { NetworkResourceCustomization networkResourceCustomization = client.getNetworkResourceCustomizationByModelCustomizationUUID("3bdbb104-476c-483e-9f8b-c095b3d308ac"); - Assert.assertNotNull(networkResourceCustomization); - Assert.assertNotNull(networkResourceCustomization.getModelCustomizationUUID()); - Assert.assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName()); - Assert.assertNotNull(networkResourceCustomization.getNetworkResource()); + assertNotNull(networkResourceCustomization); + assertNotNull(networkResourceCustomization.getModelCustomizationUUID()); + assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName()); + assertNotNull(networkResourceCustomization.getNetworkResource()); } @Test public void testGetNetworkResourceCustomizationByModelCustomizationUUIDNotFound() { NetworkResourceCustomization networkResourceCustomization = client.getNetworkResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(networkResourceCustomization); + assertNull(networkResourceCustomization); } @Test @@ -253,10 +251,10 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID( "cb82ffd8-252a-11e7-93ae-92361f002672", "20c4431c-246d-11e7-93ae-92361f002672"); - Assert.assertNotNull(vfModuleCustomization); - Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); - Assert.assertNotNull(vfModuleCustomization.getVfModule()); - Assert.assertEquals("base", vfModuleCustomization.getLabel()); + assertNotNull(vfModuleCustomization); + assertNotNull(vfModuleCustomization.getModelCustomizationUUID()); + assertNotNull(vfModuleCustomization.getVfModule()); + assertEquals("base", vfModuleCustomization.getLabel()); } @Test @@ -264,44 +262,43 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VfModuleCustomization vfModuleCustomization = client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID( "cb82ffd8-252a-11e7-93ae-92361f002672", UUID.randomUUID().toString()); - Assert.assertNull(vfModuleCustomization); + assertNull(vfModuleCustomization); } @Test public void testGetFirstByServiceModelUUIDAndAction() { ServiceRecipe serviceRecipe = client.getFirstByServiceModelUUIDAndAction("4694a55f-58b3-4f17-92a5-796d6f5ffd0d", "createInstance"); - Assert.assertNotNull(serviceRecipe); - Assert.assertNotNull(serviceRecipe.getServiceModelUUID()); - Assert.assertNotNull(serviceRecipe.getAction()); - Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", - serviceRecipe.getOrchestrationUri()); - Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); + assertNotNull(serviceRecipe); + assertNotNull(serviceRecipe.getServiceModelUUID()); + assertNotNull(serviceRecipe.getAction()); + assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", serviceRecipe.getOrchestrationUri()); + assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); } @Test public void testGetFirstByServiceModelUUIDAndActionNotFound() { ServiceRecipe serviceRecipe = client.getFirstByServiceModelUUIDAndAction("5df8b6de-2083-11e7-93ae-92361f002671", UUID.randomUUID().toString()); - Assert.assertNull(serviceRecipe); + assertNull(serviceRecipe); } @Test public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersion() { VnfResource vnfResource = client .getFirstVnfResourceByModelInvariantUUIDAndModelVersion("2fff5b20-214b-11e7-93ae-92361f002671", "2.0"); - Assert.assertNotNull(vnfResource); - Assert.assertNotNull(vnfResource.getModelInvariantId()); - Assert.assertNotNull(vnfResource.getModelVersion()); - Assert.assertNotNull(vnfResource.getHeatTemplates()); - Assert.assertEquals("vSAMP10a", vnfResource.getModelName()); + assertNotNull(vnfResource); + assertNotNull(vnfResource.getModelInvariantId()); + assertNotNull(vnfResource.getModelVersion()); + assertNotNull(vnfResource.getHeatTemplates()); + assertEquals("vSAMP10a", vnfResource.getModelName()); } @Test public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersionNotFound() { VnfResource vnfResource = client.getFirstVnfResourceByModelInvariantUUIDAndModelVersion( "2fff5b20-214b-11e7-93ae-92361f002671", UUID.randomUUID().toString()); - Assert.assertNull(vnfResource); + assertNull(vnfResource); } @Test @@ -310,29 +307,28 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { vnfr.setModelUUID("ff2ae348-214a-11e7-93ae-92361f002671"); VnfResourceCustomization firstVnfResourceCustomizationByModelInstanceNameAndVnfResources = client.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources("vSAMP10a 1", vnfr); - Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources); - Assert.assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole()); - Assert.assertEquals("vSAMP10a 1", + assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources); + assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole()); + assertEquals("vSAMP10a 1", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getModelInstanceName()); - Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources()); - Assert.assertNotNull( - firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations()); + assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources()); + assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations()); } @Test public void testGetFirstVnfRecipeByNfRoleAndAction() { VnfRecipe vnfRecipe = client.getFirstVnfRecipeByNfRoleAndAction("GR-API-DEFAULT", "createInstance"); - Assert.assertNotNull(vnfRecipe); - Assert.assertNotNull(vnfRecipe.getNfRole()); - Assert.assertNotNull(vnfRecipe.getAction()); - Assert.assertEquals("Gr api recipe to create vnf", vnfRecipe.getDescription()); - Assert.assertEquals("/mso/async/services/WorkflowActionBB", vnfRecipe.getOrchestrationUri()); + assertNotNull(vnfRecipe); + assertNotNull(vnfRecipe.getNfRole()); + assertNotNull(vnfRecipe.getAction()); + assertEquals("Gr api recipe to create vnf", vnfRecipe.getDescription()); + assertEquals("/mso/async/services/WorkflowActionBB", vnfRecipe.getOrchestrationUri()); } @Test public void testGetFirstVnfRecipeByNfRoleAndActionNotFound() { VnfRecipe vnfRecipe = client.getFirstVnfRecipeByNfRoleAndAction(UUID.randomUUID().toString(), "createInstance"); - Assert.assertNull(vnfRecipe); + assertNull(vnfRecipe); } @Test @@ -340,12 +336,12 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VnfComponentsRecipe vnfComponentsRecipe = client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( "20c4431c-246d-11e7-93ae-92361f002671", "volumeGroup", "createInstance"); - Assert.assertNotNull(vnfComponentsRecipe); - Assert.assertNotNull(vnfComponentsRecipe.getAction()); - Assert.assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID()); - Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType()); - Assert.assertEquals("Gr api recipe to create volume-group", vnfComponentsRecipe.getDescription()); - Assert.assertEquals("/mso/async/services/WorkflowActionBB", vnfComponentsRecipe.getOrchestrationUri()); + assertNotNull(vnfComponentsRecipe); + assertNotNull(vnfComponentsRecipe.getAction()); + assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID()); + assertNotNull(vnfComponentsRecipe.getVnfComponentType()); + assertEquals("Gr api recipe to create volume-group", vnfComponentsRecipe.getDescription()); + assertEquals("/mso/async/services/WorkflowActionBB", vnfComponentsRecipe.getOrchestrationUri()); } @@ -355,80 +351,79 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { VnfComponentsRecipe vnfComponentsRecipe = client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( UUID.randomUUID().toString(), "volumeGroup", "createInstance"); - Assert.assertNull(vnfComponentsRecipe); + assertNull(vnfComponentsRecipe); } @Test public void testGetFirstVnfComponentsRecipeByVnfComponentTypeAndAction() { VnfComponentsRecipe vnfComponentsRecipe = client.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction("volumeGroup", "createInstance"); - Assert.assertNotNull(vnfComponentsRecipe); - Assert.assertNotNull(vnfComponentsRecipe.getAction()); - Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType()); - Assert.assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription()); - Assert.assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1", - vnfComponentsRecipe.getOrchestrationUri()); + assertNotNull(vnfComponentsRecipe); + assertNotNull(vnfComponentsRecipe.getAction()); + assertNotNull(vnfComponentsRecipe.getVnfComponentType()); + assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription()); + assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1", vnfComponentsRecipe.getOrchestrationUri()); } @Test public void testGetServiceByModelVersionAndModelInvariantUUID() { Service service = client.getServiceByModelVersionAndModelInvariantUUID("2.0", "9647dfc4-2083-11e7-93ae-92361f002671"); - Assert.assertNotNull(service); - Assert.assertNotNull(service.getModelVersion()); - Assert.assertNotNull(service.getModelInvariantUUID()); - Assert.assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName()); - Assert.assertEquals("NA", service.getServiceRole()); + assertNotNull(service); + assertNotNull(service.getModelVersion()); + assertNotNull(service.getModelInvariantUUID()); + assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName()); + assertEquals("NA", service.getServiceRole()); } @Test public void testGetServiceByModelVersionAndModelInvariantUUIDNotFound() { Service service = client.getServiceByModelVersionAndModelInvariantUUID("2.0", UUID.randomUUID().toString()); - Assert.assertNull(service); + assertNull(service); } @Test public void testGetVfModuleByModelInvariantUUIDAndModelVersion() { VfModule vfModule = client.getVfModuleByModelInvariantUUIDAndModelVersion("78ca26d0-246d-11e7-93ae-92361f002671", "2"); - Assert.assertNotNull(vfModule); - Assert.assertNotNull(vfModule.getModelVersion()); - Assert.assertNotNull(vfModule.getModelInvariantUUID()); - Assert.assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); - Assert.assertEquals("vSAMP10a DEV Base", vfModule.getDescription()); + assertNotNull(vfModule); + assertNotNull(vfModule.getModelVersion()); + assertNotNull(vfModule.getModelInvariantUUID()); + assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName()); + assertEquals("vSAMP10a DEV Base", vfModule.getDescription()); } @Test public void testGetVfModuleByModelInvariantUUIDAndModelVersionNotFound() { VfModule vfModule = client.getVfModuleByModelInvariantUUIDAndModelVersion(UUID.randomUUID().toString(), "2"); - Assert.assertNull(vfModule); + assertNull(vfModule); } @Test public void testGetServiceByModelInvariantUUIDOrderByModelVersionDesc() { List<Service> serviceList = client.getServiceByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671"); - Assert.assertFalse(serviceList.isEmpty()); - Assert.assertEquals(2, serviceList.size()); + assertFalse(serviceList.isEmpty()); + assertEquals(2, serviceList.size()); Service service = serviceList.get(0); - Assert.assertEquals("2.0", service.getModelVersion()); + assertEquals("2.0", service.getModelVersion()); } @Test public void testGetServiceByModelInvariantUUIDOrderByModelVersionDescNotFound() { List<Service> serviceList = client.getServiceByModelInvariantUUIDOrderByModelVersionDesc(UUID.randomUUID().toString()); - Assert.assertTrue(serviceList.isEmpty()); + assertTrue(serviceList.isEmpty()); } @Test public void testGetVfModuleByModelInvariantUUIDOrderByModelVersionDesc() { List<VfModule> moduleList = client.getVfModuleByModelInvariantUUIDOrderByModelVersionDesc("78ca26d0-246d-11e7-93ae-92361f002671"); - Assert.assertFalse(moduleList.isEmpty()); - Assert.assertEquals(2, moduleList.size()); + assertFalse(moduleList.isEmpty()); + assertEquals(2, moduleList.size()); VfModule module = moduleList.get(0); - Assert.assertEquals("vSAMP10a DEV Base", module.getDescription()); + assertEquals("vSAMP10a DEV Base", module.getDescription()); } @Test @@ -454,20 +449,20 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { cloudSite.setIdentityService(cloudIdentity); localClient.postCloudSite(cloudSite); CloudSite getCloudSite = this.client.getCloudSite("MTN6"); - Assert.assertNotNull(getCloudSite); - Assert.assertNotNull(getCloudSite.getIdentityService()); - Assert.assertEquals("TESTCLLI", getCloudSite.getClli()); - Assert.assertEquals("regionId", getCloudSite.getRegionId()); - Assert.assertEquals("RANDOMID", getCloudSite.getIdentityServiceId()); + assertNotNull(getCloudSite); + assertNotNull(getCloudSite.getIdentityService()); + assertEquals("TESTCLLI", getCloudSite.getClli()); + assertEquals("regionId", getCloudSite.getRegionId()); + assertEquals("RANDOMID", getCloudSite.getIdentityServiceId()); } @Test public void testGetHomingInstance() { HomingInstance homingInstance = client.getHomingInstance("5df8b6de-2083-11e7-93ae-92361f232671"); - Assert.assertNotNull(homingInstance); - Assert.assertNotNull(homingInstance.getCloudOwner()); - Assert.assertNotNull(homingInstance.getCloudRegionId()); - Assert.assertNotNull(homingInstance.getOofDirectives()); + assertNotNull(homingInstance); + assertNotNull(homingInstance.getCloudOwner()); + assertNotNull(homingInstance.getCloudRegionId()); + assertNotNull(homingInstance.getOofDirectives()); } @Test @@ -491,43 +486,43 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { + "\"id\": \"vsink\"\n" + "}\n" + "]\n" + "}"); localClient.postHomingInstance(homingInstance); HomingInstance getHomingInstance = this.client.getHomingInstance("5df8d6be-2083-11e7-93ae-92361f232671"); - Assert.assertNotNull(getHomingInstance); - Assert.assertNotNull(getHomingInstance.getCloudRegionId()); - Assert.assertNotNull(getHomingInstance.getCloudOwner()); - Assert.assertEquals("CloudOwner-1", getHomingInstance.getCloudOwner()); - Assert.assertEquals("CloudRegionOne", getHomingInstance.getCloudRegionId()); + assertNotNull(getHomingInstance); + assertNotNull(getHomingInstance.getCloudRegionId()); + assertNotNull(getHomingInstance.getCloudOwner()); + assertEquals("CloudOwner-1", getHomingInstance.getCloudOwner()); + assertEquals("CloudRegionOne", getHomingInstance.getCloudRegionId()); } @Test public void testGetServiceByModelName() { Service service = client.getServiceByModelName("MSOTADevInfra_Test_Service"); - Assert.assertNotNull(service); - Assert.assertNotNull(service.getModelVersion()); - Assert.assertNotNull(service.getModelInvariantUUID()); - Assert.assertEquals("MSOTADevInfra_Test_Service", service.getModelName()); - Assert.assertEquals("NA", service.getServiceRole()); + assertNotNull(service); + assertNotNull(service.getModelVersion()); + assertNotNull(service.getModelInvariantUUID()); + assertEquals("MSOTADevInfra_Test_Service", service.getModelName()); + assertEquals("NA", service.getServiceRole()); } @Test public void testGetServiceByModelNameNotFound() { Service service = client.getServiceByModelName("Not_Found"); - Assert.assertNull(service); + assertNull(service); } @Test public void testGetServiceByModelUUID() { Service service = client.getServiceByModelUUID("5df8b6de-2083-11e7-93ae-92361f002679"); - Assert.assertNotNull(service); - Assert.assertNotNull(service.getModelVersion()); - Assert.assertNotNull(service.getModelInvariantUUID()); - Assert.assertEquals("5df8b6de-2083-11e7-93ae-92361f002679", service.getModelUUID()); - Assert.assertEquals("NA", service.getServiceRole()); + assertNotNull(service); + assertNotNull(service.getModelVersion()); + assertNotNull(service.getModelInvariantUUID()); + assertEquals("5df8b6de-2083-11e7-93ae-92361f002679", service.getModelUUID()); + assertEquals("NA", service.getServiceRole()); } @Test public void testGetServiceByModelUUIDNotFound() { Service service = client.getServiceByModelUUID("Not_Found"); - Assert.assertNull(service); + assertNull(service); } @Test @@ -539,53 +534,52 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { northBoundRequest.setCloudOwner("my-custom-cloud-owner"); client.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner("createService", "service", true, "my-custom-cloud-owner"); - Assert.assertNotNull(northBoundRequest); - Assert.assertEquals("createService", northBoundRequest.getAction()); - Assert.assertEquals("service", northBoundRequest.getRequestScope()); - Assert.assertEquals(true, northBoundRequest.getIsAlacarte()); - Assert.assertEquals("my-custom-cloud-owner", northBoundRequest.getCloudOwner()); + assertNotNull(northBoundRequest); + assertEquals("createService", northBoundRequest.getAction()); + assertEquals("service", northBoundRequest.getRequestScope()); + assertEquals(true, northBoundRequest.getIsAlacarte()); + assertEquals("my-custom-cloud-owner", northBoundRequest.getCloudOwner()); } @Test public void testFindServiceRecipeByActionAndServiceModelUUID() { ServiceRecipe serviceRecipe = client.findServiceRecipeByActionAndServiceModelUUID("createInstance", "4694a55f-58b3-4f17-92a5-796d6f5ffd0d"); - Assert.assertNotNull(serviceRecipe); - Assert.assertNotNull(serviceRecipe.getServiceModelUUID()); - Assert.assertNotNull(serviceRecipe.getAction()); - Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", - serviceRecipe.getOrchestrationUri()); - Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); + assertNotNull(serviceRecipe); + assertNotNull(serviceRecipe.getServiceModelUUID()); + assertNotNull(serviceRecipe.getAction()); + assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", serviceRecipe.getOrchestrationUri()); + assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription()); } @Test public void testFindServiceRecipeByActionAndServiceModelUUIDNotFound() { ServiceRecipe serviceRecipe = client.findServiceRecipeByActionAndServiceModelUUID("not_found", "5df8b6de-2083-11e7-93ae-test"); - Assert.assertNull(serviceRecipe); + assertNull(serviceRecipe); } @Test public void testFindExternalToInternalServiceByServiceName() { ExternalServiceToInternalService externalServiceToInternalService = client.findExternalToInternalServiceByServiceName("MySpecialServiceName"); - Assert.assertNotNull(externalServiceToInternalService); - Assert.assertNotNull(externalServiceToInternalService.getServiceName()); - Assert.assertNotNull(externalServiceToInternalService.getServiceModelUUID()); - Assert.assertEquals("MySpecialServiceName", externalServiceToInternalService.getServiceName()); + assertNotNull(externalServiceToInternalService); + assertNotNull(externalServiceToInternalService.getServiceName()); + assertNotNull(externalServiceToInternalService.getServiceModelUUID()); + assertEquals("MySpecialServiceName", externalServiceToInternalService.getServiceName()); } @Test public void testFindExternalToInternalServiceByServiceNameNotFound() { ExternalServiceToInternalService externalServiceToInternalService = client.findExternalToInternalServiceByServiceName("Not_Found"); - Assert.assertNull(externalServiceToInternalService); + assertNull(externalServiceToInternalService); } @Test public void getPnfResourceByModelUUID_validUuid_expectedOutput() { PnfResource pnfResource = client.getPnfResourceByModelUUID("ff2ae348-214a-11e7-93ae-92361f002680"); - Assert.assertNotNull(pnfResource); + assertNotNull(pnfResource); assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID()); assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680", pnfResource.getModelInvariantUUID()); @@ -596,7 +590,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getPnfResourceByModelUUID_invalidUuid_NullOutput() { PnfResource pnfResource = client.getPnfResourceByModelUUID(UUID.randomUUID().toString()); - Assert.assertNull(pnfResource); + assertNull(pnfResource); } @Test @@ -620,7 +614,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { public void getPnfResourceCustomizationByModelCustomizationUUID_invalidUuid_nullOutput() { PnfResourceCustomization pnfResourceCustomization = client.getPnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString()); - Assert.assertNull(pnfResourceCustomization); + assertNull(pnfResourceCustomization); } @Test @@ -651,6 +645,53 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { } @Test + public void testGetServiceTopologyById() throws Exception { + org.onap.so.rest.catalog.beans.Service serviceByID = + client.getServiceModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", "2"); + assertNotNull(serviceByID); + assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName()); + assertEquals("NA", serviceByID.getServiceType()); + assertEquals("NA", serviceByID.getServiceRole()); + } + + @Test + public void testGetServices() throws Exception { + List<org.onap.so.rest.catalog.beans.Service> services = client.getServices(); + assertEquals(false, services.isEmpty()); + } + + @Test + public void testVnf() throws Exception { + org.onap.so.rest.catalog.beans.Vnf vnf = client.getVnfModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", + "68dc9a92-214c-11e7-93ae-92361f002671", "0"); + assertNotNull(vnf); + assertEquals("vSAMP10a", vnf.getModelName()); + assertEquals(false, vnf.getNfDataValid()); + assertEquals("vSAMP", vnf.getNfFunction()); + assertEquals("vSAMP", vnf.getNfNamingCode()); + assertEquals("vSAMP", vnf.getNfRole()); + assertEquals("vSAMP", vnf.getNfType()); + + vnf.setNfDataValid(true); + vnf.setNfFunction("nfFunction"); + vnf.setNfRole("nfRole"); + vnf.setNfType("nfType"); + vnf.setNfNamingCode("nfNamingCode"); + + client.updateVnf("5df8b6de-2083-11e7-93ae-92361f002671", vnf); + vnf = client.getVnfModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", + "68dc9a92-214c-11e7-93ae-92361f002671", "0"); + assertEquals("vSAMP10a", vnf.getModelName()); + assertEquals(true, vnf.getNfDataValid()); + assertEquals("nfFunction", vnf.getNfFunction()); + assertEquals("nfNamingCode", vnf.getNfNamingCode()); + assertEquals("nfRole", vnf.getNfRole()); + assertEquals("nfType", vnf.getNfType()); + + + } + + @Test public void getWorkflowByArtifactUUID_validUuid_expectedOutput() { Workflow workflow = client.findWorkflowByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1"); assertEquals("artifactName", "testingWorkflow.bpmn", workflow.getArtifactName()); @@ -659,7 +700,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowByArtifactUUID_invalidUuid_nullOutput() { Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString()); - Assert.assertNull(workflow); + assertNull(workflow); } @Test @@ -674,7 +715,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowByModelUUID_invalidUuid_nullOutput() { Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString()); - Assert.assertNull(workflow); + assertNull(workflow); } @Test @@ -689,7 +730,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { @Test public void getWorkflowBySource_invalidSource_nullOutput() { List<Workflow> workflow = client.findWorkflowBySource("abc"); - Assert.assertNull(workflow); + assertNull(workflow); } } diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json b/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json index cc5145f0e3..2dc83c8963 100644 --- a/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json +++ b/adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json @@ -23,6 +23,7 @@ "toscaNodeType": "toscaNodeType", "nfFunction": "nfFunction", "nfRole": "nfRole", + "nfType": "nfType", "nfNamingCode": "nfNamingCode", "multiStageDesign": "multiStageDesign", "orchestrationMode": "orchestrationMode", diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index c0e065c298..153de2fb12 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -1477,13 +1477,19 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } if (subnet.getAllocationPools() != null) { - curR = curR + " allocation_pools:\n"; + StringBuilder tempBuf = new StringBuilder(); + tempBuf.append(curR); + tempBuf.append(" allocation_pools:\n"); for (Pool pool : subnet.getAllocationPools()) { if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) { - curR = curR + " - start: " + pool.getStart() + "\n"; - curR = curR + " end: " + pool.getEnd() + "\n"; + tempBuf.append(" - start: "); + tempBuf.append(pool.getStart()); + tempBuf.append("\n end: "); + tempBuf.append(pool.getEnd()); + tempBuf.append("\n"); } } + curR = tempBuf.toString(); } resourcesBuf.append(curR); @@ -1492,7 +1498,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { curO = curO.replace("%subnetId%", subnet.getSubnetId()); outputsBuf.append(curO); - } // append resources and outputs in heatTemplate logger.debug("Tempate initial:{}", heatTemplate); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java deleted file mode 100644 index 7786b872ef..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.vnf; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; -import org.onap.so.adapters.vdu.VduArtifact; -import org.onap.so.adapters.vdu.VduArtifact.ArtifactType; -import org.onap.so.adapters.vdu.VduModelInfo; -import org.onap.so.adapters.vnf.exceptions.VnfException; -import com.google.common.io.Files; - -/** - * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA - * orchestrator. - * - * @author DeWayne - * - */ -public class CSAR { - private static final String MANIFEST_FILENAME = "MANIFEST.MF"; - private VduModelInfo vduModel; - - public CSAR(VduModelInfo model) { - this.vduModel = model; - } - - /** - * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor. - * - * @return - * @throws VnfException - */ - public byte[] create() { - File dir = Files.createTempDir(); - - /** - * Create subdir - */ - File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata"); - if (!metadir.mkdir()) { - throw new RuntimeException("CSAR TOSCA-Metadata directory create failed"); - } - - /** - * Organize model info for consumption - */ - VduArtifact mainTemplate = null; - List<VduArtifact> extraFiles = new ArrayList<>(); - for (VduArtifact artifact : vduModel.getArtifacts()) { - if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) { - mainTemplate = artifact; - } else { - extraFiles.add(artifact); - } - } - - if (mainTemplate == null) { // make a dummy to avoid null pointers - mainTemplate = new VduArtifact("", new byte[0], null); - } - - /** - * Write template files - */ - try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName())); - PrintStream mfstream = - new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) { - ofs.write(mainTemplate.getContent()); - - /** - * Write other files - */ - if (!extraFiles.isEmpty()) { - for (VduArtifact artifact : extraFiles) { - try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) { - out.write(artifact.getContent()); - } - } - } - - - /** - * Create manifest - */ - mfstream.println("TOSCA-Meta-File-Version: 1.0"); - mfstream.println("CSAR-Version: 1.1"); - mfstream.println("Created-by: ONAP"); - mfstream.println("Entry-Definitions: " + mainTemplate.getName()); - - /** - * ZIP it up - */ - ByteArrayOutputStream zipbytes = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(zipbytes); - compressTree(zos, "", dir, dir); - zos.close(); - return zipbytes.toByteArray(); - - } catch (Exception e) { - throw new RuntimeException("Failed to create CSAR: " + e.getMessage()); - } finally { - /** - * Clean up tmpdir - */ - deleteDirectory(dir); - } - } - - /** - * Private methods - */ - - /** - * Compresses (ZIPs) a directory tree - * - * @param dir - * @throws IOException - */ - private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException { - if (!dir.isDirectory()) - return; - - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - String newpath = path + f.getName() + '/'; - ZipEntry entry = new ZipEntry(newpath); - zos.putNextEntry(entry); - zos.closeEntry(); - compressTree(zos, newpath, basedir, f); - } else { - ZipEntry ze = new ZipEntry( - f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/")); - zos.putNextEntry(ze); - // read the file and write to ZipOutputStream - try (FileInputStream fis = new FileInputStream(f);) { - byte[] buffer = new byte[1024]; - int len; - while ((len = fis.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } - } - zos.closeEntry(); - } - } - } - - private boolean deleteDirectory(File directory) { - if (directory.exists()) { - File[] files = directory.listFiles(); - if (null != files) { - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - deleteDirectory(files[i]); - } else { - files[i].delete(); - } - } - } - } - return (directory.delete()); - } -} 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 1d73bf21c9..af2fa24ff9 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 @@ -640,7 +640,11 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { StackInfo heatStack = null; try { - heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); + if (heat != null) { + heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); + } else { + throw new MsoHeatNotFoundException(); + } } catch (MsoException me) { String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index 7b3ffd7d30..9406bc445d 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -1109,6 +1109,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java index 3b9406a697..073412133c 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java @@ -37,6 +37,7 @@ import java.nio.file.Paths; import java.util.List; import java.util.Optional; import org.onap.so.logger.LoggingAnchor; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.sdc.api.IDistributionClient; import org.onap.sdc.api.consumer.IDistributionStatusMessage; import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; @@ -71,6 +72,7 @@ import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.stereotype.Component; @@ -588,6 +590,10 @@ public class ASDCController { logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(), String.valueOf(noOfArtifacts), iNotif.getServiceUUID(), "ASDC"); try { + + if (iNotif.getDistributionID() != null && !iNotif.getDistributionID().isEmpty()) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, iNotif.getDistributionID()); + } logger.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif)); logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(), "ASDC", "treatNotification"); diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java index 095741c19b..195aa7e302 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/BpmnInstaller.java @@ -33,7 +33,6 @@ import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; -import org.onap.so.logger.LoggingAnchor; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; @@ -49,6 +48,7 @@ import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.HttpClientBuilder; import org.onap.so.asdc.client.ASDCConfiguration; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,9 +71,8 @@ public class BpmnInstaller { public void installBpmn(String csarFilePath) { logger.info("Deploying BPMN files from {}", csarFilePath); - try { - ZipInputStream csarFile = - new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString())); + try (ZipInputStream csarFile = + new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()))) { ZipEntry entry = csarFile.getNextEntry(); while (entry != null) { @@ -103,7 +102,6 @@ public class BpmnInstaller { } entry = csarFile.getNextEntry(); } - csarFile.close(); } catch (IOException ex) { logger.debug("Exception :", ex); logger.error(LoggingAnchor.FIVE, MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath, diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java index 0681cd8aed..055968cc95 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java @@ -33,6 +33,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.asdc.BaseTest; import org.onap.so.asdc.client.exceptions.ASDCControllerException; import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl; @@ -55,6 +56,7 @@ import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @@ -277,6 +279,35 @@ public class ASDCControllerITTest extends BaseTest { } } + /** + * Test to check RequestId is being set using the DistributionID. + */ + @Test + public void treatNotification_verifyRequestID() { + + String serviceUuid = "efaea486-561f-4159-9191-a8d3cb346728"; + String serviceInvariantUuid = "f2edfbf4-bb0a-4fe7-a57a-71362d4b0b23"; + distributionId = "bb15de12-166d-4e45-9e5f-4b3f25200d7b"; + + initMockAaiServer(serviceUuid, serviceInvariantUuid); + + NotificationDataImpl notificationData = new NotificationDataImpl(); + notificationData.setServiceUUID(serviceUuid); + notificationData.setDistributionID(distributionId); + notificationData.setServiceInvariantUUID(serviceInvariantUuid); + notificationData.setServiceVersion("1.0"); + + try { + asdcController.treatNotification(notificationData); + logger.info("Verify RequestId : {}", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("bb15de12-166d-4e45-9e5f-4b3f25200d7b", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + + } catch (Exception e) { + logger.info(e.getMessage(), e); + fail(e.getMessage()); + } + } + private ArtifactInfoImpl constructPnfServiceArtifact() { ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); artifactInfo.setArtifactType(ASDCConfiguration.TOSCA_CSAR); diff --git a/asdc-controller/src/test/resources/schema.sql b/asdc-controller/src/test/resources/schema.sql index 652fc8f0de..ad6b156956 100644 --- a/asdc-controller/src/test/resources/schema.sql +++ b/asdc-controller/src/test/resources/schema.sql @@ -1113,6 +1113,7 @@ CREATE TABLE `vnf_resource_customization` ( `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java index 68cda5c22b..69151ff74f 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java @@ -27,9 +27,9 @@ import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner; import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java index 5f4dc871fb..ea7de687ee 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java @@ -27,8 +27,8 @@ import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java index 040522b576..02cddf3655 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java @@ -28,9 +28,11 @@ import org.camunda.bpm.engine.delegate.DelegateExecution; import org.javatuples.Pair; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; -import org.onap.so.bpmn.common.listener.ListenerRunner; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.listener.ListenerRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -47,6 +49,9 @@ public abstract class FlowValidatorRunner<S extends FlowValidator, E extends Flo private static Logger logger = LoggerFactory.getLogger(FlowValidatorRunner.class); + @Autowired + protected ExceptionBuilder exceptionBuilder; + protected List<S> preFlowValidators; protected List<E> postFlowValidators; diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java index 09a5424d47..be53e505ac 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java @@ -104,6 +104,7 @@ public class ExecuteBuildingBlockRainyDay { } } catch (Exception ex) { // keep default serviceType value + logger.error("Exception in serviceType retrivel", ex); } String vnfType = ASTERISK; try { @@ -115,6 +116,7 @@ public class ExecuteBuildingBlockRainyDay { } } catch (Exception ex) { // keep default vnfType value + logger.error("Exception in vnfType retrivel", ex); } String errorCode = ASTERISK; @@ -122,12 +124,14 @@ public class ExecuteBuildingBlockRainyDay { errorCode = "" + workflowException.getErrorCode(); } catch (Exception ex) { // keep default errorCode value + logger.error("Exception in errorCode retrivel", ex); } try { errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode"); } catch (Exception ex) { // keep default errorCode value + logger.error("Exception in errorCode retrivel", ex); } String workStep = ASTERISK; @@ -135,6 +139,7 @@ public class ExecuteBuildingBlockRainyDay { workStep = workflowException.getWorkStep(); } catch (Exception ex) { // keep default workStep value + logger.error("Exception in workStep retrivel", ex); } String errorMessage = ASTERISK; @@ -142,6 +147,7 @@ public class ExecuteBuildingBlockRainyDay { errorMessage = workflowException.getErrorMessage(); } catch (Exception ex) { // keep default workStep value + logger.error("Exception in errorMessage retrivel", ex); } String serviceRole = ASTERISK; @@ -177,14 +183,14 @@ public class ExecuteBuildingBlockRainyDay { logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex); } } - if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) { + if ("RollbackToAssigned".equals(handlingCode) && !aLaCarte) { handlingCode = "Rollback"; } if (handlingCode.startsWith("Rollback")) { String targetState = ""; - if (handlingCode.equalsIgnoreCase("RollbackToAssigned")) { + if ("RollbackToAssigned".equalsIgnoreCase(handlingCode)) { targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString(); - } else if (handlingCode.equalsIgnoreCase("RollbackToCreated")) { + } else if ("RollbackToCreated".equalsIgnoreCase(handlingCode)) { targetState = Status.ROLLED_BACK_TO_CREATED.toString(); } else { targetState = Status.ROLLED_BACK.toString(); @@ -204,7 +210,7 @@ public class ExecuteBuildingBlockRainyDay { int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries)); execution.setVariable("maxRetries", envMaxRetries); } catch (Exception ex) { - logger.error("Could not read maxRetries from config file. Setting max to 5 retries"); + logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex); execution.setVariable("maxRetries", 5); } } @@ -247,8 +253,7 @@ public class ExecuteBuildingBlockRainyDay { request.setLastModifiedBy("CamundaBPMN"); requestDbclient.updateInfraActiveRequests(request); } catch (Exception e) { - logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: " - + e.getMessage()); + logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: ", e); } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java index b2dbd97bfc..aee28cae00 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java @@ -90,7 +90,6 @@ public class ExtractPojosForBB { result = lookupObjectInList(serviceInstance.getConfigurations(), value); break; case VPN_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value); break; case VPN_BONDING_LINK_ID: @@ -107,8 +106,9 @@ public class ExtractPojosForBB { } catch (BBObjectNotFoundException e) { // re-throw parent object not found throw e; } catch (Exception e) { // convert all other exceptions to object not found - logger.warn("BBObjectNotFoundException in ExtractPojosForBB", - "BBObject " + key + " was not found in " + "gBBInput using reference value: " + value); + logger.warn( + "BBObjectNotFoundException in ExtractPojosForBB, BBObject {} was not found in gBBInput using reference value: {} {}", + key, value, e); throw new BBObjectNotFoundException(key, value); } @@ -119,13 +119,8 @@ public class ExtractPojosForBB { } } - protected <T> Optional<T> lookupObject(Object obj, String value) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { - return findValue(obj, value); - } - - protected <T> Optional<T> lookupObjectInList(List<?> list, String value) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + protected <T> Optional<T> lookupObjectInList(List<?> list, String value) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Optional<T> result = Optional.empty(); for (Object obj : list) { result = findValue(obj, value); @@ -137,8 +132,8 @@ public class ExtractPojosForBB { } - protected <T> Optional<T> findValue(Object obj, String value) throws IllegalAccessException, - IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { + protected <T> Optional<T> findValue(Object obj, String value) + throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { for (Field field : obj.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) { String fieldName = field.getName(); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java index 2c0377d11c..f4fe6d7158 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java @@ -47,7 +47,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {ValidationConfig.class}) -public class BuildingBlockValidatorRunnerTest { +public class BuildingBlockValidatorRunnerTest extends BuildingBlockValidatorRunner { @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java index 0143e567af..596eced1d1 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java @@ -45,7 +45,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {ValidationConfig.class}) -public class WorkflowValidatorRunnerTest { +public class WorkflowValidatorRunnerTest extends WorkflowValidatorRunner { @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java index af64ed2de6..544d370a3c 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java @@ -23,8 +23,8 @@ package org.onap.so.bpmn.common.listener.validation; import java.util.Collections; import java.util.Optional; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.Skip; import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; +import org.onap.so.listener.Skip; import org.springframework.stereotype.Component; @Component diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java index 068f433dd5..a3692a50b7 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java @@ -21,13 +21,13 @@ package org.onap.so.bpmn.common.listener.validation; import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator; -import org.onap.so.bpmn.common.listener.ListenerRunner; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.listener.ListenerRunner; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class}, +@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class, WorkflowValidatorRunner.class}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class) public class ValidationConfig { diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java index 093fba089d..050a2af06a 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java @@ -136,8 +136,8 @@ public class MSOInfrastructureApplication { deploymentBuilder.addString(workflowName, workflowBody); } deploymentBuilder.enableDuplicateFiltering(true); - deploymentBuilder.deploy(); } + deploymentBuilder.deploy(); } } catch (Exception e) { logger.warn("Unable to deploy custom workflows, " + e.getMessage()); diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java index 2f05eb5f2d..29dca19820 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java @@ -50,6 +50,7 @@ import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.camunda.bpm.engine.delegate.DelegateExecution; @@ -98,8 +99,7 @@ public class ServicePluginFactory { new String[] {VS_MONITORED, VS_UNMONITORED, TS_MONITORED, TS_UNMONITORED}; static { - try { - InputStream is = ClassLoader.class.getResourceAsStream("/application.properties"); + try (InputStream is = ClassLoader.class.getResourceAsStream("/application.properties")) { if (null != is) { Properties prop = new Properties(); prop.load(is); @@ -855,14 +855,12 @@ public class ServicePluginFactory { HttpRequestBase method = null; HttpResponse httpResponse = null; - try { + try (CloseableHttpClient client = HttpClientBuilder.create().build()) { int timeout = DEFAULT_TIME_OUT; RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout).build(); - HttpClient client = HttpClientBuilder.create().build(); - if ("POST".equalsIgnoreCase(methodType)) { HttpPost httpPost = new HttpPost(msbUrl); httpPost.setConfig(requestConfig); @@ -902,9 +900,6 @@ public class ServicePluginFactory { method = null; return responseContent; - } catch (SocketTimeoutException | ConnectTimeoutException e) { - return null; - } catch (Exception e) { return null; @@ -913,13 +908,14 @@ public class ServicePluginFactory { try { EntityUtils.consume(httpResponse.getEntity()); } catch (Exception e) { + logger.debug("Exception while executing finally block", e); } } if (method != null) { try { method.reset(); } catch (Exception e) { - + logger.debug("Exception while executing finally block", e); } } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java index 68cfd487b3..bd60fbe38c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java @@ -71,6 +71,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import com.google.common.base.Strings; @Component public class AAICreateTasks { @@ -184,24 +185,35 @@ public class AAICreateTasks { ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); OwningEntity owningEntity = serviceInstance.getOwningEntity(); - String owningEntityId = owningEntity.getOwningEntityId(); - String owningEntityName = owningEntity.getOwningEntityName(); - if (owningEntityId == null || "".equals(owningEntityId)) { - String msg = "Exception in AAICreateOwningEntity. OwningEntityId is null."; + if (Strings.isNullOrEmpty(owningEntity.getOwningEntityId()) + && Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) { + String msg = "Exception in AAICreateOwningEntity. OwningEntityId and Name are null."; execution.setVariable("ErrorCreateOEAAI", msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); + } else if (Strings.isNullOrEmpty(owningEntity.getOwningEntityId()) + && !Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) { + if (aaiSIResources.existsOwningEntityName(owningEntity.getOwningEntityName())) { + org.onap.aai.domain.yang.OwningEntity aaiEntity = + aaiSIResources.getOwningEntityByName(owningEntity.getOwningEntityName()); + owningEntity.setOwningEntityId(aaiEntity.getOwningEntityId()); + owningEntity.setOwningEntityName(owningEntity.getOwningEntityName()); + aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance); + } else { + owningEntity.setOwningEntityId(UUID.randomUUID().toString()); + aaiSIResources.createOwningEntityandConnectServiceInstance(owningEntity, serviceInstance); + } } else { if (aaiSIResources.existsOwningEntity(owningEntity)) { aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance); } else { - if (owningEntityName == null || "".equals(owningEntityName)) { + if (Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) { String msg = "Exception in AAICreateOwningEntity. Can't create an owningEntity with no owningEntityName."; logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", ErrorCode.UnknownError.getValue(), msg); exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg); } else { - if (aaiSIResources.existsOwningEntityName(owningEntityName)) { + if (aaiSIResources.existsOwningEntityName(owningEntity.getOwningEntityName())) { String msg = "Exception in AAICreateOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)"; logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java index eddcc94e71..127d21c0ed 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java @@ -23,8 +23,12 @@ package org.onap.so.bpmn.infrastructure.appc.tasks; import java.util.HashMap; +import java.util.List; import java.util.Optional; import org.onap.so.logger.LoggingAnchor; +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.aai.domain.yang.Vserver; import org.onap.appc.client.lcm.model.Action; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; @@ -33,9 +37,14 @@ import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.Relationships; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.appc.ApplicationControllerAction; import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.orchestration.AAIVnfResources; import org.onap.so.db.catalog.beans.ControllerSelectionReference; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logger.ErrorCode; @@ -59,6 +68,8 @@ public class AppcRunTasks { private CatalogDbClient catalogDbClient; @Autowired private ApplicationControllerAction appCClient; + @Autowired + private AAIVnfResources aaiVnfResources; public void preProcessActivity(BuildingBlockExecution execution) { execution.setVariable("actionSnapshot", Action.Snapshot); @@ -78,6 +89,22 @@ public class AppcRunTasks { execution.setVariable(ROLLBACK_VNF_STOP, false); execution.setVariable(ROLLBACK_VNF_LOCK, false); execution.setVariable(ROLLBACK_QUIESCE_TRAFFIC, false); + execution.setVariable("vmIdList", null); + execution.setVariable("vserverIdList", null); + + GenericVnf vnf = null; + try { + vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + } catch (BBObjectNotFoundException e) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "No valid VNF exists"); + } + + try { + getVserversForAppc(execution, vnf); + } catch (Exception e) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Unable to retrieve vservers"); + } + } public void runAppcCommand(BuildingBlockExecution execution, Action action) { @@ -155,7 +182,7 @@ public class AppcRunTasks { } protected void mapRollbackVariables(BuildingBlockExecution execution, Action action, String appcCode) { - if (appcCode.equals("0") && action != null) { + if (appcCode != null && appcCode.equals("0") && action != null) { if (action.equals(Action.Lock)) { execution.setVariable(ROLLBACK_VNF_LOCK, true); } else if (action.equals(Action.Unlock)) { @@ -184,4 +211,45 @@ public class AppcRunTasks { payloadInfo.put("vfModuleId", vfModuleId); return payloadInfo; } + + protected void getVserversForAppc(BuildingBlockExecution execution, GenericVnf vnf) throws Exception { + AAIResultWrapper aaiRW = aaiVnfResources.queryVnfWrapperById(vnf); + + if (aaiRW != null && aaiRW.getRelationships() != null && aaiRW.getRelationships().isPresent()) { + Relationships relationships = aaiRW.getRelationships().get(); + if (relationships != null) { + List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER); + JSONArray vserverIds = new JSONArray(); + JSONArray vserverSelfLinks = new JSONArray(); + if (vserverUris != null) { + for (AAIResourceUri j : vserverUris) { + if (j != null) { + if (j.getURIKeys() != null) { + String vserverId = j.getURIKeys().get("vserver-id"); + vserverIds.put(vserverId); + } + Optional<Vserver> oVserver = aaiVnfResources.getVserver(j); + if (oVserver.isPresent()) { + Vserver vserver = oVserver.get(); + if (vserver != null) { + String vserverSelfLink = vserver.getVserverSelflink(); + vserverSelfLinks.put(vserverSelfLink); + } + } + } + } + } + + JSONObject vmidsArray = new JSONObject(); + JSONObject vserveridsArray = new JSONObject(); + vmidsArray.put("vmIds", vserverSelfLinks.toString()); + vserveridsArray.put("vserverIds", vserverIds.toString()); + logger.debug("vmidsArray is: {}", vmidsArray.toString()); + logger.debug("vserveridsArray is: {}", vserveridsArray.toString()); + + execution.setVariable("vmIdList", vmidsArray.toString()); + execution.setVariable("vserverIdList", vserveridsArray.toString()); + } + } + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java index fc3f2aec7a..52d294955a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java @@ -23,10 +23,10 @@ package org.onap.so.bpmn.infrastructure.validations; import java.util.Optional; import java.util.regex.Pattern; import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.onap.so.bpmn.common.listener.Skip; import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.listener.Skip; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java new file mode 100644 index 0000000000..5f65e5d76d --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java @@ -0,0 +1,16 @@ +package org.onap.so.client.orchestration; + +public class AAIEntityNotFoundException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -107868951852460677L; + + public AAIEntityNotFoundException(String error) { + super(error); + } + + + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java index c41f3fa56c..fc1528526c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java @@ -22,7 +22,9 @@ package org.onap.so.client.orchestration; +import java.util.List; import java.util.Optional; +import org.onap.aai.domain.yang.OwningEntities; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity; @@ -120,6 +122,25 @@ public class AAIServiceInstanceResources { return aaiRC.exists(owningEntityUri); } + public org.onap.aai.domain.yang.OwningEntity getOwningEntityByName(String owningEntityName) + throws AAIEntityNotFoundException { + AAIResourceUri owningEntityUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.OWNING_ENTITY) + .queryParam("owning-entity-name", owningEntityName); + AAIResourcesClient aaiRC = injectionHelper.getAaiClient(); + Optional<OwningEntities> owningEntities = aaiRC.get(OwningEntities.class, owningEntityUri); + if (owningEntities.isPresent()) { + List<org.onap.aai.domain.yang.OwningEntity> owningEntityList = owningEntities.get().getOwningEntity(); + if (owningEntityList.size() > 1) { + throw new AAIEntityNotFoundException( + "Non unique result returned for owning entity name: " + owningEntityName); + } else { + return owningEntityList.get(0); + } + } else { + throw new AAIEntityNotFoundException("No result returned for owning entity name: " + owningEntityName); + } + } + public void connectOwningEntityandServiceInstance(OwningEntity owningEntity, ServiceInstance serviceInstance) { AAIResourceUri owningEntityURI = AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId()); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java index a9635d1e34..63bde79b3f 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java @@ -24,6 +24,7 @@ package org.onap.so.client.orchestration; import java.io.IOException; import java.util.Optional; +import org.onap.aai.domain.yang.Vserver; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; @@ -37,9 +38,8 @@ import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; +import org.onap.so.client.graphinventory.entities.uri.Depth; import org.onap.so.db.catalog.beans.OrchestrationStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -160,4 +160,14 @@ public class AAIVnfResources { AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName); return injectionHelper.getAaiClient().exists(vnfUri); } + + public AAIResultWrapper queryVnfWrapperById(GenericVnf vnf) { + AAIResourceUri uri = + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId()).depth(Depth.ALL); + return injectionHelper.getAaiClient().get(uri); + } + + public Optional<Vserver> getVserver(AAIResourceUri uri) { + return injectionHelper.getAaiClient().get(uri).asBean(Vserver.class); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java index ed3ec759c3..a8550d8df9 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java @@ -54,16 +54,16 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network; import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness; import org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy; +import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.db.catalog.beans.OrchestrationStatus; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; public class AAICreateTasksTest extends BaseTaskTest { @@ -272,24 +272,6 @@ public class AAICreateTasksTest extends BaseTaskTest { } @Test - public void createOwningEntityNullOwningEntityIdTest() throws Exception { - expectedException.expect(BpmnError.class); - - serviceInstance.getOwningEntity().setOwningEntityId(null); - - aaiCreateTasks.createOwningEntity(execution); - } - - @Test - public void createOwningEntityEmptyOwningEntityIdTest() throws Exception { - expectedException.expect(BpmnError.class); - - serviceInstance.getOwningEntity().setOwningEntityId(""); - - aaiCreateTasks.createOwningEntity(execution); - } - - @Test public void createOwningEntityNullOwningEntityNameTest() throws Exception { expectedException.expect(BpmnError.class); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java index e7a8b35db8..8328e0e08b 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java @@ -19,11 +19,17 @@ */ package org.onap.so.bpmn.infrastructure.appc.tasks; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.HashMap; import java.util.Optional; import java.util.UUID; @@ -39,6 +45,8 @@ import org.springframework.beans.factory.annotation.Autowired; public class AppcRunTasksIT extends BaseIntegrationTest { + private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/"; + @Autowired private AppcRunTasks appcRunTasks; @@ -56,8 +64,51 @@ public class AppcRunTasksIT extends BaseIntegrationTest { } @Test - public void preProcessActivityTest() throws Exception { + public void preProcessActivityWithVserversTest() throws Exception { + final String aaiVnfJson = + new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnfWithVservers.json"))); + wireMockServer.stubFor( + get(urlEqualTo("/aai/v15/network/generic-vnfs/generic-vnf/testVnfId1?depth=all")).willReturn(aResponse() + .withHeader("Content-Type", "application/json").withBody(aaiVnfJson).withStatus(200))); + + final String aaiVserverJson = + new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVserverFullQueryResponse.json"))); + wireMockServer.stubFor(get(urlEqualTo( + "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/48bd7f11-408f-417c-b834-b41c1b98f7d7")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(aaiVserverJson) + .withStatus(200))); + wireMockServer.stubFor(get(urlEqualTo( + "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(aaiVserverJson) + .withStatus(200))); + wireMockServer.stubFor(get(urlEqualTo( + "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/14551849-1e70-45cd-bc5d-a256d49548a2")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(aaiVserverJson) + .withStatus(200))); + + appcRunTasks.preProcessActivity(execution); + String vserverIdList = execution.getVariable("vserverIdList"); + String expectedVserverIdList = + "{\"vserverIds\":\"[\\\"1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5\\\",\\\"14551849-1e70-45cd-bc5d-a256d49548a2\\\",\\\"48bd7f11-408f-417c-b834-b41c1b98f7d7\\\"]\"}"; + String vmIdList = execution.getVariable("vmIdList"); + String expectedVmIdList = + "{\"vmIds\":\"[\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\"]\"}"; + + assertEquals(vserverIdList, expectedVserverIdList); + assertEquals(vmIdList, expectedVmIdList); + assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic); + assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false); + } + + @Test + public void preProcessActivityNoVserversTest() throws Exception { + final String aaiVnfJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnf.json"))); + wireMockServer.stubFor( + get(urlEqualTo("/aai/v15/network/generic-vnfs/generic-vnf/testVnfId1?depth=all")).willReturn(aResponse() + .withHeader("Content-Type", "application/json").withBody(aaiVnfJson).withStatus(200))); appcRunTasks.preProcessActivity(execution); + assertNull(execution.getVariable("vmIdList")); + assertNull(execution.getVariable("vServerIdList")); assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic); assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java index cf673c5eb5..cc25689358 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java @@ -26,12 +26,17 @@ import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Optional; import org.junit.Test; import org.mockito.InjectMocks; +import org.onap.aai.domain.yang.Vserver; import org.onap.appc.client.lcm.model.Action; import org.onap.so.bpmn.BaseTaskTest; import org.onap.so.bpmn.common.BuildingBlockExecution; @@ -39,11 +44,16 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.db.catalog.beans.ControllerSelectionReference; +import com.fasterxml.jackson.databind.ObjectMapper; public class AppcRunTasksTest extends BaseTaskTest { + private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/"; + @InjectMocks private AppcRunTasks appcRunTasks = new AppcRunTasks(); @@ -132,6 +142,32 @@ public class AppcRunTasksTest extends BaseTaskTest { assertEquals(true, execution.getVariable("rollbackVnfLock")); } + @Test + public void getVserversForAppcTest() throws Exception { + + GenericVnf genericVnf = getTestGenericVnf(); + + final String aaiVnfJson = + new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnfWithVservers.json"))); + final String aaiVserverJson = + new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVserverQueryResponse.json"))); + AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiVnfJson); + ObjectMapper mapper = new ObjectMapper(); + Vserver vserver = mapper.readValue(aaiVserverJson, Vserver.class); + doReturn(aaiResultWrapper).when(aaiVnfResources).queryVnfWrapperById(genericVnf); + doReturn(Optional.of(vserver)).when(aaiVnfResources).getVserver(any(AAIResourceUri.class)); + appcRunTasks.getVserversForAppc(execution, genericVnf); + String vserverIdList = execution.getVariable("vserverIdList"); + String expectedVserverIdList = + "{\"vserverIds\":\"[\\\"1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5\\\",\\\"14551849-1e70-45cd-bc5d-a256d49548a2\\\",\\\"48bd7f11-408f-417c-b834-b41c1b98f7d7\\\"]\"}"; + String vmIdList = execution.getVariable("vmIdList"); + String expectedVmIdList = + "{\"vmIds\":\"[\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\"]\"}"; + + assertEquals(vserverIdList, expectedVserverIdList); + assertEquals(vmIdList, expectedVmIdList); + } + private void mockReferenceResponse() { ControllerSelectionReference reference = new ControllerSelectionReference(); reference.setControllerName("TEST-CONTROLLER-NAME"); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java index 0d48a29ca9..3680eaac81 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java @@ -20,8 +20,10 @@ package org.onap.so.client.orchestration; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -31,6 +33,8 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Optional; import org.junit.Before; import org.junit.Test; @@ -54,11 +58,14 @@ import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; +import org.onap.so.client.graphinventory.entities.uri.Depth; import org.onap.so.db.catalog.beans.OrchestrationStatus; @RunWith(MockitoJUnitRunner.Silent.class) public class AAIVnfResourcesTest extends TestDataSetup { + private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/"; + private GenericVnf genericVnf; private ServiceInstance serviceInstance; @@ -249,4 +256,37 @@ public class AAIVnfResourcesTest extends TestDataSetup { boolean nameInUse = aaiVnfResources.checkNameInUse("vnfName"); assertFalse(nameInUse); } + + @Test + public void queryVnfWrapperByIdTest() throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId").depth(Depth.ALL); + final String aaiResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnf.json"))); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setVnfId("vnfId"); + AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse); + doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(eq(uri)); + AAIResultWrapper actualResult = aaiVnfResources.queryVnfWrapperById(genericVnf); + assertEquals(actualResult, aaiResultWrapper); + + } + + @Test + public void getVserverTest() throws Exception { + final String content = + new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVserverQueryResponse.json"))); + AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content); + Optional<org.onap.aai.domain.yang.Vserver> oVserver = Optional.empty(); + AAIResourceUri vserverUri = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, "ModelInvariantUUID", + "serviceModelVersionId", "abc", "abc"); + + doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class)); + oVserver = aaiVnfResources.getVserver(vserverUri); + + verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class)); + + if (oVserver.isPresent()) { + org.onap.aai.domain.yang.Vserver vserver = oVserver.get(); + assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.Vserver.class).get(), sameBeanAs(vserver)); + } + } } diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnf.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnf.json new file mode 100644 index 0000000000..e997db3f69 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnf.json @@ -0,0 +1,57 @@ +{ + "closedLoopDisabled":false, + "vnf-id":"vnfId1", + "vnf-name":"vnfName", + "vnf-type":"vnfType", + "orchestration-status":"PRECREATED", + "vf-modules": { + "vf-module": [{ + "vf-module-id": "lukewarm", + "vf-module-name": "testVfModuleNameGWPrim", + "heat-stack-id": "fastburn", + "is-base-vf-module": true, + "orchestration-status": "Created" + }, + { + "vf-module-id": "testVfModuleIdGWSec", + "vf-module-name": "testVfModuleNameGWSec", + "heat-stack-id": "testHeatStackIdGWSec", + "orchestration-status": "Created" + }] + }, + "volume-groups":[], + "line-of-business":null, + "platform":null, + "cascaded":false, + "cloud-params":{}, + "cloud-context":null, + "solution":null, + "vnf-name-2":null, + "service-id":null, + "regional-resource-zone":null, + "prov-status":null, + "operational-status":null, + "equipment-role":null, + "management-option":null, + "ipv4-oam-address":null, + "ipv4-loopback0-address":null, + "nm-lan-v6-address":null, + "management-v6-address":null, + "vcpu":null, + "vcpu-units":null, + "vmemory":null, + "vmemory-units":null, + "vdisk":null, + "vdisk-units":null, + "in-maint":false, + "is-closed-loop-disabled":false, + "summary-status":null, + "encrypted-access-flag":null, + "as-number":null, + "regional-resource-subzone":null, + "self-link":null, + "ipv4-oam-gateway-address":null, + "ipv4-oam-gateway-address-prefix-length":null, + "vlan-id-outer":null,"nm-profile-name":null, + "model-info-generic-vnf":null +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnfWithVservers.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnfWithVservers.json new file mode 100644 index 0000000000..0ad0f054b0 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnfWithVservers.json @@ -0,0 +1,434 @@ +{ + "vnf-id": "example-vnf-id-val-90603", + "vnf-name": "example-vnf-name-val-56838", + "vnf-name2": "example-vnf-name2-val-56319", + "vnf-type": "example-vnf-type-val-30533", + "service-id": "example-service-id-val-28290", + "regional-resource-zone": "example-regional-resource-zone-val-11059", + "prov-status": "example-prov-status-val-59777", + "operational-status": "example-operational-status-val-22513", + "in-maint": true, + + "equipment-role": "example-equipment-role-val-23396", + "orchestration-status": "example-orchestration-status-val-59435", + "heat-stack-id": "example-heat-stack-id-val-96869", + "mso-catalog-key": "example-mso-catalog-key-val-30721", + "management-option": "example-management-option-val-61927", + "ipv4-oam-address": "192.168.10.14", + "ipv4-loopback0-address": "example-ipv4-loopback0-address-val-87072", + "nm-lan-v6-address": "example-nm-lan-v6-address-val-91063", + "management-v6-address": "example-management-v6-address-val-80466", + "vcpu": 45837298, + "vcpu-units": "example-vcpu-units-val-86249", + "vmemory": 57288956, + "vmemory-units": "example-vmemory-units-val-13291", + "vdisk": 16937143, + "vdisk-units": "example-vdisk-units-val-73197", + + "is-closed-loop-disabled": true, + "summary-status": "example-summary-status-val-86438", + "encrypted-access-flag": true, + + + + + "model-invariant-id": "example-model-invariant-id-val-14704", + "model-version-id": "example-model-version-id-val-47847", + "model-customization-id": "example-model-customization-id-val-52688", + "widget-model-id": "example-widget-model-id-val-20939", + "widget-model-version": "example-widget-model-version-val-72210", + "as-number": "example-as-number-val-68358", + "regional-resource-subzone": "example-regional-resource-subzone-val-34391", + "nf-type": "example-nf-type-val-54866", + "nf-function": "example-nf-function-val-24790", + "nf-role": "example-nf-role-val-4780", + "nf-naming-code": "example-nf-naming-code-val-25118", + "selflink": "example-selflink-val-68404", + + "relationship-list": {"relationship": [ + { + "related-to": "service-instance", + "relationship-label": "org.onap.relationships.inventory.ComposedOf", + "related-link": "/aai/v12/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/2c323333-af4f-4849-af03-c862c0e93e3b", + "relationship-data": [ + { + "relationship-key": "customer.global-customer-id", + "relationship-value": "e433710f-9217-458d-a79d-1c7aff376d89" + }, + { + "relationship-key": "service-subscription.service-type", + "relationship-value": "VIRTUAL USP" + }, + { + "relationship-key": "service-instance.service-instance-id", + "relationship-value": "2c323333-af4f-4849-af03-c862c0e93e3b" + } + ], + "related-to-property": [ { + "property-key": "service-instance.service-instance-name", + "property-value": "kjhgfd1" + }] + }, + { + "related-to": "vserver", + "relationship-label": "tosca.relationships.HostedOn", + "related-link": "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "CloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "mtn23a" + }, + { + "relationship-key": "tenant.tenant-id", + "relationship-value": "e6beab145f6b49098277ac163ac1b4f3" + }, + { + "relationship-key": "vserver.vserver-id", + "relationship-value": "1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5" + } + ], + "related-to-property": [ { + "property-key": "vserver.vserver-name", + "property-value": "comx5000vm003" + }] + }, + { + "related-to": "vserver", + "relationship-label": "tosca.relationships.HostedOn", + "related-link": "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/14551849-1e70-45cd-bc5d-a256d49548a2", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "CloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "mtn23a" + }, + { + "relationship-key": "tenant.tenant-id", + "relationship-value": "e6beab145f6b49098277ac163ac1b4f3" + }, + { + "relationship-key": "vserver.vserver-id", + "relationship-value": "14551849-1e70-45cd-bc5d-a256d49548a2" + } + ], + "related-to-property": [ { + "property-key": "vserver.vserver-name", + "property-value": "comx5000vm002" + }] + }, + { + "related-to": "vserver", + "relationship-label": "tosca.relationships.HostedOn", + "related-link": "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/48bd7f11-408f-417c-b834-b41c1b98f7d7", + "relationship-data": [ + { + "relationship-key": "cloud-region.cloud-owner", + "relationship-value": "CloudOwner" + }, + { + "relationship-key": "cloud-region.cloud-region-id", + "relationship-value": "mtn23a" + }, + { + "relationship-key": "tenant.tenant-id", + "relationship-value": "e6beab145f6b49098277ac163ac1b4f3" + }, + { + "relationship-key": "vserver.vserver-id", + "relationship-value": "48bd7f11-408f-417c-b834-b41c1b98f7d7" + } + ], + "related-to-property": [ { + "property-key": "vserver.vserver-name", + "property-value": "comx5000vm001" + }] + } + ]}, + + + "l-interfaces": { + "l-interface": [ + { + "interface-name": "example-interface-name-val-50593", + "interface-role": "example-interface-role-val-23375", + "v6-wan-link-ip": "example-v6-wan-link-ip-val-5921", + "selflink": "example-selflink-val-75663", + "interface-id": "example-interface-id-val-37465", + "macaddr": "example-macaddr-val-62657", + "network-name": "example-network-name-val-7252", + "management-option": "example-management-option-val-32963", + "interface-description": "example-interface-description-val-89453", + "is-port-mirrored": true, + "vlans": { + "vlan": [ + { + "vlan-interface": "example-vlan-interface-val-16684", + "vlan-id-inner": 8602916, + "vlan-id-outer": 97348542, + "speed-value": "example-speed-value-val-90330", + "speed-units": "example-speed-units-val-15849", + "vlan-description": "example-vlan-description-val-46942", + "backdoor-connection": "example-backdoor-connection-val-78445", + + "orchestration-status": "example-orchestration-status-val-44994", + + + + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-90277", + "l3-interface-ipv4-prefix-length": 3364150, + "vlan-id-inner": 44021171, + "vlan-id-outer": 55708677, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-43267", + "neutron-subnet-id": "example-neutron-subnet-id-val-62870" + } + ], + "l3-interface-ipv6-address-list": [ + { + "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-45323", + "l3-interface-ipv6-prefix-length": 56688923, + "vlan-id-inner": 5703071, + "vlan-id-outer": 86682265, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-28366", + "neutron-subnet-id": "example-neutron-subnet-id-val-53034" + } + ] + } + ] + }, + "sriov-vfs": { + "sriov-vf": [ + { + "pci-id": "example-pci-id-val-4720", + "vf-vlan-filter": "example-vf-vlan-filter-val-42594", + "vf-mac-filter": "example-vf-mac-filter-val-13375", + "vf-vlan-strip": true, + "vf-vlan-anti-spoof-check": true, + "vf-mac-anti-spoof-check": true, + "vf-mirrors": "example-vf-mirrors-val-6057", + "vf-broadcast-allow": true, + "vf-unknown-multicast-allow": true, + "vf-unknown-unicast-allow": true, + "vf-insert-stag": true, + "vf-link-status": "example-vf-link-status-val-81448", + "neutron-network-id": "example-neutron-network-id-val-9504" + } + ] + }, + "l-interfaces": { + "l-interface": [ + { + "interface-name": "example-interface-name-val-16738", + "interface-role": "example-interface-role-val-13943", + "v6-wan-link-ip": "example-v6-wan-link-ip-val-63173", + "selflink": "example-selflink-val-43085", + "interface-id": "example-interface-id-val-51379", + "macaddr": "example-macaddr-val-16195", + "network-name": "example-network-name-val-45683", + "management-option": "example-management-option-val-78983", + "interface-description": "example-interface-description-val-34414", + "is-port-mirrored": true + } + ] + }, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-99078", + "l3-interface-ipv4-prefix-length": 55755841, + "vlan-id-inner": 81525473, + "vlan-id-outer": 90908072, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-47919", + "neutron-subnet-id": "example-neutron-subnet-id-val-84236" + } + ], + "l3-interface-ipv6-address-list": [ + { + "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-21939", + "l3-interface-ipv6-prefix-length": 50057584, + "vlan-id-inner": 75774660, + "vlan-id-outer": 4421090, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-46377", + "neutron-subnet-id": "example-neutron-subnet-id-val-16585" + } + ] + } + ] + }, + "lag-interfaces": { + "lag-interface": [ + { + "interface-name": "example-interface-name-val-39234", + "interface-description": "example-interface-description-val-1037", + "speed-value": "example-speed-value-val-1929", + "speed-units": "example-speed-units-val-74937", + "interface-id": "example-interface-id-val-91265", + "interface-role": "example-interface-role-val-19613", + + + "l-interfaces": { + "l-interface": [ + { + "interface-name": "example-interface-name-val-10722", + "interface-role": "example-interface-role-val-95194", + "v6-wan-link-ip": "example-v6-wan-link-ip-val-24328", + "selflink": "example-selflink-val-24987", + "interface-id": "example-interface-id-val-75726", + "macaddr": "example-macaddr-val-36940", + "network-name": "example-network-name-val-65359", + "management-option": "example-management-option-val-49521", + "interface-description": "example-interface-description-val-70528", + "is-port-mirrored": true, + "vlans": { + "vlan": [ + { + "vlan-interface": "example-vlan-interface-val-70827", + "vlan-id-inner": 55659612, + "vlan-id-outer": 90335612, + "speed-value": "example-speed-value-val-54761", + "speed-units": "example-speed-units-val-91398", + "vlan-description": "example-vlan-description-val-17018", + "backdoor-connection": "example-backdoor-connection-val-4021", + + "orchestration-status": "example-orchestration-status-val-18315", + + + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-59336", + "l3-interface-ipv4-prefix-length": 57636053, + "vlan-id-inner": 34068397, + "vlan-id-outer": 48570286, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-69862", + "neutron-subnet-id": "example-neutron-subnet-id-val-75795" + } + ], + "l3-interface-ipv6-address-list": [ + { + "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-15038", + "l3-interface-ipv6-prefix-length": 42694503, + "vlan-id-inner": 15929806, + "vlan-id-outer": 87413856, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-52519", + "neutron-subnet-id": "example-neutron-subnet-id-val-24471" + } + ] + } + ] + }, + "sriov-vfs": { + "sriov-vf": [ + { + "pci-id": "example-pci-id-val-44669", + "vf-vlan-filter": "example-vf-vlan-filter-val-53436", + "vf-mac-filter": "example-vf-mac-filter-val-71902", + "vf-vlan-strip": true, + "vf-vlan-anti-spoof-check": true, + "vf-mac-anti-spoof-check": true, + "vf-mirrors": "example-vf-mirrors-val-54963", + "vf-broadcast-allow": true, + "vf-unknown-multicast-allow": true, + "vf-unknown-unicast-allow": true, + "vf-insert-stag": true, + "vf-link-status": "example-vf-link-status-val-1546", + "neutron-network-id": "example-neutron-network-id-val-92159" + } + ] + }, + "l-interfaces": { + "l-interface": [ + { + "interface-name": "example-interface-name-val-9327", + "interface-role": "example-interface-role-val-21859", + "v6-wan-link-ip": "example-v6-wan-link-ip-val-21445", + "selflink": "example-selflink-val-6085", + "interface-id": "example-interface-id-val-39854", + "macaddr": "example-macaddr-val-14433", + "network-name": "example-network-name-val-3722", + "management-option": "example-management-option-val-64739", + "interface-description": "example-interface-description-val-5814", + "is-port-mirrored": true + + + + } + ] + }, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-64531", + "l3-interface-ipv4-prefix-length": 66545882, + "vlan-id-inner": 12194134, + "vlan-id-outer": 29589286, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-91108", + "neutron-subnet-id": "example-neutron-subnet-id-val-56984" + } + ], + "l3-interface-ipv6-address-list": [ + { + "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-37408", + "l3-interface-ipv6-prefix-length": 5116459, + "vlan-id-inner": 39229896, + "vlan-id-outer": 15091934, + "is-floating": true, + "neutron-network-id": "example-neutron-network-id-val-87700", + "neutron-subnet-id": "example-neutron-subnet-id-val-37352" + } + ] + } + ] + } + } + ] + }, + "vf-modules": { + "vf-module": [ + { + "vf-module-id": "example-vf-module-id-val-56249", + "vf-module-name": "example-vf-module-name-val-18987", + "heat-stack-id": "example-heat-stack-id-val-80110", + "orchestration-status": "example-orchestration-status-val-8226", + "is-base-vf-module": true, + "model-invariant-id": "example-model-invariant-id-val-5071", + "model-version-id": "example-model-version-id-val-80793", + "model-customization-id": "example-model-customization-id-val-83277", + "widget-model-id": "example-widget-model-id-val-99814", + "widget-model-version": "example-widget-model-version-val-22799", + "contrail-service-instance-fqdn": "example-contrail-service-instance-fqdn-val-52133", + "module-index": 1933, + "selflink": "example-selflink-val-69992" + } + ] + }, + "licenses": { + "license": [ + { + "group-uuid": "example-group-uuid-val-73012", + "resource-uuid": "example-resource-uuid-val-80045" + } + ] + }, + "entitlements": { + "entitlement": [ + { + "group-uuid": "example-group-uuid-val-14874", + "resource-uuid": "example-resource-uuid-val-49146" + } + ] + } + +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverFullQueryResponse.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverFullQueryResponse.json new file mode 100644 index 0000000000..1c7e1fb970 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverFullQueryResponse.json @@ -0,0 +1,13 @@ +{ + "in-maint": null, + "is-closed-loop-disabled": null, + "linterfaces": null, + "prov-status": null, + "relationship-list": null, + "resource-version": null, + "volumes": null, + "vserver-id": "VServerId", + "vserver-name": "VServerName", + "vserver-name2": "VServerName2", + "vserver-selflink": "http://VSERVER-link.com" + }
\ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverQueryResponse.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverQueryResponse.json new file mode 100644 index 0000000000..eca735b810 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverQueryResponse.json @@ -0,0 +1,6 @@ +{ + "vserverId": "VServerId", + "vserverName": "VServerName", + "vserverName2": "VServerName2", + "vserverSelflink": "http://VSERVER-link.com" + }
\ No newline at end of file diff --git a/common/pom.xml b/common/pom.xml index a52897170a..2553038e6b 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -186,6 +186,11 @@ <version>${grpc.version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.javatuples</groupId> + <artifactId>javatuples</artifactId> + <version>1.2</version> + </dependency> </dependencies> <dependencyManagement> diff --git a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java index 4ca5690188..8ef08057e6 100644 --- a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java +++ b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java @@ -35,11 +35,12 @@ public class DefaultDmaapPropertiesImpl implements DmaapProperties { public DefaultDmaapPropertiesImpl() throws IOException { File initialFile = new File("src/test/resources/dmaap.properties"); - InputStream targetStream = new FileInputStream(initialFile); Properties properties = new Properties(); - properties.load(targetStream); - this.properties = new HashMap<>(); - properties.forEach((key, value) -> this.properties.put((String) key, (String) value)); + try (InputStream targetStream = new FileInputStream(initialFile)) { + properties.load(targetStream); + this.properties = new HashMap<>(); + properties.forEach((key, value) -> this.properties.put((String) key, (String) value)); + } } @Override diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java b/common/src/main/java/org/onap/so/listener/ListenerRunner.java index 3c36052dca..a489be6070 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java +++ b/common/src/main/java/org/onap/so/listener/ListenerRunner.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.listener; +package org.onap.so.listener; import java.lang.annotation.Annotation; import java.util.Comparator; @@ -27,7 +27,6 @@ import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Priority; -import org.onap.so.client.exception.ExceptionBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -36,10 +35,7 @@ public abstract class ListenerRunner { @Autowired protected ApplicationContext context; - @Autowired - protected ExceptionBuilder exceptionBuilder; - - protected <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) { + public <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) { return validators.stream().filter(item -> { return !item.getClass().isAnnotationPresent(Skip.class) && predicate.test(item); }).sorted(Comparator.comparing(item -> { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java b/common/src/main/java/org/onap/so/listener/Skip.java index a0543fd3cc..aa3ec2a204 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java +++ b/common/src/main/java/org/onap/so/listener/Skip.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.common.listener; +package org.onap.so.listener; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java index 9fceed1641..a72229a25c 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java @@ -57,6 +57,9 @@ public class RequestParameters implements Serializable { @JsonProperty("rebuildVolumeGroups") private Boolean rebuildVolumeGroups; + @JsonProperty("enforceValidNfValues") + private Boolean enforceValidNfValues = false; + @Override public String toString() { return new ToStringBuilder(this).append("subscriptionServiceType", subscriptionServiceType) @@ -64,7 +67,15 @@ public class RequestParameters implements Serializable { .append("usePreload", usePreload).append("autoBuildVfModules", autoBuildVfModules) .append("cascadeDelete", cascadeDelete).append("testApi", testApi) .append("retainAssignments", retainAssignments).append("rebuildVolumeGroups", rebuildVolumeGroups) - .toString(); + .append("enforceValidNfValues", enforceValidNfValues).toString(); + } + + public Boolean getEnforceValidNfValues() { + return enforceValidNfValues; + } + + public void setEnforceValidNfValues(Boolean enforceValidNfValues) { + this.enforceValidNfValues = enforceValidNfValues; } public String getSubscriptionServiceType() { diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java index c7f6459482..ab2ce10690 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java @@ -29,7 +29,7 @@ public abstract class ApiException extends Exception { * */ private static final long serialVersionUID = 683162058616691134L; - private int httpResponseCode; + private int httpResponseCode = 500; private String messageID; private ErrorLoggerInfo errorLoggerInfo; @@ -49,6 +49,15 @@ public abstract class ApiException extends Exception { super(message, cause); } + public ApiException(String message, int httpResponseCode) { + super(message); + this.httpResponseCode = httpResponseCode; + } + + public ApiException(String message) { + super(message); + } + public String getMessageID() { return messageID; } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java index 66b86a6961..6a56b58f04 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java @@ -70,7 +70,7 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> { @Override public Response toResponse(ApiException exception) { - + logger.error("Error During API Call", exception); return Response.status(exception.getHttpResponseCode()).entity(buildErrorString(exception)).build(); } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java index 372ed30d8e..ae8256e64f 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java @@ -28,6 +28,11 @@ public class ValidateException extends ApiException { } + public ValidateException(String errorMessage, int httpResponseCode) { + super(errorMessage, httpResponseCode); + } + + public static class Builder extends ApiException.Builder<Builder> { public Builder(String message, int httpResponseCode, String messageID) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index 451fa64585..e56eb422d8 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 @@ -115,7 +115,7 @@ public class CamundaRequestHandler { List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody(); - if (historicProcessInstanceList != null) { + if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) { Collections.reverse(historicProcessInstanceList); processInstanceId = historicProcessInstanceList.get(0).getId(); } else { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index 6f36fb2aff..a5ccb1b29b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -42,6 +42,7 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.EnumUtils; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; @@ -411,7 +412,11 @@ public class OrchestrationRequests { protected String mapRequestStatusToRequest(InfraActiveRequests iar, String format) { if (iar.getRequestStatus() != null) { - if (!StringUtils.isBlank(format) && OrchestrationRequestFormat.DETAIL.toString().equalsIgnoreCase(format)) { + boolean requestFormat = false; + if (format != null) { + requestFormat = EnumUtils.isValidEnum(OrchestrationRequestFormat.class, format.toUpperCase()); + } + if (requestFormat) { return iar.getRequestStatus(); } else { if (Status.ABORTED.toString().equalsIgnoreCase(iar.getRequestStatus()) 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 b6f3f82ab1..2fddfd9a95 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -479,24 +479,11 @@ public class RequestHandlerUtils extends AbstractRestHandler { boolean isAlaCarte, Actions action) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); - if (msoRawRequest != null) { - ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); - if (serviceInstRequest != null && serviceInstRequest.getRequestDetails() != null - && serviceInstRequest.getRequestDetails().getRequestParameters() != null) { - if (!isAlaCarte && Action.createInstance.equals(action)) { - sir.getRequestDetails() - .setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); - sir.getRequestDetails().getRequestParameters().setUserParams( - serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); - } - sir.getRequestDetails().getRequestParameters() - .setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload()); - } - - logger.debug("Value as string: {}", mapper.writeValueAsString(sir)); - return mapper.writeValueAsString(sir); + if (serviceInstRequest != null) { + return mapper.writeValueAsString(serviceInstRequest); + } else { + return msoRawRequest; } - return null; } public Optional<String> retrieveModelName(RequestParameters requestParams) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 5b827d9cf8..b1d38983ec 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 @@ -51,6 +51,7 @@ import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler; +import org.onap.so.apihandlerinfra.infra.rest.validators.RequestValidatorListenerRunner; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.constants.Status; import org.onap.so.db.catalog.beans.NetworkResource; @@ -124,6 +125,9 @@ public class ServiceInstances extends AbstractRestHandler { @Autowired private RequestHandlerUtils requestHandlerUtils; + @Autowired + private RequestValidatorListenerRunner requestValidatorListenerRunner; + @POST @Path("/{version:[vV][5-7]}/serviceInstances") @Consumes(MediaType.APPLICATION_JSON) @@ -764,6 +768,13 @@ public class ServiceInstances extends AbstractRestHandler { public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { + return serviceInstances(requestJSON, action, instanceIdMap, version, requestId, requestUri, null); + + } + + public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, + String version, String requestId, String requestUri, HashMap<String, String> queryParams) + throws ApiException { String serviceInstanceId; Boolean aLaCarte = null; ServiceInstancesRequest sir; @@ -771,6 +782,8 @@ public class ServiceInstances extends AbstractRestHandler { sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); action = handleReplaceInstance(action, sir); + requestValidatorListenerRunner.runValidations(requestUri, instanceIdMap, sir, queryParams); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java new file mode 100644 index 0000000000..344e5438c9 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java @@ -0,0 +1,85 @@ +package org.onap.so.apihandlerinfra.infra.rest; + +import java.util.Optional; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VolumeGroup; +import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class AAIDataRetrieval { + + private static final String VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID = "VF Module Not Found In Inventory, VnfId: "; + + private AAIResourcesClient aaiResourcesClient; + + private static final Logger logger = LoggerFactory.getLogger(AAIDataRetrieval.class); + + public ServiceInstance getServiceInstance(String serviceInstanceId) { + return this.getAaiResourcesClient() + .get(ServiceInstance.class, + AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) + .orElseGet(() -> { + logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); + return null; + }); + } + + + public VfModule getAAIVfModule(String vnfId, String vfModuleId) { + return this.getAaiResourcesClient() + .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) + .orElseGet(() -> { + logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); + return null; + }); + } + + public GenericVnf getGenericVnf(String vnfId) { + return this.getAaiResourcesClient() + .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) + .orElseGet(() -> { + logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); + return null; + }); + } + + public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { + AAIResultWrapper wrapper = + this.getAaiResourcesClient().get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + .relatedTo(AAIObjectType.VOLUME_GROUP, volumeGroupId)); + Optional<VolumeGroup> volume = wrapper.asBean(VolumeGroup.class); + if (volume.isPresent()) { + return volume.get(); + } else { + logger.debug("No VolumeGroup in A&AI found: {}", vnfId); + return null; + } + } + + public L3Network getNetwork(String networkId) { + return this.getAaiResourcesClient() + .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) + .orElseGet(() -> { + logger.debug("No Network found in A&AI NetworkId: {}", networkId); + return null; + }); + } + + protected AAIResourcesClient getAaiResourcesClient() { + if (aaiResourcesClient == null) { + aaiResourcesClient = new AAIResourcesClient(); + } + return aaiResourcesClient; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java index bb5b4edfe4..ee2bb586cf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java @@ -33,10 +33,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException; import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.constants.Status; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -75,17 +72,19 @@ public class BpmnRequestBuilder { @Autowired private RequestsDbClient infraActiveRequestsClient; + @Autowired + private AAIDataRetrieval aaiDataRet; + private ObjectMapper mapper = new ObjectMapper(); - private AAIResourcesClient aaiResourcesClient; public ServiceInstancesRequest buildVFModuleDeleteRequest(String vnfId, String vfModuleId, ModelType modelType) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } - VfModule vfModule = getAAIVfModule(vnfId, vfModuleId); + VfModule vfModule = aaiDataRet.getAAIVfModule(vnfId, vfModuleId); if (vfModule == null) { throw new AAIEntityNotFound(VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " vfModuleId: " + vfModuleId); } @@ -94,11 +93,11 @@ public class BpmnRequestBuilder { public ServiceInstancesRequest buildVolumeGroupDeleteRequest(String vnfId, String volumeGroupId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } - VolumeGroup volumeGroup = getVolumeGroup(vnfId, volumeGroupId); + VolumeGroup volumeGroup = aaiDataRet.getVolumeGroup(vnfId, volumeGroupId); if (volumeGroup == null) { throw new AAIEntityNotFound( VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); @@ -107,7 +106,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildServiceDeleteRequest(String serviceInstanceId) throws AAIEntityNotFound { - ServiceInstance serviceInstance = getServiceInstance(serviceInstanceId); + ServiceInstance serviceInstance = aaiDataRet.getServiceInstance(serviceInstanceId); if (serviceInstance == null) { throw new AAIEntityNotFound( "ServiceInstance Not Found In Inventory, ServiceInstanceId: " + serviceInstanceId); @@ -116,7 +115,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildVnfDeleteRequest(String vnfId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); + GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId); if (vnf == null) { throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId); } @@ -124,7 +123,7 @@ public class BpmnRequestBuilder { } public ServiceInstancesRequest buildNetworkDeleteRequest(String networkId) throws AAIEntityNotFound { - L3Network network = getNetwork(networkId); + L3Network network = aaiDataRet.getNetwork(networkId); if (network == null) { throw new AAIEntityNotFound("Network Not Found In Inventory, NetworkId: " + networkId); } @@ -407,72 +406,5 @@ public class BpmnRequestBuilder { return requestParams; } - public VfModule getAAIVfModule(String vnfId, String vfModuleId) { - return this.getAaiResourcesClient() - .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) - .orElseGet(() -> { - logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId); - return null; - }); - } - - public GenericVnf getGenericVnf(String vnfId) { - return this.getAaiResourcesClient() - .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) - .orElseGet(() -> { - logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId); - return null; - }); - } - - public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound { - GenericVnf vnf = getGenericVnf(vnfId); - AAIResultWrapper wrapper = new AAIResultWrapper(vnf); - List<AAIResourceUri> listVserverWrapper; - Optional<AAIResourceUri> volumeGroupURI; - if (wrapper.getRelationships().isPresent()) { - listVserverWrapper = wrapper.getRelationships().get().getRelatedUris(AAIObjectType.VOLUME_GROUP); - volumeGroupURI = listVserverWrapper.stream() - .filter(resourceURI -> resourceURI.getURIKeys().get("volume-group-id").equals(volumeGroupId)) - .findFirst(); - } else { - throw new AAIEntityNotFound( - VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId); - } - return this.getAaiResourcesClient().get(VolumeGroup.class, volumeGroupURI.get()).orElseGet(() -> { - logger.debug("No VolumeGroup in A&AI found: {}", vnfId); - return null; - }); - } - - public ServiceInstance getServiceInstance(String serviceInstanceId) { - return this.getAaiResourcesClient() - .get(ServiceInstance.class, - AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId)) - .orElseGet(() -> { - logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId); - return null; - }); - } - - public L3Network getNetwork(String networkId) { - return this.getAaiResourcesClient() - .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId)) - .orElseGet(() -> { - logger.debug("No Network found in A&AI NetworkId: {}", networkId); - return null; - }); - } - - public AAIResourcesClient getAaiResourcesClient() { - if (aaiResourcesClient == null) { - aaiResourcesClient = new AAIResourcesClient(); - } - return aaiResourcesClient; - } - - public void setAaiResourcesClient(AAIResourcesClient aaiResourcesClient) { - this.aaiResourcesClient = aaiResourcesClient; - } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java new file mode 100644 index 0000000000..4aa60152dd --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra.infra.rest.validators; + +import java.util.Map; +import java.util.Optional; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; + +public interface RequestValidator { + + + /** + * Should this validator run for given request + * + * @return + */ + public boolean shouldRunFor(String uri, ServiceInstancesRequest request); + + + public Optional<String> validate(Map<String, String> instanceIdMap, ServiceInstancesRequest request, + Map<String, String> queryParams); +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java new file mode 100644 index 0000000000..d689c6b7a5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra.infra.rest.validators; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.javatuples.Pair; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.listener.ListenerRunner; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +@Component +public class RequestValidatorListenerRunner extends ListenerRunner { + + private static Logger logger = LoggerFactory.getLogger(RequestValidatorListenerRunner.class); + + protected List<RequestValidator> requestValidators; + + @PostConstruct + protected void init() { + requestValidators = new ArrayList<>( + Optional.ofNullable(context.getBeansOfType(RequestValidator.class)).orElse(new HashMap<>()).values()); + } + + public boolean runValidations(String requestURI, Map<String, String> instanceIdMap, ServiceInstancesRequest request, + Map<String, String> queryParams) throws ApiException { + logger.info("Running local validations"); + List<Pair<String, Optional<String>>> results = + runValidations(requestValidators, instanceIdMap, request, queryParams, requestURI); + if (!results.isEmpty()) { + throw new ValidateException("Failed Validations:\n" + + results.stream().map(item -> String.format("%s: %s", item.getValue0(), item.getValue1().get())) + .collect(Collectors.joining("\n")), + 400); + } + + return true; + } + + protected List<Pair<String, Optional<String>>> runValidations(List<? extends RequestValidator> validators, + Map<String, String> instanceIdMap, ServiceInstancesRequest request, Map<String, String> queryParams, + String requestURI) { + + List<? extends RequestValidator> filtered = + filterListeners(validators, (item -> item.shouldRunFor(requestURI, request))); + + List<Pair<String, Optional<String>>> results = new ArrayList<>(); + filtered.forEach(item -> results + .add(new Pair<>(item.getClass().getName(), item.validate(instanceIdMap, request, queryParams)))); + + return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList()); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java index 71405b0f63..20be2b5a8b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java @@ -43,7 +43,8 @@ public class PlatformLOBValidation implements ValidationRule { platform = info.getSir().getRequestDetails().getPlatform(); lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness(); - if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) { + if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance + && !info.getReqParameters().getEnforceValidNfValues()) { if (reqVersion > 5 && platform == null) { throw new ValidationException("platform"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java index 584269715a..cebbd6389c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java @@ -41,10 +41,12 @@ public class ProjectOwningEntityValidation implements ValidationRule { String requestScope = info.getRequestScope(); Actions action = info.getAction(); + project = info.getSir().getRequestDetails().getProject(); owningEntity = info.getSir().getRequestDetails().getOwningEntity(); if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name()) - && action == Action.createInstance || action == Action.assignInstance) { + && !info.getReqParameters().getEnforceValidNfValues() && action == Action.createInstance + || action == Action.assignInstance) { if (reqVersion > 5 && owningEntity == null) { throw new ValidationException("owningEntity"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java index e6b5163f59..830f38f98b 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 @@ -30,6 +30,7 @@ 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; @@ -119,7 +120,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameTest() throws IOException { + public void getActivityNameTest() { String expectedActivityName = "Last task executed: BB to Execute"; String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); @@ -127,7 +128,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameNullActivityNameTest() throws IOException { + public void getActivityNameNullActivityNameTest() { String expectedActivityName = "Task name is null."; HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity(); List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); @@ -139,7 +140,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameNullListTest() throws IOException { + public void getActivityNameNullListTest() { String expectedActivityName = "No results returned on activityInstance history lookup."; List<HistoricActivityInstanceEntity> activityInstanceList = null; String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); @@ -148,7 +149,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getActivityNameEmptyListTest() throws IOException { + public void getActivityNameEmptyListTest() { String expectedActivityName = "No results returned on activityInstance history lookup."; List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>(); String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList); @@ -157,7 +158,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameTest() throws IOException, ContactCamundaException { + public void getTaskNameTest() throws ContactCamundaException { doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID); doReturn(activityInstanceResponse).when(camundaRequestHandler) .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID); @@ -170,7 +171,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException { + 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; @@ -181,7 +182,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException { + public void getTaskNameNullProcessInstanceIdTest() throws ContactCamundaException { HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity(); List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>(); processInstanceList.add(processInstance); @@ -196,7 +197,19 @@ public class CamundaRequestHandlerTest { } @Test - public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException { + 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); @@ -205,7 +218,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException { + public void getCamundaActivityHistoryTest() throws ContactCamundaException { HttpHeaders headers = setHeaders(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId=" @@ -239,7 +252,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException { + public void getCamundaProccesInstanceHistoryTest() { HttpHeaders headers = setHeaders(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); String targetUrl = @@ -292,7 +305,7 @@ public class CamundaRequestHandlerTest { } @Test - public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException { + public void getCamundaProccesInstanceHistoryFailThenSuccessTest() { HttpHeaders headers = setHeaders(); HttpEntity<?> requestEntity = new HttpEntity<>(headers); String targetUrl = @@ -310,7 +323,7 @@ public class CamundaRequestHandlerTest { } @Test - public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + public void setCamundaHeadersTest() { String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password String key = "07a7159d3bf51a0e53be7a8f89699be7"; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java index 5023155768..f672648a6b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java @@ -295,6 +295,14 @@ public class OrchestrationRequestsUnitTest { assertEquals(Status.ABORTED.toString(), result); } + @Test + public void mapRequestStatusToRequestForFormatStatusDetailTest() throws ApiException { + iar.setRequestStatus(Status.ABORTED.toString()); + String result = orchestrationRequests.mapRequestStatusToRequest(iar, "statusDetail"); + + assertEquals(Status.ABORTED.toString(), result); + } + @Test public void mapRequestStatusToRequestForFormatEmptyStringTest() throws ApiException { diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index e28e36d307..a79aeb2bd7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -2934,15 +2934,5 @@ public class ServiceInstancesTest extends BaseTest { Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir); assertEquals(Action.replaceInstanceRetainAssignments, action); } - /* - * @Test public void buildSelfLinkUrlTest() throws Exception { // v - version String incomingUrl = - * "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; String expectedSelfLink = - * "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; String requestId = - * "efce3167-5e45-4666-9d4d-22e23648e5d1"; Optional<URL> actualSelfLinkUrl = buildSelfLinkUrl(incomingUrl, - * requestId); assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); // V - Version String - * incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; String - * expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - * Optional<URL> actualSelfLinkUrlV = buildSelfLinkUrl(incomingUrlV, requestId); assertEquals(expectedSelfLinkV, - * actualSelfLinkUrlV.get().toString()); } - */ } + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java index 3644dd8e7f..f73da49e0d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java @@ -23,6 +23,7 @@ package org.onap.so.apihandlerinfra.infra.rest; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import java.io.File; import java.util.Optional; import org.junit.Before; @@ -32,7 +33,6 @@ import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.ServiceInstance; @@ -40,6 +40,7 @@ import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.so.db.request.client.RequestsDbClient; @@ -55,15 +56,19 @@ public class BpmnRequestBuilderTest { @Rule public ExpectedException exceptionRule = ExpectedException.none(); + + @Mock + private AAIResourcesClient aaiResourcesClient; + @InjectMocks - @Spy - BpmnRequestBuilder reqBuilder; + private AAIDataRetrieval aaiData = spy(AAIDataRetrieval.class); @Mock private RequestsDbClient requestDBClient; - @Mock - private AAIResourcesClient aaiResourcesClient; + @InjectMocks + private BpmnRequestBuilder reqBuilder = spy(BpmnRequestBuilder.class); + private ObjectMapper mapper = new ObjectMapper(); @@ -71,8 +76,7 @@ public class BpmnRequestBuilderTest { @Before public void setup() { - reqBuilder.setAaiResourcesClient(aaiResourcesClient); - + // aaiData.setAaiResourcesClient(aaiResourcesClient); } @Test @@ -80,11 +84,11 @@ public class BpmnRequestBuilderTest { ServiceInstance service = provider.getMapper().readValue(new File(RESOURCE_PATH + "ServiceInstance.json"), ServiceInstance.class); - doReturn(service).when(reqBuilder).getServiceInstance("serviceId"); + doReturn(service).when(aaiData).getServiceInstance("serviceId"); ServiceInstancesRequest expectedRequest = mapper .readValue(new File(RESOURCE_PATH + "ExpectedServiceRequest.json"), ServiceInstancesRequest.class); - expectedRequest.getRequestDetails().getModelInfo().setModelId(null); - // bad getter/setter setting multiple fields + expectedRequest.getRequestDetails().getModelInfo().setModelId(null); // bad getter/setter setting multiple + // fields ServiceInstancesRequest actualRequest = reqBuilder.buildServiceDeleteRequest("serviceId"); assertThat(actualRequest, sameBeanAs(expectedRequest)); } @@ -128,13 +132,16 @@ public class BpmnRequestBuilderTest { AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")); VolumeGroup volumeGroup = provider.getMapper().readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class); - - doReturn(Optional.of(volumeGroup)).when(aaiResourcesClient).get(VolumeGroup.class, AAIUriFactory - .createResourceUri(AAIObjectType.VOLUME_GROUP, "cloudOwner", "regionOne", "volumeGroupId")); + AAIResultWrapper wrapper = new AAIResultWrapper(volumeGroup); + doReturn(wrapper).when(aaiResourcesClient) + .get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId") + .relatedTo(AAIObjectType.VOLUME_GROUP, "volumeGroupId")); ServiceInstancesRequest expectedRequest = mapper .readValue(new File(RESOURCE_PATH + "ExpectedVolumeGroupRequest.json"), ServiceInstancesRequest.class); ServiceInstancesRequest actualRequest = reqBuilder.buildVolumeGroupDeleteRequest("vnfId", "volumeGroupId"); assertThat(actualRequest, sameBeanAs(expectedRequest)); } + } + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json new file mode 100644 index 0000000000..a6aa3e1c25 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json @@ -0,0 +1,33 @@ +{ + "serviceInstanceId":"1882939", + "vnfInstanceId":"1882938", + "networkInstanceId":"1882937", + "volumeGroupInstanceId":"1882935", + "vfModuleInstanceId":"1882934", + "requestDetails": { + "requestInfo": { + "source": "VID", + "requestorId": "xxxxxx", + "instanceName": "testService9" + }, + "requestParameters": { + "aLaCarte": true, + "autoBuildVfModules": false, + "subscriptionServiceType": "test", + "disableOwningEntityProject": true + }, + "modelInfo":{ + "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965", + "modelVersion":"1", + "modelVersionId":"10", + "modelType":"service", + "modelName":"serviceModel", + "modelInstanceName":"modelInstanceName", + "modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796" + }, + "subscriberInfo": { + "globalSubscriberId": "someTestId", + "subscriberName": "someTestId" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json index 09f6d81da3..0b03f56caa 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json @@ -101,7 +101,7 @@ }, { "relationship-key": "volume-group.volume-group-id", - "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6" + "relationship-value": "volumeGroupId" } ] }, diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index 731d2bec4d..ee53e491a4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -1111,6 +1111,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java index 36c9251d59..aec1c7fb22 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java @@ -23,9 +23,7 @@ package org.onap.so.db.catalog.beans; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; -import java.util.HashSet; import java.util.List; -import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -34,7 +32,6 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; @@ -124,6 +121,9 @@ public class VnfResourceCustomization implements Serializable { @Column(name = "VNFCINSTANCEGROUP_ORDER") private String vnfcInstanceGroupOrder; + @Column(name = "NF_DATA_VALID") + private Boolean nfDataValid; + @Override public boolean equals(final Object other) { if (!(other instanceof VnfResourceCustomization)) { @@ -336,4 +336,14 @@ public class VnfResourceCustomization implements Serializable { public void setVnfcInstanceGroupOrder(String vnfcInstanceGroupOrder) { this.vnfcInstanceGroupOrder = vnfcInstanceGroupOrder; } + + public Boolean getNfDataValid() { + return nfDataValid; + } + + public void setNfDataValid(Boolean nfDataValid) { + this.nfDataValid = nfDataValid; + } + + } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java index a959f2f5a1..23539b074d 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java @@ -27,7 +27,9 @@ import java.util.List; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.persistence.EntityNotFoundException; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; +import org.apache.http.HttpStatus; import org.onap.so.db.catalog.beans.BuildingBlockDetail; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.CloudifyManager; @@ -67,13 +69,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import com.google.common.base.Strings; import uk.co.blackpepper.bowman.Client; import uk.co.blackpepper.bowman.ClientFactory; import uk.co.blackpepper.bowman.Configuration; @@ -888,6 +895,90 @@ public class CatalogDbClient { "Unable to find CvnfcConfigurationCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid); } + public org.onap.so.rest.catalog.beans.Service getServiceModelInformation(String serviceModelUUID, String depth) { + if (Strings.isNullOrEmpty(serviceModelUUID)) { + throw new EntityNotFoundException("Service Model UUID passed as Null or Empty String"); + } + try { + HttpEntity<?> entity = getHttpEntity(); + return restTemplate.exchange( + UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID) + .queryParam("depth", depth).build().encode().toString(), + HttpMethod.GET, entity, org.onap.so.rest.catalog.beans.Service.class).getBody(); + } catch (HttpClientErrorException e) { + logger.warn("Entity Not found in DLP", e); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException("Unable to find Service with ServiceModelUUID:" + serviceModelUUID); + } + throw e; + } + } + + public List<org.onap.so.rest.catalog.beans.Service> getServices() { + try { + HttpEntity<?> entity = getHttpEntity(); + return restTemplate + .exchange( + UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services").build() + .encode().toString(), + HttpMethod.GET, entity, + new ParameterizedTypeReference<List<org.onap.so.rest.catalog.beans.Service>>() {}) + .getBody(); + } catch (HttpClientErrorException e) { + logger.error("Error Calling catalog database", e); + throw e; + } + } + + public org.onap.so.rest.catalog.beans.Vnf getVnfModelInformation(String serviceModelUUID, + String vnfCustomizationUUID, String depth) { + if (Strings.isNullOrEmpty(serviceModelUUID)) { + throw new EntityNotFoundException("Service Model UUID passed as Null or Empty String"); + } + if (Strings.isNullOrEmpty(vnfCustomizationUUID)) { + throw new EntityNotFoundException("Vnf Customization UUID passed as Null or Empty String"); + } + try { + HttpEntity<?> entity = getHttpEntity(); + return restTemplate + .exchange( + UriComponentsBuilder + .fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID + + "/vnfs/" + vnfCustomizationUUID) + .queryParam("depth", depth).build().encode().toString(), + HttpMethod.GET, entity, org.onap.so.rest.catalog.beans.Vnf.class) + .getBody(); + } catch (HttpClientErrorException e) { + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException( + "Unable to find Vnf with Vnf Customization UUID:" + vnfCustomizationUUID); + } + throw e; + } + } + + public void updateVnf(String serviceModelUUID, org.onap.so.rest.catalog.beans.Vnf vnf) { + if (vnf == null) { + throw new EntityNotFoundException("Vnf passed as null"); + } + try { + HttpHeaders headers = getHttpHeaders(); + HttpEntity<org.onap.so.rest.catalog.beans.Vnf> entity = new HttpEntity<>(vnf, headers); + + restTemplate.exchange( + UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID + + "/vnfs/" + vnf.getModelCustomizationId()).build().encode().toString(), + HttpMethod.PUT, entity, org.onap.so.rest.catalog.beans.Vnf.class).getBody(); + } catch (HttpClientErrorException e) { + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException( + "Unable to find Vnf with Vnf Customization UUID:" + vnf.getModelCustomizationId()); + } + throw e; + } + } + + public Workflow findWorkflowByArtifactUUID(String artifactUUID) { return this.getSingleResource(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByArtifactUUID) .queryParam(ARTIFACT_UUID, artifactUUID).build().toString())); @@ -910,4 +1001,18 @@ public class CatalogDbClient { public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + private HttpHeaders getHttpHeaders() { + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.AUTHORIZATION, msoAdaptersAuth); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + headers.set(LogConstants.TARGET_ENTITY_HEADER, TARGET_ENTITY); + return headers; + } + + private HttpEntity<?> getHttpEntity() { + HttpHeaders headers = getHttpHeaders(); + return new HttpEntity<>(headers); + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java new file mode 100644 index 0000000000..e22f366ddf --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest.catalog.beans; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import org.apache.commons.lang3.builder.ToStringBuilder; + +@JsonInclude(Include.NON_DEFAULT) +public class Cvnfc { + + private String modelCustomizationId; + private String modelInstanceName; + private String modelVersionId; + private String modelInvariantId; + private String modelVersion; + private String modelName; + private String description; + private String nfcFunction; + private String nfcNamingCode; + + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") + private Date created; + + public String getModelCustomizationId() { + return modelCustomizationId; + } + + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + public String getModelInstanceName() { + return modelInstanceName; + } + + public void setModelInstanceName(String modelInstanceName) { + this.modelInstanceName = modelInstanceName; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getModelVersion() { + return modelVersion; + } + + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + public String getModelName() { + return modelName; + } + + public void setModelName(String modelName) { + this.modelName = modelName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getNfcFunction() { + return nfcFunction; + } + + public void setNfcFunction(String nfcFunction) { + this.nfcFunction = nfcFunction; + } + + public String getNfcNamingCode() { + return nfcNamingCode; + } + + public void setNfcNamingCode(String nfcNamingCode) { + this.nfcNamingCode = nfcNamingCode; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + + + @Override + public String toString() { + return new ToStringBuilder(this).append("modelCustomizationId", modelCustomizationId) + .append("modelInstanceName", modelInstanceName).append("modelVersionId", modelVersionId) + .append("modelInvariantId", modelInvariantId).append("modelVersion", modelVersion) + .append("modelName", modelName).append("description", description).append("nfcFunction", nfcFunction) + .append("nfcNamingCode", nfcNamingCode).append("created", created).toString(); + } + +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java index 1620058e1e..11089046fd 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java @@ -24,6 +24,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -40,6 +41,7 @@ public class Service implements Serializable { private String modelInvariantId; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") private Date created; private String modelVersion; diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java index 8e18f94faf..f2a2c77aca 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java @@ -20,9 +20,11 @@ package org.onap.so.rest.catalog.beans; +import java.util.ArrayList; import java.util.Date; import java.util.List; import org.onap.so.db.catalog.beans.HeatEnvironment; +import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -37,6 +39,7 @@ public class VfModule { private String description; private Boolean isBase; private HeatTemplate heatTemplate; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") private Date created; private List<HeatFile> heatFile; @@ -50,9 +53,7 @@ public class VfModule { private HeatEnvironment heatEnv; private Boolean isVolumeGroup; - - // Add in cvnfcCustomization - + private List<Cvnfc> vnfc = new ArrayList<>(); public String getModelName() { @@ -191,6 +192,12 @@ public class VfModule { this.isVolumeGroup = isVolumeGroup; } + public List<Cvnfc> getVnfc() { + return vnfc; + } + public void setVnfc(List<Cvnfc> vnfc) { + this.vnfc = vnfc; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java index 40d701c3c5..febf69baf1 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java +++ b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java @@ -47,12 +47,14 @@ public class Vnf implements Serializable { private String nfFunction; private String nfRole; private String nfNamingCode; + private String nfType; private String multiStageDesign; private String orchestrationMode; private String cloudVersionMin; private String cloudVersionMax; private String category; private String subCategory; + private Boolean nfDataValid; private List<VfModule> vfModule = new ArrayList<>(); public List<VfModule> getVfModule() { @@ -215,4 +217,21 @@ public class Vnf implements Serializable { public void setMultiStageDesign(String multiStepDesign) { this.multiStageDesign = multiStepDesign; } + + public String getNfType() { + return nfType; + } + + public void setNfType(String nfType) { + this.nfType = nfType; + } + + public Boolean getNfDataValid() { + return nfDataValid; + } + + public void setNfDataValid(Boolean nfDataValid) { + this.nfDataValid = nfDataValid; + } + } diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java index 612963d35b..8bf47e71d3 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java @@ -37,6 +37,7 @@ public class VnfcCustomizationRepositoryTest extends BaseTest { private VnfcCustomizationRepository vnfcCustomizationRepository; @Test + @Transactional public void findAllTest() throws Exception { List<VnfcCustomization> vnfcCustomizationList = vnfcCustomizationRepository.findAll(); Assert.assertFalse(CollectionUtils.isEmpty(vnfcCustomizationList)); diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index 7cd13a3780..7468f62ecb 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -1109,6 +1109,7 @@ CREATE TABLE `vnf_resource_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), diff --git a/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/SvnfmServiceTest.java b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/SvnfmServiceTest.java new file mode 100644 index 0000000000..ed77775421 --- /dev/null +++ b/vnfm-simulator/vnfm-service/src/test/java/org/onap/svnfm/simulator/services/SvnfmServiceTest.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Nokia. + * ================================================================================ + * 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.svnfm.simulator.services; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.junit.Before; +import org.junit.Test; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.InlineResponse201; +import org.onap.svnfm.simulator.config.ApplicationConfig; +import org.onap.svnfm.simulator.constants.Constant; +import org.onap.svnfm.simulator.model.Vnfds; +import org.onap.svnfm.simulator.repository.VnfOperationRepository; +import org.onap.svnfm.simulator.repository.VnfmRepository; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.support.SimpleValueWrapper; + +public class SvnfmServiceTest { + + private SvnfmService testedObject; + private CacheManager cacheManagerMock; + + @Before + public void setup() { + VnfmRepository vnfmRepositoryMock = mock(VnfmRepository.class); + VnfOperationRepository vnfOperationRepositoryMock = mock(VnfOperationRepository.class); + VnfmHelper vnfmHelperMock = mock(VnfmHelper.class); + ApplicationConfig applicationConfigMock = mock(ApplicationConfig.class); + cacheManagerMock = mock(CacheManager.class); + Vnfds vnfdsMock = mock(Vnfds.class); + SubscriptionService subscriptionServiceMock = mock(SubscriptionService.class); + + testedObject = new SvnfmService(vnfmRepositoryMock, vnfOperationRepositoryMock, vnfmHelperMock, + applicationConfigMock, cacheManagerMock, vnfdsMock, subscriptionServiceMock); + } + + @Test + public void getVnfSuccessful() { + // given + String vnfId = "vnfId"; + String vnfInstanceName = "testVnf"; + Cache cacheMock = mock(Cache.class); + SimpleValueWrapper simpleValueWrapperMock = mock(SimpleValueWrapper.class); + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(cacheMock); + when(cacheMock.get(vnfId)).thenReturn(simpleValueWrapperMock); + when(simpleValueWrapperMock.get()).thenReturn(prepareInlineResponse(vnfId, vnfInstanceName)); + // when + InlineResponse201 result = testedObject.getVnf(vnfId); + // then + assertThat(result.getVnfdId()).isEqualTo(vnfId); + assertThat(result.getVnfInstanceName()).isEqualTo(vnfInstanceName); + } + + @Test + public void getVnf_ifCacheNullThenReturnNull() { + // given + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(null); + // then + assertThat(testedObject.getVnf("any")).isNull(); + } + + @Test + public void getVnf_ifWrapperNullThenReturnNull() { + // given + String vnfId = "vnfId"; + Cache cacheMock = mock(Cache.class); + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(cacheMock); + when(cacheMock.get(vnfId)).thenReturn(null); + // then + assertThat(testedObject.getVnf(vnfId)).isNull(); + } + + @Test + public void getVnf_ifResultIsNullThenReturnNull() { + // when + String vnfId = "vnfId"; + Cache cacheMock = mock(Cache.class); + SimpleValueWrapper simpleValueWrapperMock = mock(SimpleValueWrapper.class); + when(cacheManagerMock.getCache(Constant.IN_LINE_RESPONSE_201_CACHE)).thenReturn(cacheMock); + when(cacheMock.get(vnfId)).thenReturn(simpleValueWrapperMock); + when(simpleValueWrapperMock.get()).thenReturn(null); + // then + assertThat(testedObject.getVnf(vnfId)).isNull(); + } + + private InlineResponse201 prepareInlineResponse(String vnfId, String vnfInstanceName) { + InlineResponse201 response201 = new InlineResponse201(); + response201.setVnfdId(vnfId); + response201.vnfInstanceName(vnfInstanceName); + return response201; + } +} |