diff options
Diffstat (limited to 'adapters')
43 files changed, 1741 insertions, 580 deletions
diff --git a/adapters/etsi-sol002-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java b/adapters/etsi-sol002-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java index 3995185f23..f326d92927 100644 --- a/adapters/etsi-sol002-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java +++ b/adapters/etsi-sol002-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java @@ -25,11 +25,22 @@ import java.util.LinkedList; import java.util.List; import java.util.Optional; import org.apache.logging.log4j.util.Strings; -import org.onap.aai.domain.yang.*; -import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.GenericVnfs; +import org.onap.aai.domain.yang.RelatedToProperty; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aai.domain.yang.Vserver; import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.aaiclient.client.graphinventory.entities.uri.Depth; import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.slf4j.Logger; @@ -104,7 +115,7 @@ public class AaiConnection { } private List<EsrSystemInfo> receiveVnfmInternal() { - final AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST); + final AAIPluralResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.externalSystem().esrVnfmList()); final Optional<EsrVnfmList> response = getResourcesClient().get(EsrVnfmList.class, resourceUri); if (response.isPresent()) { @@ -127,7 +138,7 @@ public class AaiConnection { private List<EsrSystemInfo> receiveVnfmServiceUrl(final String vnfmId) { final Optional<EsrVnfm> response = getResourcesClient().get(EsrVnfm.class, - AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId).depth(Depth.ONE)); + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.externalSystem().esrVnfm(vnfmId)).depth(Depth.ONE)); if (response.isPresent()) { final EsrVnfm esrVnfm = response.get(); @@ -143,8 +154,8 @@ public class AaiConnection { } public String receiveGenericVnfId(final String href) { - final AAIResourceUri resourceUri = - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNFS).queryParam(SELFLINK, href); + final AAIPluralResourceUri resourceUri = + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnfs()).queryParam(SELFLINK, href); final Optional<GenericVnfs> response = getResourcesClient().get(GenericVnfs.class, resourceUri); if (response.isPresent()) { @@ -165,7 +176,7 @@ public class AaiConnection { } public String receiveVserverName(final String genericId) { - final AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericId); + final AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericId)); final Optional<GenericVnf> response = getResourcesClient().get(GenericVnf.class, resourceUri); if (response.isPresent()) { @@ -199,7 +210,7 @@ public class AaiConnection { private String receiveVserverNameFromParams(final String cloudOwner, final String cloudId, final String tenantId, final String vserverId) { final AAIResourceUri resourceUri = - AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudId, tenantId, vserverId); + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudId).tenant(tenantId).vserver(vserverId)); final Optional<Vserver> response = getResourcesClient().get(Vserver.class, resourceUri); if (response.isPresent()) { diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java index d9450b3472..8f95d8ab85 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/main/java/org/onap/so/adapters/etsisol003adapter/lcm/extclients/aai/AaiServiceProviderImpl.java @@ -26,8 +26,8 @@ import org.onap.aai.domain.yang.EsrVnfmList; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.GenericVnfs; import org.onap.aai.domain.yang.Vserver; -import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.aaiclient.client.graphinventory.entities.uri.Depth; import org.onap.so.adapters.etsisol003adapter.lcm.v1.model.Tenant; import org.slf4j.Logger; @@ -49,7 +49,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public GenericVnf invokeGetGenericVnf(final String vnfId) { return aaiClientProvider.getAaiClient() - .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)) + .get(GenericVnf.class, + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId))) .orElseGet(() -> { logger.debug("No vnf found in AAI with ID: {}", vnfId); return null; @@ -58,9 +59,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public GenericVnfs invokeQueryGenericVnf(final String selfLink) { - return aaiClientProvider.getAaiClient() - .get(GenericVnfs.class, - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNFS).queryParam("selflink", selfLink)) + return aaiClientProvider.getAaiClient().get(GenericVnfs.class, AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.network().genericVnfs()).queryParam("selflink", selfLink)) .orElseGet(() -> { logger.debug("No vnf found in AAI with selflink: {}", selfLink); return null; @@ -70,7 +70,9 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public EsrVnfmList invokeGetVnfms() { return aaiClientProvider.getAaiClient() - .get(EsrVnfmList.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST)).orElseGet(() -> { + .get(EsrVnfmList.class, + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.externalSystem().esrVnfmList())) + .orElseGet(() -> { logger.debug("No VNFMs in AAI"); return null; }); @@ -79,7 +81,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public EsrVnfm invokeGetVnfm(final String vnfmId) { return aaiClientProvider.getAaiClient() - .get(EsrVnfm.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId).depth(Depth.ONE)) + .get(EsrVnfm.class, AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.externalSystem().esrVnfm(vnfmId)).depth(Depth.ONE)) .orElseGet(() -> { logger.debug("VNFM not found in AAI"); return null; @@ -90,7 +93,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { public EsrSystemInfoList invokeGetVnfmEsrSystemInfoList(final String vnfmId) { return aaiClientProvider.getAaiClient() .get(EsrSystemInfoList.class, - AAIUriFactory.createResourceUri(AAIObjectType.VNFM_ESR_SYSTEM_INFO_LIST, vnfmId)) + AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.externalSystem().esrVnfm(vnfmId).esrSystemInfoList())) .orElseGet(() -> { logger.debug("VNFM ESR system info list not found in AAI"); return null; @@ -99,45 +103,47 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public void invokePatchGenericVnf(final GenericVnf vnf) { - aaiClientProvider.getAaiClient() - .update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId()), vnf); + aaiClientProvider.getAaiClient().update( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnf.getVnfId())), vnf); } @Override public void invokePutGenericVnfToVnfmRelationship(final GenericVnf vnf, final String vnfmId) { - aaiClientProvider.getAaiClient().connect(AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId), - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())); + aaiClientProvider.getAaiClient().connect( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.externalSystem().esrVnfm(vnfmId)), + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnf.getVnfId()))); } @Override public void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenant, final Vserver vserver) { - aaiClientProvider.getAaiClient().create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegion, tenant, vserver.getVserverId()), vserver); + aaiClientProvider + .getAaiClient().create( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenant).vserver(vserver.getVserverId())), + vserver); } @Override public void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, final String tenant, final Vserver vserver, final String vnfId) { - aaiClientProvider.getAaiClient() - .connect( - AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, - vserver.getVserverId()), - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)); + aaiClientProvider.getAaiClient().connect( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenant).vserver(vserver.getVserverId())), + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId))); } @Override public void invokeDeleteVserver(final String cloudOwner, final String cloudRegion, final String tenant, final String vserverId) { - aaiClientProvider.getAaiClient().delete( - AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, vserverId)); + aaiClientProvider.getAaiClient().delete(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenant).vserver(vserverId))); } @Override public Tenant invokeGetTenant(final String cloudOwner, final String cloudRegion, final String tenantId) { - return aaiClientProvider.getAaiClient() - .get(Tenant.class, - AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegion, tenantId)) + return aaiClientProvider.getAaiClient().get(Tenant.class, AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId))) .orElseGet(() -> { logger.debug("Tenant not found in AAI"); return null; @@ -147,8 +153,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public EsrSystemInfoList invokeGetCloudRegionEsrSystemInfoList(final String cloudOwner, final String cloudRegion) { return aaiClientProvider - .getAaiClient().get(EsrSystemInfoList.class, AAIUriFactory - .createResourceUri(AAIObjectType.CLOUD_ESR_SYSTEM_INFO_LIST, cloudOwner, cloudRegion)) + .getAaiClient().get(EsrSystemInfoList.class, AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).esrSystemInfoList())) .orElseGet(() -> { logger.debug("Cloud esr system info list not found in AAI"); return null; diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java index 9aed675324..5bc4daac42 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/EtsiSol003AdapterControllerTest.java @@ -53,6 +53,7 @@ import org.onap.aai.domain.yang.RelationshipData; import org.onap.aai.domain.yang.RelationshipList; import org.onap.aaiclient.client.aai.AAIResourcesClient; import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.aaiclient.client.aai.entities.uri.AAIBaseResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.so.adapters.etsisol003adapter.lcm.extclients.EtsiPackageProvider; import org.onap.so.adapters.etsisol003adapter.lcm.extclients.vnfm.VnfmRestTemplateConfiguration; @@ -534,7 +535,7 @@ public class EtsiSol003AdapterControllerTest { } - private class AaiResourceUriMatcher extends BaseMatcher<AAIResourceUri> { + private class AaiResourceUriMatcher extends BaseMatcher<AAIBaseResourceUri<?, ?>> { final String uriAsString; @@ -544,12 +545,12 @@ public class EtsiSol003AdapterControllerTest { @Override public boolean matches(final Object item) { - if (item instanceof AAIResourceUri) { + if (item instanceof AAIBaseResourceUri<?, ?>) { if (uriAsString.endsWith("...")) { - return ((AAIResourceUri) item).build().toString() + return ((AAIBaseResourceUri<?, ?>) item).build().toString() .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); } - return ((AAIResourceUri) item).build().toString().equals(uriAsString); + return ((AAIBaseResourceUri<?, ?>) item).build().toString().equals(uriAsString); } return false; } diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java index 21e56617cd..99b8c71764 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003GrantControllerTest.java @@ -43,7 +43,7 @@ import org.onap.aai.domain.yang.Relationship; import org.onap.aai.domain.yang.RelationshipData; import org.onap.aai.domain.yang.RelationshipList; import org.onap.aaiclient.client.aai.AAIResourcesClient; -import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; +import org.onap.aaiclient.client.aai.entities.uri.AAIBaseResourceUri; import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantRequest; import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantRequest.OperationEnum; import org.onap.so.adapters.etsisol003adapter.lcm.grant.model.GrantsAddResources; @@ -224,7 +224,7 @@ public class Sol003GrantControllerTest { "/network/generic-vnfs?selflink=http%3A%2F%2Fvnfm%3A8080%2Fvnfs%2FmyTestVnfIdOnVnfm"))); } - private class AaiResourceUriMatcher extends BaseMatcher<AAIResourceUri> { + private class AaiResourceUriMatcher extends BaseMatcher<AAIBaseResourceUri<?, ?>> { final String uriAsString; @@ -234,12 +234,12 @@ public class Sol003GrantControllerTest { @Override public boolean matches(final Object item) { - if (item instanceof AAIResourceUri) { + if (item instanceof AAIBaseResourceUri) { if (uriAsString.endsWith("...")) { - return ((AAIResourceUri) item).build().toString() + return ((AAIBaseResourceUri<?, ?>) item).build().toString() .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); } - return ((AAIResourceUri) item).build().toString().equals(uriAsString); + return ((AAIBaseResourceUri<?, ?>) item).build().toString().equals(uriAsString); } return false; } diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java index 86eda0abfa..0d5bcd2573 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-adapter/src/test/java/org/onap/so/adapters/etsisol003adapter/lcm/rest/Sol003LcnControllerTest.java @@ -54,6 +54,7 @@ import org.onap.aai.domain.yang.RelationshipData; import org.onap.aai.domain.yang.RelationshipList; import org.onap.aai.domain.yang.Vserver; import org.onap.aaiclient.client.aai.AAIResourcesClient; +import org.onap.aaiclient.client.aai.entities.uri.AAIBaseResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.AaiHelper; import org.onap.so.adapters.etsisol003adapter.lcm.extclients.aai.OamIpAddressSource; @@ -385,7 +386,7 @@ public class Sol003LcnControllerTest { genericVnf.getRelationshipList().getRelationship().add(relationshipToVserver); } - private class AaiResourceUriMatcher extends BaseMatcher<AAIResourceUri> { + private class AaiResourceUriMatcher extends BaseMatcher<AAIBaseResourceUri<?, ?>> { final String uriAsString; @@ -395,12 +396,12 @@ public class Sol003LcnControllerTest { @Override public boolean matches(final Object item) { - if (item instanceof AAIResourceUri) { + if (item instanceof AAIBaseResourceUri<?, ?>) { if (uriAsString.endsWith("...")) { - return ((AAIResourceUri) item).build().toString() + return ((AAIBaseResourceUri<?, ?>) item).build().toString() .startsWith(uriAsString.substring(0, uriAsString.indexOf("..."))); } - return ((AAIResourceUri) item).build().toString().equals(uriAsString); + return ((AAIBaseResourceUri<?, ?>) item).build().toString().equals(uriAsString); } return false; } diff --git a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml index 01ba94ddd4..b636f6818c 100644 --- a/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml +++ b/adapters/etsi-sol003-adapter/etsi-sol003-lcm/etsi-sol003-lcm-api/pom.xml @@ -100,6 +100,7 @@ <source>${project.basedir}/target/generated-sources/vnfmadapter/src/gen/java/main</source> <source>${project.basedir}/target/generated-sources/sol003-vnf-lcn/src/gen/java/main</source> <source>${project.basedir}/target/generated-sources/sol003-vnf-grant/src/gen/java/main</source> + <source>${project.basedir}/target/generated-sources/etsisol003adapter/src/gen/java/main</source> </sources> </configuration> </execution> diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java index fa5c57f447..ab0239057a 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloud/authentication/AuthenticationMethodFactory.java @@ -90,22 +90,31 @@ public final class AuthenticationMethodFactory { return v3Auth; } - public final com.woorea.openstack.keystone.v3.model.Authentication getAuthenticationForV3( - CloudIdentity cloudIdentity) { + public final com.woorea.openstack.keystone.v3.model.Authentication getAuthenticationForV3ByName( + CloudIdentity cloudIdentity, String name) { Identity identity = new Identity(); Password password = new Password(); User user = new User(); Domain userDomain = new Domain(); + Scope scope = new Scope(); + Project project = new Project(); + Project.Domain projectDomain = new Project.Domain(); userDomain.setName(cloudIdentity.getUserDomainName()); + projectDomain.setName(cloudIdentity.getProjectDomainName()); user.setName(cloudIdentity.getMsoId()); user.setPassword(CryptoUtils.decryptCloudConfigPassword(cloudIdentity.getMsoPass())); user.setDomain(userDomain); password.setUser(user); + project.setDomain(projectDomain); + project.setName(name); + scope.setProject(project); identity.setPassword(password); identity.setMethods(Collections.singletonList("password")); com.woorea.openstack.keystone.v3.model.Authentication v3Auth = new com.woorea.openstack.keystone.v3.model.Authentication(); v3Auth.setIdentity(identity); + v3Auth.setScope(scope); return v3Auth; } + } diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java index 50ebcc66ee..6800428a62 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoCommonUtils.java @@ -97,7 +97,7 @@ public class MsoCommonUtils { * openstack-java-sdk classname of the OpenStackRequest<T> parameter). */ - protected <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request) { + public <T> T executeAndRecordOpenstackRequest(OpenStackRequest<T> request) { return executeAndRecordOpenstackRequest(request, true); } @@ -174,7 +174,7 @@ public class MsoCommonUtils { * Convert an Openstack Exception on a Keystone call to an MsoException. This method supports both * OpenstackResponseException and OpenStackConnectException. */ - protected MsoException keystoneErrorToMsoException(OpenStackBaseException e, String context) { + public MsoException keystoneErrorToMsoException(OpenStackBaseException e, String context) { MsoException me = null; if (e instanceof OpenStackResponseException) { @@ -455,15 +455,16 @@ public class MsoCommonUtils { */ protected KeystoneAuthHolder getKeystoneAuthHolder(String cloudSiteId, String tenantId, String serviceName) throws MsoException { - CloudSite cloudSite = - cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); - String cloudId = cloudSite.getId(); - String region = cloudSite.getRegionId(); - CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - MsoTenantUtils tenantUtils = - tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); - String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); + CloudIdentity cloudIdentity = null; try { + CloudSite cloudSite = + cloudConfig.getCloudSite(cloudSiteId).orElseThrow(() -> new MsoCloudSiteNotFound(cloudSiteId)); + String cloudId = cloudSite.getId(); + String region = cloudSite.getRegionId(); + cloudIdentity = cloudSite.getIdentityService(); + MsoTenantUtils tenantUtils = + tenantUtilsFactory.getTenantUtilsByServerType(cloudIdentity.getIdentityServerType()); + String keystoneUrl = tenantUtils.getKeystoneUrl(cloudId, cloudIdentity); if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType())) { Access access = getKeystone(tenantId, cloudIdentity, keystoneUrl); try { diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java index 072ab5a8d0..63bc235363 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoKeystoneV3Utils.java @@ -21,29 +21,15 @@ package org.onap.so.openstack.utils; import java.util.Map; -import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.db.catalog.beans.CloudIdentity; -import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.openstack.beans.MsoTenant; import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; -import org.onap.so.utils.CryptoUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.woorea.openstack.keystone.v3.model.Token; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.v3.Keystone; -import com.woorea.openstack.keystone.v3.api.TokensResource.Authenticate; -import com.woorea.openstack.keystone.v3.model.Authentication; -import com.woorea.openstack.keystone.v3.model.Authentication.Identity; @Component public class MsoKeystoneV3Utils extends MsoTenantUtils { - @Autowired - private AuthenticationMethodFactory authenticationMethodFactory; - @Override public String createTenant(String tenantName, String cloudSiteId, Map<String, String> metadata, boolean backout) throws MsoException { @@ -71,22 +57,4 @@ public class MsoKeystoneV3Utils extends MsoTenantUtils { return cloudIdentity.getIdentityUrl(); } - public Token getKeystoneToken(CloudSite cloudSite) throws MsoException { - try { - CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - - Keystone keystone = new Keystone(cloudIdentity.getIdentityUrl()); - - Authentication auth = authenticationMethodFactory.getAuthenticationForV3(cloudIdentity); - - Authenticate authenticate = keystone.tokens().authenticate(auth); - return executeAndRecordOpenstackRequest(authenticate); - - } catch (OpenStackResponseException e) { - throw keystoneErrorToMsoException(e, "TokenAuth"); - } catch (OpenStackConnectException e) { - throw keystoneErrorToMsoException(e, "TokenAuth"); - } - } - } diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java index 305d52a997..89fd9a0147 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java @@ -37,10 +37,11 @@ public class QueryServiceMacroHolder extends CatalogQuery { + "\t\t\"modelUuid\" : <SERVICE_MODEL_UUID>,\n" + "\t\t\"modelInvariantUuid\" : <SERVICE_MODEL_INVARIANT_ID>,\n" + "\t\t\"modelVersion\" : <SERVICE_MODEL_VERSION>\n" + "\t},\n" - + "\t\"serviceType\" : <SERVICE_TYPE>,\n" + "\t\"serviceRole\" : <SERVICE_ROLE>,\n" - + "\t\"environmentContext\" : <ENVIRONMENT_CONTEXT>,\n" + "\t\"resourceOrder\" : <RESOURCE_ORDER>,\n" - + "\t\"workloadContext\" : <WORKLOAD_CONTEXT>,\n" + "<_SERVICEVNFS_>,\n" + "<_SERVICENETWORKS_>,\n" - + "<_SERVICEINFO_>,\n" + "<_SERVICEPROXY_>,\n" + "<_SERVICEALLOTTEDRESOURCES_>\n" + "\t}}"; + + "\t\"serviceCategory\" : <SERVICE_CATEGORY>,\n" + "\t\"serviceType\" : <SERVICE_TYPE>,\n" + + "\t\"serviceRole\" : <SERVICE_ROLE>,\n" + "\t\"environmentContext\" : <ENVIRONMENT_CONTEXT>,\n" + + "\t\"resourceOrder\" : <RESOURCE_ORDER>,\n" + "\t\"workloadContext\" : <WORKLOAD_CONTEXT>,\n" + + "<_SERVICEVNFS_>,\n" + "<_SERVICENETWORKS_>,\n" + "<_SERVICEINFO_>,\n" + "<_SERVICEPROXY_>,\n" + + "<_SERVICEALLOTTEDRESOURCES_>\n" + "\t}}"; public QueryServiceMacroHolder() { super(); @@ -80,6 +81,7 @@ public class QueryServiceMacroHolder extends CatalogQuery { put(valueMap, "SERVICE_MODEL_VERSION", service.getModelVersion()); put(valueMap, "SERVICE_TYPE", service.getServiceType()); put(valueMap, "SERVICE_ROLE", service.getServiceRole()); + put(valueMap, "SERVICE_CATEGORY", service.getCategory()); put(valueMap, "ENVIRONMENT_CONTEXT", service.getEnvironmentContext()); put(valueMap, "WORKLOAD_CONTEXT", service.getWorkloadContext()); put(valueMap, "RESOURCE_ORDER", service.getResourceOrder()); diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java index e94c283a98..0ba40e2700 100644 --- a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/MSOCnfApplication.java @@ -28,8 +28,10 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerA import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; @SpringBootApplication @ComponentScan(basePackages = {"org.onap.so.adapters.cnf"}) @@ -42,4 +44,9 @@ public class MSOCnfApplication { public static void main(String... args) { SpringApplication.run(MSOCnfApplication.class, args); } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } } diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/GroupVersionKind.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/GroupVersionKind.java new file mode 100644 index 0000000000..bfa5505ccc --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/GroupVersionKind.java @@ -0,0 +1,66 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"Group", "Version", "Kind"}) +public class GroupVersionKind { + @JsonProperty("Group") + private String group; + @JsonProperty("Version") + private String version; + @JsonProperty("Kind") + private String kind; + + @JsonProperty("Group") + public String getGroup() { + return group; + } + + @JsonProperty("Group") + public void setGroup(String group) { + this.group = group; + } + + @JsonProperty("Version") + public String getVersion() { + return version; + } + + @JsonProperty("Version") + public void setVersion(String version) { + this.version = version; + } + + @JsonProperty("Kind") + public String getKind() { + return kind; + } + + @JsonProperty("Kind") + public void setKind(String kind) { + this.kind = kind; + } +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceMiniResponse.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceMiniResponse.java new file mode 100644 index 0000000000..58040826dd --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceMiniResponse.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(value = "true") +public class InstanceMiniResponse extends Response { + + private String id; + private MulticloudInstanceRequest request; + private String nameSpace; + + public InstanceMiniResponse(String errorMsg) { + super(errorMsg); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public MulticloudInstanceRequest getRequest() { + return request; + } + + public void setRequest(MulticloudInstanceRequest request) { + this.request = request; + } + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceMiniResponseList.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceMiniResponseList.java new file mode 100644 index 0000000000..ad70fbb7d0 --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceMiniResponseList.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(value = "true") +public class InstanceMiniResponseList extends Response { + + public InstanceMiniResponseList(String errorMsg) { + super(errorMsg); + } + + private List<InstanceMiniResponse> instancList; + + public List<InstanceMiniResponse> getInstancList() { + return instancList; + } + + public void setInstancList(List<InstanceMiniResponse> instancList) { + this.instancList = instancList; + } + +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceResponse.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceResponse.java new file mode 100644 index 0000000000..effaaf5f78 --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceResponse.java @@ -0,0 +1,87 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"id", "request", "namespace", "resources"}) +@JsonIgnoreProperties(value = "true") +public class InstanceResponse extends Response { + + @JsonProperty("id") + private String id; + @JsonProperty("request") + private MulticloudInstanceRequest request; + @JsonProperty("namespace") + private String namespace; + @JsonProperty("resources") + private List<Resource> resources = null; + + public InstanceResponse(String errorMsg) { + super(errorMsg); + } + + @JsonProperty("id") + public String getId() { + return id; + } + + @JsonProperty("id") + public void setId(String id) { + this.id = id; + } + + @JsonProperty("request") + public MulticloudInstanceRequest getRequest() { + return request; + } + + @JsonProperty("request") + public void setRequest(MulticloudInstanceRequest request) { + this.request = request; + } + + @JsonProperty("namespace") + public String getNamespace() { + return namespace; + } + + @JsonProperty("namespace") + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + @JsonProperty("resources") + public List<Resource> getResources() { + return resources; + } + + @JsonProperty("resources") + public void setResources(List<Resource> resources) { + this.resources = resources; + } + +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceStatusResponse.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceStatusResponse.java new file mode 100644 index 0000000000..2472684bc0 --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/InstanceStatusResponse.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(value = "true") +public class InstanceStatusResponse extends Response { + + public InstanceStatusResponse(String errorMsg) { + super(errorMsg); + } + + private MulticloudInstanceRequest request; + + private boolean ready; + + private String resourceCount; + + private List<PodStatus> podStatuses; + + private List<?> servicesStatuses; + + public MulticloudInstanceRequest getRequest() { + return request; + } + + public void setRequest(MulticloudInstanceRequest request) { + this.request = request; + } + + public boolean isReady() { + return ready; + } + + public void setReady(boolean ready) { + this.ready = ready; + } + + public String getResourceCount() { + return resourceCount; + } + + public void setResourceCount(String resourceCount) { + this.resourceCount = resourceCount; + } + + public List<PodStatus> getPodStatuses() { + return podStatuses; + } + + public void setPodStatuses(List<PodStatus> podStatuses) { + this.podStatuses = podStatuses; + } + + public List<?> getServicesStatuses() { + return servicesStatuses; + } + + public void setServicesStatuses(List<?> servicesStatuses) { + this.servicesStatuses = servicesStatuses; + } + +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/PodStatus.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/PodStatus.java new file mode 100644 index 0000000000..ed04601b2c --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/PodStatus.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +public class PodStatus { + + private String name; + private String nameSpace; + private boolean ready; + private String status; + private String[] ipAddresses; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + public boolean isReady() { + return ready; + } + + public void setReady(boolean ready) { + this.ready = ready; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String[] getIpAddresses() { + return ipAddresses; + } + + public void setIpAddresses(String[] ipAddresses) { + this.ipAddresses = ipAddresses; + } + +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/Resource.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/Resource.java new file mode 100644 index 0000000000..d18cd76039 --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/Resource.java @@ -0,0 +1,54 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"GVK", "Name"}) +public class Resource { + @JsonProperty("GVK") + private GroupVersionKind gVK; + @JsonProperty("Name") + private String name; + + @JsonProperty("GVK") + public GroupVersionKind getGVK() { + return gVK; + } + + @JsonProperty("GVK") + public void setGVK(GroupVersionKind gVK) { + this.gVK = gVK; + } + + @JsonProperty("Name") + public String getName() { + return name; + } + + @JsonProperty("Name") + public void setName(String name) { + this.name = name; + } +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/Response.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/Response.java new file mode 100644 index 0000000000..423022393c --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/model/Response.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.model; + +public class Response { + + private String errorMsg; + + public Response(String errorMsg) { + this.errorMsg = errorMsg; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + +} diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java index b6d50da557..825778b89a 100644 --- a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/rest/CnfAdapterRest.java @@ -1,6 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.rest; import java.io.File; +import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; @@ -20,12 +41,17 @@ import org.onap.so.adapters.cnf.model.ConfigTemplateEntity; import org.onap.so.adapters.cnf.model.ConfigurationEntity; import org.onap.so.adapters.cnf.model.ConfigurationRollbackEntity; import org.onap.so.adapters.cnf.model.ConnectivityInfo; -import org.onap.so.adapters.cnf.model.MulticloudInstanceRequest; +import org.onap.so.adapters.cnf.model.InstanceMiniResponseList; +import org.onap.so.adapters.cnf.model.InstanceResponse; +import org.onap.so.adapters.cnf.model.InstanceStatusResponse; import org.onap.so.adapters.cnf.model.ProfileEntity; import org.onap.so.adapters.cnf.model.ResourceBundleEntity; import org.onap.so.adapters.cnf.model.Tag; +import org.onap.so.adapters.cnf.service.CnfAdapterService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -34,6 +60,8 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -43,23 +71,78 @@ public class CnfAdapterRest { private static final Logger logger = LoggerFactory.getLogger(CnfAdapterRest.class); private final CloseableHttpClient httpClient = HttpClients.createDefault(); + @Autowired + private CnfAdapterService cnfAdapterService; + @ResponseBody @RequestMapping(value = {"/api/cnf-adapter/v1/healthcheck"}, method = RequestMethod.GET, produces = "application/json") - public String healthCheck() throws Exception { + public ResponseEntity<String> healthCheck() throws Exception { - logger.info("health check called."); + logger.info("healthCheck called."); + return cnfAdapterService.healthCheck(); + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/instance"}, method = RequestMethod.POST, + produces = "application/json", consumes = "application/json") + public ResponseEntity<InstanceResponse> createInstance(@RequestBody BpmnInstanceRequest bpmnInstanceRequest) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("createInstance called."); + return cnfAdapterService.createInstance(bpmnInstanceRequest); + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/instance/{instID}"}, method = RequestMethod.GET, + produces = "application/json") + public ResponseEntity<InstanceResponse> getInstanceByInstanceId(@PathVariable("instID") String instanceId) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("getInstanceByInstanceId called."); + + return cnfAdapterService.getInstanceByInstanceId(instanceId); + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/instance/{instID}/status"}, method = RequestMethod.GET, + produces = "application/json") + public ResponseEntity<InstanceStatusResponse> getInstanceStatusByInstanceId( + @PathVariable("instID") String instanceId) throws JsonParseException, JsonMappingException, IOException { + + logger.info("getInstanceStatusByInstanceId called."); + + return cnfAdapterService.getInstanceStatusByInstanceId(instanceId); + + } + + @RequestMapping(value = {"/api/cnf-adapter/v1/instance"}, method = RequestMethod.GET, produces = "application/json") + public ResponseEntity<InstanceMiniResponseList> getInstanceByRBNameOrRBVersionOrProfileName( + @RequestParam(value = "rb-name", required = false) String rbName, + @RequestParam(value = "rb-version", required = false) String rbVersion, + @RequestParam(value = "profile-name", required = false) String profileName) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("getInstanceByRBNameOrRBVersionOrProfileName called."); + return cnfAdapterService.getInstanceByRBNameOrRBVersionOrProfileName(rbName, rbVersion, profileName); + + } + + @ResponseBody + @RequestMapping(value = {"/api/cnf-adapter/v1/instance/{instID}"}, method = RequestMethod.DELETE, + produces = "application/json") + public ResponseEntity<String> deleteInstanceByInstanceId(@PathVariable("instID") String instanceID) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("deleteInstanceByInstanceId called."); + return cnfAdapterService.deleteInstanceByInstanceId(instanceID); - // TODO - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/healthcheck"); - try (CloseableHttpResponse response = httpClient.execute(req)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition"}, method = RequestMethod.POST, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition"}, method = RequestMethod.POST, produces = "application/json") public String createRB(@RequestBody ResourceBundleEntity rB) throws Exception { @@ -67,7 +150,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/rb/definition"); + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/rb/definition"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); String requestBody = objectMapper.writeValueAsString(rB); @@ -82,7 +165,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}"}, method = RequestMethod.GET, produces = "application/json") public String getRB(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -91,7 +174,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion); + HttpGet req = new HttpGet("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); return EntityUtils.toString(response.getEntity()); @@ -99,8 +182,8 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}"}, - method = RequestMethod.DELETE, produces = "application/json") + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}"}, method = RequestMethod.DELETE, + produces = "application/json") public String deleteRB(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -108,7 +191,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion); + HttpDelete req = new HttpDelete("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -118,7 +201,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}"}, method = RequestMethod.GET, produces = "application/json") public String getListOfRB(@PathVariable("rb-name") String rbName) throws Exception { @@ -126,7 +209,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition/" + rbName); + HttpGet req = new HttpGet("http://multicloud-k8s:9015/v1/rb/definition/" + rbName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -136,7 +219,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition"}, method = RequestMethod.GET, produces = "application/json") public String getListOfRBWithoutUsingRBName() throws Exception { @@ -144,7 +227,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition"); + HttpGet req = new HttpGet("http://multicloud-k8s:9015/v1/rb/definition"); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -154,7 +237,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/content"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/content"}, method = RequestMethod.POST, produces = "multipart/form-data") public String uploadArtifactForRB(@RequestParam("file") MultipartFile file, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -172,7 +255,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. HttpPost post = - new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/content"); + new HttpPost("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/content"); post.setHeader("Content-Type", "multipart/form-data"); logger.info(String.valueOf(post)); post.setEntity(entity); @@ -185,7 +268,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/profile"}, method = RequestMethod.POST, produces = "application/json") public String createProfile(@RequestBody ProfileEntity fE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -195,7 +278,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. HttpPost post = - new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile"); + new HttpPost("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(fE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -209,7 +292,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, method = RequestMethod.GET, produces = "application/json") public String getProfile(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("pr-name") String prName) throws Exception { @@ -219,7 +302,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. HttpGet req = new HttpGet( - "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName); + "http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -228,7 +311,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/profile"}, method = RequestMethod.GET, produces = "application/json") public String getListOfProfile(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -237,7 +320,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile"); + HttpGet req = + new HttpGet("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile"); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -246,7 +330,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}"}, method = RequestMethod.DELETE, produces = "application/json") public String deleteProfile(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("pr-name") String prName) throws Exception { @@ -256,7 +340,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. HttpDelete req = new HttpDelete( - "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName); + "http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -266,7 +350,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}/content"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/profile/{pr-name}/content"}, method = RequestMethod.POST, produces = "multipart/form-data") public String uploadArtifactForProfile(@RequestParam("file") MultipartFile file, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @@ -284,7 +368,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/profile/" + prName + "/content"); post.setHeader("Content-Type", "multipart/form-data"); @@ -299,144 +383,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance"}, method = RequestMethod.POST, - produces = "application/json") - public String createInstance(@RequestBody BpmnInstanceRequest bpmnInstanceRequest) throws Exception { - - logger.info("create Instance called."); - - MulticloudInstanceRequest multicloudInstanceRequest = new MulticloudInstanceRequest(); - - if (bpmnInstanceRequest.getK8sRBProfileName() != null) { - multicloudInstanceRequest.setCloudRegion(bpmnInstanceRequest.getCloudRegionId()); - multicloudInstanceRequest.setLabels(bpmnInstanceRequest.getLabels()); - multicloudInstanceRequest.setOverrideValues(bpmnInstanceRequest.getOverrideValues()); - multicloudInstanceRequest.setProfileName(bpmnInstanceRequest.getK8sRBProfileName()); - multicloudInstanceRequest.setRbName(bpmnInstanceRequest.getModelInvariantId()); - multicloudInstanceRequest.setRbVersion(bpmnInstanceRequest.getModelVersionId()); - multicloudInstanceRequest.setVfModuleUuid(bpmnInstanceRequest.getVfModuleUUID()); - } else { - - logger.info("K8sRBProfileName is required"); - return "K8sRBProfileName is required"; - } - - // TODO - // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/instance"); - ObjectMapper objectMapper = new ObjectMapper(); - - String requestBody = objectMapper.writeValueAsString(multicloudInstanceRequest); - StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); - post.setEntity(requestEntity); - - try (CloseableHttpClient httpClient = HttpClients.createDefault(); - CloseableHttpResponse response = httpClient.execute(post)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } - } - - // This api is not enabled in multicloud project ,but this is required in - // future. - @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{vnfInstanceId}"}, method = RequestMethod.PUT, - produces = "application/json") - public String updateInstance(@RequestBody MulticloudInstanceRequest iE, - @PathVariable("vnfInstanceId") String instanceId) throws Exception { - - logger.info("create Instance called."); - - // TODO - // Below URL should be changed as appropriate multicloud URL. - HttpPut post = new HttpPut("http://172.17.0.2:31770/v1/instance/" + instanceId); - ObjectMapper objectMapper = new ObjectMapper(); - - String requestBody = objectMapper.writeValueAsString(iE); - StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); - post.setEntity(requestEntity); - - try (CloseableHttpClient httpClient = HttpClients.createDefault(); - CloseableHttpResponse response = httpClient.execute(post)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } - } - - @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{instID}"}, method = RequestMethod.GET, - produces = "application/json") - public String getInstance(@PathVariable("instID") String instanceId) throws Exception { - - logger.info("get Instance called."); - - // TODO - // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/instance/" + instanceId); - - try (CloseableHttpResponse response = httpClient.execute(req)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } - } - - @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{instID}/status"}, method = RequestMethod.GET, - produces = "application/json") - public String getInstanceStatus(@PathVariable("instID") String instanceId) throws Exception { - - logger.info("getInstanceStatus called."); - - // TODO - // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/instance/" + instanceId + "/status"); - - try (CloseableHttpResponse response = httpClient.execute(req)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } - } - - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance"}, method = RequestMethod.GET, - produces = "application/json") - public String getInstanceBasedOnRBNameOrRBVersionOrProfileName( - @RequestParam(value = "rb-name", required = false) String rbName, - @RequestParam(value = "rb-version", required = false) String rbVersion, - @RequestParam(value = "profile-name", required = false) String profileName) throws Exception { - - logger.info("getInstanceBasedOnRBNameOrRBVersionOrProfileName called."); - - // TODO - // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/instance?rb-name=" + rbName + "&rb-version=" + rbVersion - + "&profile-name=" + profileName); - - try (CloseableHttpResponse response = httpClient.execute(req)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } - } - - @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/instance/{instID}"}, method = RequestMethod.DELETE, - produces = "application/json") - public String deleteInstance(@PathVariable("instID") String instanceID) throws Exception { - - logger.info("delete Instance called."); - - // TODO - // Below URL should be changed as appropriate multicloud URL. - HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/instance/" + instanceID); - - try (CloseableHttpResponse response = httpClient.execute(req)) { - logger.info("response:" + response.getEntity()); - return EntityUtils.toString(response.getEntity()); - } - - } - - @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config"}, method = RequestMethod.POST, produces = "application/json") public String createConfiguration(@RequestBody ConfigurationEntity cE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName) @@ -446,8 +393,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost( - "http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + prName + "/config"); + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/definition/" + rbName + "/" + rbVersion + + "/profile/" + prName + "/config"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(cE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -461,8 +408,8 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = { - "/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, + @RequestMapping( + value = {"/api/cnf-adapter/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, method = RequestMethod.GET, produces = "application/json") public String getConfiguration(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName, @PathVariable("cfg-name") String cfgName) throws Exception { @@ -471,7 +418,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + HttpGet req = new HttpGet("http://multicloud-k8s:9015/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + prName + "/config/" + cfgName); try (CloseableHttpResponse response = httpClient.execute(req)) { @@ -481,8 +428,8 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = { - "/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, + @RequestMapping( + value = {"/api/cnf-adapter/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, method = RequestMethod.DELETE, produces = "application/json") public String deleteConfiguration(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName, @@ -492,7 +439,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + HttpDelete req = new HttpDelete("http://multicloud-k8s:9015/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + prName + "/config/" + cfgName); try (CloseableHttpResponse response = httpClient.execute(req)) { @@ -503,8 +450,8 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = { - "/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, + @RequestMapping( + value = {"/api/cnf-adapter/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/config/{cfg-name}"}, method = RequestMethod.PUT, produces = "application/json") public String updateConfiguration(@RequestBody ConfigurationEntity cE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("profile-name") String prName, @@ -514,7 +461,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPut post = new HttpPut("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + HttpPut post = new HttpPut("http://multicloud-k8s:9015/v1/definition/" + rbName + "/" + rbVersion + "/profile/" + prName + "/config/" + cfgName); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(cE); @@ -529,7 +476,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/tagit"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/definition/{rb-name}/{rb-version}/profile/{profile-name}/tagit"}, method = RequestMethod.POST, produces = "application/json") public String tagConfigurationValue(@RequestBody Tag tag, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("pr-name") String prName) throws Exception { @@ -537,8 +484,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" - + prName + "/config/tagit"); + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/definition/" + rbName + "/" + rbVersion + + "/profile/" + prName + "/config/tagit"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(tag); @@ -553,7 +500,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/connectivity-info"}, method = RequestMethod.POST, + @RequestMapping(value = {"/api/cnf-adapter/v1/connectivity-info"}, method = RequestMethod.POST, produces = "application/json") public String createConnectivityInfo(@RequestBody ConnectivityInfo cIE) throws Exception { @@ -561,7 +508,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/connectivity-info"); + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/connectivity-info"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(cIE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -575,7 +522,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/connectivity-info/{connname}"}, method = RequestMethod.GET, + @RequestMapping(value = {"/api/cnf-adapter/v1/connectivity-info/{connname}"}, method = RequestMethod.GET, produces = "application/json") public String getConnectivityInfo(@PathVariable("connname") String connName) throws Exception { @@ -583,7 +530,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet("http://172.17.0.2:31770/v1/connectivity-info/" + connName); + HttpGet req = new HttpGet("http://multicloud-k8s:9015/v1/connectivity-info/" + connName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -592,7 +539,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/connectivity-info/{connname}"}, method = RequestMethod.DELETE, + @RequestMapping(value = {"/api/cnf-adapter/v1/connectivity-info/{connname}"}, method = RequestMethod.DELETE, produces = "application/json") public String deleteConnectivityInfo(@PathVariable("connname") String connName) throws Exception { @@ -600,7 +547,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpDelete req = new HttpDelete("http://172.17.0.2:31770/v1/connectivity-info/" + connName); + HttpDelete req = new HttpDelete("http://multicloud-k8s:9015/v1/connectivity-info/" + connName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -610,7 +557,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/config-template"}, method = RequestMethod.POST, produces = "application/json") public String createConfigTemplate(@RequestBody ConfigTemplateEntity tE, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion) throws Exception { @@ -620,7 +567,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. HttpPost post = new HttpPost( - "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template"); + "http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(tE); StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); @@ -634,7 +581,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, method = RequestMethod.GET, produces = "application/json") public String getConfigTemplate(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("tname") String tName) throws Exception { @@ -643,8 +590,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpGet req = new HttpGet( - "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template/" + tName); + HttpGet req = new HttpGet("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + + "/config-template/" + tName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -653,7 +600,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}"}, method = RequestMethod.DELETE, produces = "application/json") public String deleteTemplate(@PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @PathVariable("tname") String tName) throws Exception { @@ -662,8 +609,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpDelete req = new HttpDelete( - "http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template/" + tName); + HttpDelete req = new HttpDelete("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + + "/config-template/" + tName); try (CloseableHttpResponse response = httpClient.execute(req)) { logger.info("response:" + response.getEntity()); @@ -674,7 +621,7 @@ public class CnfAdapterRest { @ResponseBody @RequestMapping( - value = {"/api/cnf-adapter/v1/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}/content"}, + value = {"/api/cnf-adapter/v1/rb/definition/{rb-name}/{rb-version}/config-template/{tname}/content"}, method = RequestMethod.POST, produces = "multipart/form-data") public String uploadTarFileForTemplate(@RequestParam("file") MultipartFile file, @PathVariable("rb-name") String rbName, @PathVariable("rb-version") String rbVersion, @@ -692,7 +639,7 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/rb/definition/" + rbName + "/" + rbVersion + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/rb/definition/" + rbName + "/" + rbVersion + "/config-template/" + tName + "/content"); post.setHeader("Content-Type", "multipart/form-data"); @@ -707,7 +654,7 @@ public class CnfAdapterRest { } @ResponseBody - @RequestMapping(value = {"/api/cnf-adapter/v1/v1/definition/{rbName}/{rbVersion}/profile/{prName}/config/rollback"}, + @RequestMapping(value = {"/api/cnf-adapter/v1/definition/{rbName}/{rbVersion}/profile/{prName}/config/rollback"}, method = RequestMethod.DELETE, produces = "application/json") public String rollbackConfiguration(@RequestBody ConfigurationRollbackEntity rE, @PathVariable("rbName") String rbName, @PathVariable("rbVersion") String rbVersion, @@ -716,8 +663,8 @@ public class CnfAdapterRest { // TODO // Below URL should be changed as appropriate multicloud URL. - HttpPost post = new HttpPost("http://172.17.0.2:31770/v1/definition/" + rbName + "/" + rbVersion + "/profile/" - + prName + "/config/rollback"); + HttpPost post = new HttpPost("http://multicloud-k8s:9015/v1/definition/" + rbName + "/" + rbVersion + + "/profile/" + prName + "/config/rollback"); ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(rE); diff --git a/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/service/CnfAdapterService.java b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/service/CnfAdapterService.java new file mode 100644 index 0000000000..06c09e3431 --- /dev/null +++ b/adapters/mso-cnf-adapter/src/main/java/org/onap/so/adapters/cnf/service/CnfAdapterService.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Huawei Technologies Co., Ltd. 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.cnf.service; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import javax.persistence.EntityNotFoundException; +import javax.ws.rs.core.UriBuilder; +import org.apache.http.HttpStatus; +import org.onap.so.adapters.cnf.model.BpmnInstanceRequest; +import org.onap.so.adapters.cnf.model.InstanceMiniResponse; +import org.onap.so.adapters.cnf.model.InstanceMiniResponseList; +import org.onap.so.adapters.cnf.model.InstanceResponse; +import org.onap.so.adapters.cnf.model.InstanceStatusResponse; +import org.onap.so.adapters.cnf.model.MulticloudInstanceRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; + +@Service +public class CnfAdapterService { + private static final Logger logger = LoggerFactory.getLogger(CnfAdapterService.class); + @Autowired + private RestTemplate restTemplate; + private static final String INSTANCE_CREATE_PATH = "/v1/instance"; + private static final String HEALTH_CHECK = "/v1/healthcheck"; + + public ResponseEntity<String> healthCheck() { + + logger.info("CnfAdapterService createInstance called"); + ResponseEntity<String> result = null; + try { + + logger.info("CnfAdapterService createInstance called"); + + // String uri = env.getRequiredProperty("multicloud.endpoint"); //TODO: + // This needs to be added as well + // for configuration + String uri = "http://multicloud-k8s:9015"; // TODO: What is the correct uri? + String endpoint = UriBuilder.fromUri(uri).path(HEALTH_CHECK).build().toString(); + HttpEntity<?> requestEntity = new HttpEntity<>(getHttpHeaders()); + result = restTemplate.exchange(endpoint, HttpMethod.GET, requestEntity, String.class); + return result; + } catch (HttpClientErrorException e) { + logger.error("Error Calling Multicloud, e"); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException(e.getResponseBodyAsString()); + } + throw e; + } catch (HttpStatusCodeException e) { + logger.error("Error in Multicloud, e"); + String responseString = e.getResponseBodyAsString(); + return ResponseEntity.status(e.getStatusCode()).body(responseString); + } + } + + public ResponseEntity<InstanceResponse> createInstance(BpmnInstanceRequest bpmnInstanceRequest) + throws JsonParseException, JsonMappingException, IOException { + try { + logger.info("CnfAdapterService createInstance called"); + MulticloudInstanceRequest multicloudInstanceRequest = new MulticloudInstanceRequest(); + ResponseEntity<InstanceResponse> instanceResponse = null; + if (bpmnInstanceRequest.getK8sRBProfileName() != null) { + multicloudInstanceRequest.setCloudRegion(bpmnInstanceRequest.getCloudRegionId()); + multicloudInstanceRequest.setLabels(bpmnInstanceRequest.getLabels()); + multicloudInstanceRequest.setOverrideValues(bpmnInstanceRequest.getOverrideValues()); + multicloudInstanceRequest.setProfileName(bpmnInstanceRequest.getK8sRBProfileName()); + multicloudInstanceRequest.setRbName(bpmnInstanceRequest.getModelInvariantId()); + multicloudInstanceRequest.setRbVersion(bpmnInstanceRequest.getModelVersionId()); + multicloudInstanceRequest.setVfModuleUuid(bpmnInstanceRequest.getVfModuleUUID()); + } else { + logger.error("k8sProfileName should not be null"); + return instanceResponse; + } + // String uri = env.getRequiredProperty("multicloud.endpoint"); //TODO: + // This needs to be added as well + // for configuration + String uri = "http://multicloud-k8s:9015"; // TODO: What is the correct uri? + String endpoint = UriBuilder.fromUri(uri).path(INSTANCE_CREATE_PATH).build().toString(); + HttpEntity<?> entity = getHttpEntity(multicloudInstanceRequest); + instanceResponse = restTemplate.exchange(endpoint, HttpMethod.POST, entity, InstanceResponse.class); + return instanceResponse; + } catch (HttpClientErrorException e) { + logger.error("Error Calling Multicloud, e"); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException(e.getResponseBodyAsString()); + } + throw e; + } catch (HttpStatusCodeException e) { + logger.error("Error in Multicloud, e"); + String responseString = e.getResponseBodyAsString(); + InstanceResponse result = new InstanceResponse(responseString.trim()); + return ResponseEntity.status(e.getStatusCode()).body(result); + } + } + + public ResponseEntity<InstanceResponse> getInstanceByInstanceId(String instanceId) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("CnfAdapterService createInstance called"); + ResponseEntity<InstanceResponse> instanceResponse = null; + try { + + // String uri = env.getRequiredProperty("multicloud.endpoint"); //TODO: + // This needs to be added as well + // for configuration + String uri = "http://multicloud-k8s:9015"; // TODO: What is the correct uri? + String path = "/v1/instance/" + instanceId; + String endpoint = UriBuilder.fromUri(uri).path(path).build().toString(); + HttpEntity<?> requestEntity = new HttpEntity<>(getHttpHeaders()); + instanceResponse = restTemplate.exchange(endpoint, HttpMethod.GET, requestEntity, InstanceResponse.class); + return instanceResponse; + } catch (HttpClientErrorException e) { + logger.error("Error Calling Multicloud, e"); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException(e.getResponseBodyAsString()); + } + throw e; + } catch (HttpStatusCodeException e) { + logger.error("Error in Multicloud, e"); + String responseString = e.getResponseBodyAsString(); + InstanceResponse result = new InstanceResponse(responseString.trim()); + return ResponseEntity.status(e.getStatusCode()).body(result); + } + } + + public ResponseEntity<InstanceStatusResponse> getInstanceStatusByInstanceId(String instanceId) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("CnfAdapterService createInstance called"); + ResponseEntity<InstanceStatusResponse> instanceResponse = null; + try { + + // String uri = env.getRequiredProperty("multicloud.endpoint"); //TODO: + // This needs to be added as well + // for configuration + String uri = "http://multicloud-k8s:9015"; // TODO: What is the correct uri? + String path = "/v1/instance/" + instanceId + "/status"; + String endpoint = UriBuilder.fromUri(uri).path(path).build().toString(); + HttpEntity<?> requestEntity = new HttpEntity<>(getHttpHeaders()); + instanceResponse = + restTemplate.exchange(endpoint, HttpMethod.GET, requestEntity, InstanceStatusResponse.class); + return instanceResponse; + } catch (HttpClientErrorException e) { + logger.error("Error Calling Multicloud, e"); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException(e.getResponseBodyAsString()); + } + throw e; + } catch (HttpStatusCodeException e) { + logger.error("Error in Multicloud, e"); + String responseString = e.getResponseBodyAsString(); + InstanceStatusResponse result = new InstanceStatusResponse(responseString.trim()); + return ResponseEntity.status(e.getStatusCode()).body(result); + } + + } + + public ResponseEntity<InstanceMiniResponseList> getInstanceByRBNameOrRBVersionOrProfileName(String rbName, + String rbVersion, String profileName) throws JsonParseException, JsonMappingException, IOException { + + logger.info("CnfAdapterService createInstance called"); + ResponseEntity<InstanceMiniResponseList> instanceMiniResponseList = null; + try { + + // String uri = env.getRequiredProperty("multicloud.endpoint"); //TODO: + // This needs to be added as well + // for configuration + String uri = "http://multicloud-k8s:9015"; // TODO: What is the correct uri? + String path = + "/v1/instance" + "?rb-name=" + rbName + "&rb-version=" + rbVersion + "&profile-name=" + profileName; + String endPoint = uri + path; + HttpEntity<?> requestEntity = new HttpEntity<>(getHttpHeaders()); + instanceMiniResponseList = + restTemplate.exchange(endPoint, HttpMethod.GET, requestEntity, InstanceMiniResponseList.class); + return instanceMiniResponseList; + } catch (HttpClientErrorException e) { + logger.error("Error Calling Multicloud, e"); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException(e.getResponseBodyAsString()); + } + throw e; + } catch (HttpStatusCodeException e) { + logger.error("Error in Multicloud, e"); + String responseString = e.getResponseBodyAsString(); + InstanceMiniResponseList result = new InstanceMiniResponseList(responseString.trim()); + return ResponseEntity.status(e.getStatusCode()).body(result); + } + } + + public ResponseEntity<String> deleteInstanceByInstanceId(String instanceId) + throws JsonParseException, JsonMappingException, IOException { + + logger.info("CnfAdapterService createInstance called"); + ResponseEntity<String> result = null; + try { + + // String uri = env.getRequiredProperty("multicloud.endpoint"); //TODO: + // This needs to be added as well + // for configuration + String uri = "http://multicloud-k8s:9015"; // TODO: What is the correct uri? + String path = "/v1/instance/" + instanceId; + String endpoint = UriBuilder.fromUri(uri).path(path).build().toString(); + HttpEntity<?> requestEntity = new HttpEntity<>(getHttpHeaders()); + result = restTemplate.exchange(endpoint, HttpMethod.DELETE, requestEntity, String.class); + return result; + } catch (HttpClientErrorException e) { + logger.error("Error Calling Multicloud, e"); + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + throw new EntityNotFoundException(e.getResponseBodyAsString()); + } + throw e; + } catch (HttpStatusCodeException e) { + logger.error("Error in Multicloud, e"); + String responseString = e.getResponseBodyAsString(); + return ResponseEntity.status(e.getStatusCode()).body(responseString); + } + } + + protected HttpHeaders getHttpHeaders() { + HttpHeaders headers = new HttpHeaders(); + List<MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + headers.setContentType(MediaType.APPLICATION_JSON); + /* + * try { String userCredentials = CryptoUtils.decrypt(env.getRequiredProperty("mso.cnf.adapter.auth"), + * env.getRequiredProperty("mso.msoKey")); if (userCredentials != null) { headers.add(HttpHeaders.AUTHORIZATION, + * "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); } } catch + * (GeneralSecurityException e) { logger.error("Security exception", e); } + */ + return headers; + } + + protected HttpEntity<?> getHttpEntity(MulticloudInstanceRequest request) { + HttpHeaders headers = getHttpHeaders(); + return new HttpEntity<>(request, headers); + } +} diff --git a/adapters/mso-cnf-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties b/adapters/mso-cnf-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties index f93ec63f37..bccd43aea7 100644 --- a/adapters/mso-cnf-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties +++ b/adapters/mso-cnf-adapter/src/main/resources/META-INF/services/org.onap.so.client.RestProperties @@ -1 +1 @@ -org.onap.so.adapters.nssmf.extclients.aai.AaiClientPropertiesImpl
\ No newline at end of file +org.onap.so.adapters.cnf.extclients.aai.AaiClientPropertiesImpl
\ No newline at end of file diff --git a/adapters/mso-cnf-adapter/src/main/resources/application.yaml b/adapters/mso-cnf-adapter/src/main/resources/application.yaml index 30b1b626a5..5a9adbfd04 100644 --- a/adapters/mso-cnf-adapter/src/main/resources/application.yaml +++ b/adapters/mso-cnf-adapter/src/main/resources/application.yaml @@ -38,14 +38,14 @@ # naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy # enable-lazy-load-no-trans: true server: - port: 9013 + port: 9012 tomcat: max-threads: 50 #mso: # key: 07a7159d3bf51a0e53be7a8f89699be7 # site-name: localSite -# logPath: ./logs/nssmf +# logPath: ./logs/cnf # msb-ip: msb-iag.{{ include "common.namespace" . }} # msb-port: 80 # adapters: diff --git a/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java index 38a10918bc..ee7a771034 100644 --- a/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java +++ b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/CnfAdapterRestTest.java @@ -16,7 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - */ + package org.onap.so.adapters.cnf; @@ -60,3 +60,4 @@ public class CnfAdapterRestTest { } } +*/ diff --git a/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java new file mode 100644 index 0000000000..df21a4212f --- /dev/null +++ b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/rest/CnfAdapterRestTest.java @@ -0,0 +1,161 @@ + +/* + * ============LICENSE_START======================================================= ONAP - SO + * ================================================================================ Copyright (C) 2020 Huawei + * Technologies Co., Ltd. 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.cnf.rest; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.so.adapters.cnf.model.BpmnInstanceRequest; +import org.onap.so.adapters.cnf.model.InstanceMiniResponse; +import org.onap.so.adapters.cnf.model.InstanceMiniResponseList; +import org.onap.so.adapters.cnf.model.InstanceResponse; +import org.onap.so.adapters.cnf.model.InstanceStatusResponse; +import org.onap.so.adapters.cnf.model.MulticloudInstanceRequest; +import org.onap.so.adapters.cnf.model.Resource; +import org.onap.so.adapters.cnf.service.CnfAdapterService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + + +@RunWith(SpringRunner.class) +public class CnfAdapterRestTest { + + @InjectMocks + CnfAdapterRest cnfAdapterRest; + + @Mock + CnfAdapterService cnfAdapterService; + + @Mock + ResponseEntity<InstanceResponse> createInstanceResponse; + + @Mock + ResponseEntity<InstanceMiniResponseList> instacneMiniResponseList; + + @Mock + ResponseEntity<InstanceStatusResponse> instanceStatusResponse; + + @Test + public void healthCheckTest() throws Exception { + + ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK); + CnfAdapterService cnfAdapterService = Mockito.mock(CnfAdapterService.class); + Mockito.when(cnfAdapterService.healthCheck()).thenReturn(response); + cnfAdapterRest.healthCheck(); + Assert.assertNotNull(response); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + } + + @Test + public void createInstanceTest() throws Exception { + + Map<String, String> labels = new HashMap<String, String>(); + labels.put("custom-label-1", "label1"); + Map<String, String> overrideValues = new HashMap<String, String>(); + labels.put("image.tag", "latest"); + labels.put("dcae_collector_ip", "1.2.3.4"); + BpmnInstanceRequest bpmnInstanceRequest = new BpmnInstanceRequest(); + bpmnInstanceRequest.setCloudRegionId("v1"); + bpmnInstanceRequest.setLabels(labels); + bpmnInstanceRequest.setModelInvariantId("krd"); + bpmnInstanceRequest.setModelVersionId("p1"); + bpmnInstanceRequest.setOverrideValues(overrideValues); + bpmnInstanceRequest.setVfModuleUUID("20200824"); + List<Resource> resourceList = new ArrayList<Resource>(); + InstanceResponse instanceResponse = new InstanceResponse(HttpStatus.CREATED.toString()); + instanceResponse.setId("123"); + instanceResponse.setNamespace("testNamespace"); + instanceResponse.setRequest(new MulticloudInstanceRequest()); + instanceResponse.setResources(resourceList); + createInstanceResponse = new ResponseEntity<InstanceResponse>(instanceResponse, HttpStatus.CREATED); + CnfAdapterService cnfAdapterService = Mockito.mock(CnfAdapterService.class); + Mockito.when(cnfAdapterService.createInstance(bpmnInstanceRequest)).thenReturn(createInstanceResponse); + cnfAdapterRest.createInstance(bpmnInstanceRequest); + Assert.assertNotNull(createInstanceResponse); + Assert.assertEquals(HttpStatus.CREATED, createInstanceResponse.getStatusCode()); + } + + @Test + public void getInstanceByInstanceIdTest() throws Exception { + + String instanceId = "123"; + createInstanceResponse = new ResponseEntity<InstanceResponse>(HttpStatus.OK); + CnfAdapterService cnfAdapterService = Mockito.mock(CnfAdapterService.class); + Mockito.when(cnfAdapterService.getInstanceByInstanceId(instanceId)).thenReturn(createInstanceResponse); + cnfAdapterRest.getInstanceByInstanceId(instanceId); + Assert.assertNotNull(createInstanceResponse); + Assert.assertEquals(HttpStatus.OK, createInstanceResponse.getStatusCode()); + } + + @Test + public void deleteInstanceByInstanceIdTest() throws Exception { + + String instanceId = "123"; + ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK); + CnfAdapterService cnfAdapterService = Mockito.mock(CnfAdapterService.class); + Mockito.when(cnfAdapterService.deleteInstanceByInstanceId(instanceId)).thenReturn(response); + cnfAdapterRest.deleteInstanceByInstanceId(instanceId); + Assert.assertNotNull(response); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + } + + @Test + public void getInstanceStatusByInstanceIdTest() throws Exception { + + String instanceId = "123"; + instanceStatusResponse = new ResponseEntity<InstanceStatusResponse>(HttpStatus.OK); + CnfAdapterService cnfAdapterService = Mockito.mock(CnfAdapterService.class); + Mockito.when(cnfAdapterService.getInstanceStatusByInstanceId(instanceId)).thenReturn(instanceStatusResponse); + cnfAdapterRest.getInstanceStatusByInstanceId(instanceId); + Assert.assertNotNull(instanceStatusResponse); + Assert.assertEquals(HttpStatus.OK, instanceStatusResponse.getStatusCode()); + } + + @Test + public void getInstanceByRBNameOrRBVersionOrProfileNameTest() throws Exception { + + String rbName = "xyz"; + String rbVersion = "v1"; + String profileName = "p1"; + InstanceMiniResponse instanceMiniResponse = new InstanceMiniResponse(HttpStatus.OK.toString()); + List<InstanceMiniResponse> instancList = new ArrayList<InstanceMiniResponse>(); + instancList.add(instanceMiniResponse); + InstanceMiniResponseList instanceMiniRespList = new InstanceMiniResponseList(HttpStatus.OK.toString()); + instanceMiniRespList.setInstancList(instancList); + instanceMiniRespList.setErrorMsg(HttpStatus.OK.toString()); + ResponseEntity<InstanceMiniResponseList> respone = + new ResponseEntity<InstanceMiniResponseList>(instanceMiniRespList, HttpStatus.OK); + CnfAdapterService cnfAdapterService = Mockito.mock(CnfAdapterService.class); + Mockito.when(cnfAdapterService.getInstanceByRBNameOrRBVersionOrProfileName(rbName, rbVersion, profileName)) + .thenReturn(instacneMiniResponseList); + cnfAdapterRest.getInstanceByRBNameOrRBVersionOrProfileName(rbName, rbVersion, profileName); + Assert.assertNotNull(instacneMiniResponseList); + Assert.assertEquals(HttpStatus.OK.toString(), instanceMiniRespList.getErrorMsg()); + } + +} + diff --git a/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java new file mode 100644 index 0000000000..0d3d8598bb --- /dev/null +++ b/adapters/mso-cnf-adapter/src/test/java/org/onap/so/adapters/cnf/service/CnfAdapterServiceTest.java @@ -0,0 +1,139 @@ +package org.onap.so.adapters.cnf.service; + +import javax.ws.rs.InternalServerErrorException; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.so.adapters.cnf.model.BpmnInstanceRequest; +import org.onap.so.adapters.cnf.model.InstanceMiniResponseList; +import org.onap.so.adapters.cnf.model.InstanceResponse; +import org.onap.so.adapters.cnf.model.InstanceStatusResponse; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +@RunWith(SpringRunner.class) +public class CnfAdapterServiceTest { + + @InjectMocks + CnfAdapterService cnfAdapterService; + + @Mock + ResponseEntity<InstanceResponse> createInstanceResponse; + + @Mock + ResponseEntity<InstanceMiniResponseList> instacneMiniResponseList; + + @Mock + ResponseEntity<InstanceStatusResponse> instanceStatusResponse; + + @Mock + private RestTemplate restTemplate; + + @Test + public void healthCheckTest() throws Exception { + + ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK); + + Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<String>>any())).thenReturn(response); + + ResponseEntity<String> actualResponse = cnfAdapterService.healthCheck(); + Assert.assertNotNull(actualResponse); + Assert.assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + + } + + @Test + public void createInstanceTest() throws Exception { + + ResponseEntity<InstanceResponse> response = new ResponseEntity<InstanceResponse>(HttpStatus.OK); + BpmnInstanceRequest bpmnInstanceRequest = new BpmnInstanceRequest(); + bpmnInstanceRequest.setK8sRBProfileName("k8sRBProfileName"); + Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<InstanceResponse>>any())).thenReturn(response); + + ResponseEntity<InstanceResponse> actualResponse = cnfAdapterService.createInstance(bpmnInstanceRequest); + Assert.assertNotNull(response); + Assert.assertEquals(actualResponse.getStatusCode(), response.getStatusCode()); + + } + + @Test + public void createInstanceExceptionTest() throws Exception { + + BpmnInstanceRequest bpmnInstanceRequest = new BpmnInstanceRequest(); + ResponseEntity<InstanceResponse> response = cnfAdapterService.createInstance(bpmnInstanceRequest); + Assert.assertNull(response); + + } + + @Test + public void getInstanceByInstanceIdTest() throws Exception { + + ResponseEntity<InstanceResponse> response = new ResponseEntity<InstanceResponse>(HttpStatus.OK); + String instanceId = "123"; + Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<InstanceResponse>>any())).thenReturn(response); + + ResponseEntity<InstanceResponse> actualResponse = cnfAdapterService.getInstanceByInstanceId(instanceId); + Assert.assertNotNull(actualResponse); + Assert.assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + + } + + @Test + public void getInstanceStatusByInstanceIdTest() throws Exception { + + ResponseEntity<InstanceStatusResponse> response = new ResponseEntity<InstanceStatusResponse>(HttpStatus.OK); + String instanceId = "123"; + Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<InstanceStatusResponse>>any())).thenReturn(response); + + ResponseEntity<InstanceStatusResponse> actualResponse = + cnfAdapterService.getInstanceStatusByInstanceId(instanceId); + Assert.assertNotNull(actualResponse); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + + } + + @Test + public void getInstanceByRBNameOrRBVersionOrProfileNameTest() throws Exception { + + ResponseEntity<InstanceMiniResponseList> response = new ResponseEntity<InstanceMiniResponseList>(HttpStatus.OK); + String rbName = "xyz"; + String rbVersion = "v1"; + String profileName = "p1"; + + Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<InstanceMiniResponseList>>any())).thenReturn(response); + + ResponseEntity<InstanceMiniResponseList> actualResponse = + cnfAdapterService.getInstanceByRBNameOrRBVersionOrProfileName(rbName, rbVersion, profileName); + Assert.assertNotNull(actualResponse); + Assert.assertEquals(HttpStatus.OK, actualResponse.getStatusCode()); + + } + + @Test + public void deleteInstanceByInstanceIdTest() throws Exception { + + ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK); + String instanceId = "123"; + Mockito.when(restTemplate.exchange(Matchers.anyString(), Matchers.any(HttpMethod.class), + Matchers.<HttpEntity<?>>any(), Matchers.<Class<String>>any())).thenReturn(response); + + ResponseEntity<String> actualResponse = cnfAdapterService.deleteInstanceByInstanceId(instanceId); + Assert.assertNotNull(response); + Assert.assertEquals(HttpStatus.OK, response.getStatusCode()); + + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java index ed327fd981..9df20bac1c 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/enums/ActionType.java @@ -20,26 +20,36 @@ package org.onap.so.adapters.nssmf.enums; +import lombok.Getter; + +@Getter public enum ActionType { - ALLOCATE, + ALLOCATE("allocate"), + + DEALLOCATE("deallocate"), + + CREATE("create"), + + TERMINATE("terminate"), - DEALLOCATE, + ACTIVATE("activate"), - CREATE, + DEACTIVATE("deactivate"), - TERMINATE, + QUERY_JOB_STATUS("query_job_status"), - ACTIVATE, + MODIFY_BY_ID("modify_by_id"), - DEACTIVATE, + MODIFY("modify"), - QUERY_JOB_STATUS, + QUERY_NSSI_SELECTION_CAPABILITY("query_nssi_selection_capability"), - MODIFY_BY_ID, + QUERY_SUB_NET_CAPABILITY("query_sub_net_capability"),; - MODIFY, + private String type; - QUERY_NSSI_SELECTION_CAPABILITY, - QUERY_SUB_NET_CAPABILITY + ActionType(String type) { + this.type = type; + } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java index 3f2e5b23f2..442339d9fe 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.java @@ -24,9 +24,9 @@ package org.onap.so.adapters.nssmf.extclients.aai; import org.onap.aai.domain.yang.EsrSystemInfoList; import org.onap.aai.domain.yang.EsrThirdpartySdncList; import org.onap.aai.domain.yang.ServiceInstance; -import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -47,7 +47,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public EsrThirdpartySdncList invokeGetThirdPartySdncList() { return aaiClientProvider.getAaiClient() - .get(EsrThirdpartySdncList.class, AAIUriFactory.createResourceUri(AAIObjectType.THIRDPARTY_SDNC_LIST)) + .get(EsrThirdpartySdncList.class, + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.externalSystem().esrThirdpartySdncList())) .orElseGet(() -> { logger.debug("No VNFMs in AAI"); return null; @@ -58,7 +59,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { public EsrSystemInfoList invokeGetThirdPartySdncEsrSystemInfo(String sdncId) { return aaiClientProvider.getAaiClient() .get(EsrSystemInfoList.class, - AAIUriFactory.createResourceUri(AAIObjectType.THIRDPARTY_SDNC_SYSTEM_INFO_LIST, sdncId)) + AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.externalSystem().esrThirdpartySdnc((sdncId)))) .orElseGet(() -> { logger.debug("VNFM not found in AAI"); return null; @@ -69,8 +71,8 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { @Override public void invokeCreateServiceInstance(ServiceInstance nssiInstance, String globalSubscriberId, String serviceType, String serviceInstanceId) { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, - serviceType, serviceInstanceId); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business() + .customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(serviceInstanceId)); aaiClientProvider.getAaiClient().create(uri, nssiInstance); } } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java index 16a5b2ada0..d8a9088a42 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/ExternalNssmfManager.java @@ -92,8 +92,13 @@ public abstract class ExternalNssmfManager extends BaseNssmfManager { private RestResponse doResponseStatus(ResourceOperationStatus status) throws ApplicationException { RestResponse restResponse = sendRequest(null); - ResponseDescriptor rspDesc = - unMarshal(restResponse.getResponseContent(), JobStatusResponse.class).getResponseDescriptor(); + JobStatusResponse jobStatusResponse = unMarshal(restResponse.getResponseContent(), JobStatusResponse.class); + + ResponseDescriptor rspDesc = jobStatusResponse.getResponseDescriptor(); + rspDesc.setNssiId(status.getResourceInstanceID()); + + jobStatusResponse.setResponseDescriptor(rspDesc); + restResponse.setResponseContent(marshal(jobStatusResponse)); updateRequestDbJobStatus(rspDesc, status, restResponse); return restResponse; } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java index f439b400d9..348bf12bcb 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/manager/impl/InternalNssmfManager.java @@ -76,6 +76,7 @@ public abstract class InternalNssmfManager extends BaseNssmfManager { descriptor.setStatus(status.getStatus()); descriptor.setStatusDescription(status.getStatusDescription()); descriptor.setProgress(Integer.parseInt(status.getProgress())); + descriptor.setNssiId(status.getResourceInstanceID()); // descriptor.setResponseId(status.getOperationId()); return restUtil.createResponse(200, marshal(descriptor)); } diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java index 5f7fe76b72..5b53856f2f 100644 --- a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/service/impl/NssmfManagerServiceImpl.java @@ -106,7 +106,7 @@ public class NssmfManagerServiceImpl implements NssmfManagerService { public ResponseEntity queryNSSISelectionCapability(NssmfAdapterNBIRequest nbiRequest) { EsrInfo esrInfo = nbiRequest.getEsrInfo(); try { - return buildResponse(buildNssmfManager(esrInfo, ActionType.QUERY_JOB_STATUS, null) + return buildResponse(buildNssmfManager(esrInfo, ActionType.QUERY_NSSI_SELECTION_CAPABILITY, null) .queryNSSISelectionCapability(nbiRequest)); } catch (ApplicationException e) { return e.buildErrorResponse(); @@ -117,8 +117,8 @@ public class NssmfManagerServiceImpl implements NssmfManagerService { public ResponseEntity querySubnetCapability(NssmfAdapterNBIRequest nbiRequest) { EsrInfo esrInfo = nbiRequest.getEsrInfo(); try { - return buildResponse( - buildNssmfManager(esrInfo, ActionType.QUERY_JOB_STATUS, null).querySubnetCapability(nbiRequest)); + return buildResponse(buildNssmfManager(esrInfo, ActionType.QUERY_SUB_NET_CAPABILITY, null) + .querySubnetCapability(nbiRequest)); } catch (ApplicationException e) { return e.buildErrorResponse(); } diff --git a/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java b/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java index 67cd913b3e..f150f47f4f 100644 --- a/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java +++ b/adapters/mso-nssmf-adapter/src/test/java/org/onap/so/adapters/nssmf/NssmfAdapterRestTest.java @@ -20,6 +20,17 @@ package org.onap.so.adapters.nssmf; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; +import static org.onap.so.beans.nsmf.NetworkType.CORE; +import static org.onap.so.beans.nsmf.ResourceSharingLevel.NON_SHARED; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.LinkedList; @@ -56,19 +67,9 @@ import org.onap.so.beans.nsmf.NssiResponse; import org.onap.so.beans.nsmf.PerfReq; import org.onap.so.beans.nsmf.PerfReqEmbb; import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; +import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; -import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; -import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; -import static org.onap.so.beans.nsmf.NetworkType.CORE; -import static org.onap.so.beans.nsmf.ResourceSharingLevel.NON_SHARED; @RunWith(SpringRunner.class) public class NssmfAdapterRestTest { @@ -281,7 +282,7 @@ public class NssmfAdapterRestTest { // @Test public void testAllocateJsonSerDeSer() throws Exception { - assertEquals(marshal(allocateNssi()), ALLOCATE); + JSONAssert.assertEquals(marshal(allocateNssi()), ALLOCATE, false); NssiAllocateRequest all = unMarshal(ALLOCATE, NssiAllocateRequest.class); assertNotNull(all); assertNotNull(all.getAllocateCnNssi()); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java index 2849907e38..bb2c938940 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java @@ -5,12 +5,11 @@ import java.util.Optional; import org.onap.aai.domain.yang.CloudRegion; import org.onap.aai.domain.yang.Complex; import org.onap.aai.domain.yang.NetworkTechnologies; -import org.onap.aaiclient.client.aai.AAIObjectPlurals; -import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.AAIResourcesClient; import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.NetworkTechnologyReference; import org.onap.so.db.catalog.client.CatalogDbClient; @@ -68,11 +67,12 @@ public class CloudRestImpl { if (complex.isPresent()) { cloudRegion.setComplexName(complex.get().getComplexName()); } - AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, - cloudRegion.getCloudOwner(), cloudRegion.getCloudRegionId()); + AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudRegion.getCloudOwner(), cloudRegion.getCloudRegionId())); getAaiClient().createIfNotExists(cloudRegionURI, Optional.of(cloudRegion)); if (complex.isPresent()) { - AAIResourceUri complexURI = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, cloudSite.getClli()); + AAIResourceUri complexURI = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().complex(cloudSite.getClli())); getAaiClient().connect(cloudRegionURI, complexURI); } createCloudRegionNetworkTechnologyRelationship(cloudSite, cloudRegionURI); @@ -88,18 +88,21 @@ public class CloudRestImpl { } protected Optional<Complex> retrieveComplex(CloudSite cloudSite) { - AAIResourceUri complexURI = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, cloudSite.getClli()); + AAIResourceUri complexURI = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().complex(cloudSite.getClli())); return getAaiClient().get(Complex.class, complexURI); } protected void linkCloudAndTechnology(String networkTechnologyName, AAIResourceUri cloudRegionURI) { - AAIPluralResourceUri technologyPluralUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_TECHNOLOGY) - .queryParam("network-technology-name", networkTechnologyName); + AAIPluralResourceUri technologyPluralUri = + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().networkTechnologies()) + .queryParam("network-technology-name", networkTechnologyName); Optional<NetworkTechnologies> networkTechnology = getAaiClient().get(NetworkTechnologies.class, technologyPluralUri); if (networkTechnology.isPresent()) { - AAIResourceUri networkTechnologyURI = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_TECHNOLOGY, - networkTechnology.get().getNetworkTechnology().get(0).getNetworkTechnologyId()); + AAIResourceUri networkTechnologyURI = + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().networkTechnology( + networkTechnology.get().getNetworkTechnology().get(0).getNetworkTechnologyId())); getAaiClient().connect(cloudRegionURI, networkTechnologyURI); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/delete/DeleteAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/delete/DeleteAAIInventory.java index 1f0422b0b2..22e6b1fc22 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/delete/DeleteAAIInventory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/delete/DeleteAAIInventory.java @@ -54,9 +54,9 @@ public class DeleteAAIInventory { CloudSite cloudSite = cloudConfig.getCloudSite(cloudInformation.getRegionId()) .orElseThrow(() -> new MsoCloudSiteNotFound(cloudInformation.getRegionId())); CloudIdentity cloudIdentity = cloudSite.getIdentityService(); - HeatBridgeApi heatBridgeClient = - new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, cloudInformation.getOwner(), - cloudInformation.getRegionId(), cloudSite.getRegionId(), cloudInformation.getTenantId()); + HeatBridgeApi heatBridgeClient = new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, + cloudInformation.getOwner(), cloudInformation.getRegionId(), cloudSite.getRegionId(), + cloudInformation.getTenantId(), cloudInformation.getNodeType()); heatBridgeClient.authenticate(); heatBridgeClient.deleteVfModuleData(cloudInformation.getVnfId(), cloudInformation.getVfModuleId()); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java index 1445622357..6f87b6b309 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java @@ -27,12 +27,13 @@ import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VfModules; import org.onap.aai.domain.yang.Vserver; -import org.onap.aaiclient.client.aai.AAIObjectPlurals; import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types; import org.onap.aaiclient.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; @@ -49,20 +50,20 @@ public class AuditVServer extends AbstractAudit { public void auditVservers(AAIObjectAuditList aaiObjectAuditList) { aaiObjectAuditList.getAuditList().forEach(aaiObjectAudit -> { - boolean vserverExist = getAaiClient().exists(AAIUriFactory - .createResourceFromExistingURI(AAIObjectType.VSERVER, aaiObjectAudit.getResourceURI())); + boolean vserverExist = getAaiClient().exists( + AAIUriFactory.createResourceFromExistingURI(Types.VSERVER, aaiObjectAudit.getResourceURI())); aaiObjectAudit.setDoesObjectExist(vserverExist); }); } public Optional<AAIObjectAuditList> auditVserversThroughRelationships(String genericVnfId, String vfModuleName) { AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, genericVnfId) - .queryParam("vf-module-name", vfModuleName); + AAIPluralResourceUri uri = + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModules()) + .queryParam("vf-module-name", vfModuleName); Optional<AAIResultWrapper> wrapper = getAaiClient().getFirstWrapper(VfModules.class, VfModule.class, uri); if (wrapper.isPresent() && wrapper.get().getRelationships().isPresent()) { - List<AAIResourceUri> relatedVservers = - wrapper.get().getRelationships().get().getRelatedUris(AAIObjectType.VSERVER); + List<AAIResourceUri> relatedVservers = wrapper.get().getRelationships().get().getRelatedUris(Types.VSERVER); if (!relatedVservers.isEmpty()) { relatedVservers.forEach(vserverUri -> { Optional<Vserver> vserver = getAaiClient().get(vserverUri).asBean(Vserver.class); @@ -70,7 +71,7 @@ public class AuditVServer extends AbstractAudit { BeanUtils.copyProperties(vserver, vServerShallow); AAIObjectAudit vServerAudit = new AAIObjectAudit(); vServerAudit.setAaiObject(vServerShallow); - vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + vServerAudit.setAaiObjectType(Types.VSERVER.typeName()); vServerAudit.setDoesObjectExist(true); auditList.getAuditList().add(vServerAudit); }); @@ -103,8 +104,8 @@ public class AuditVServer extends AbstractAudit { String cloudRegion) { AAIObjectAuditList auditList = new AAIObjectAuditList(); AAIObjectAudit vServerAudit = new AAIObjectAudit(); - AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, vServer.getVserverId()); + AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver(vServer.getVserverId())); Vserver vServerShallow = new Vserver(); BeanUtils.copyProperties(vServer, vServerShallow, "LInterfaces"); boolean vServerExists = getAaiClient().exists(vserverURI); @@ -112,7 +113,7 @@ public class AuditVServer extends AbstractAudit { vServerAudit.setAaiObject(vServerShallow); vServerAudit.setDoesObjectExist(vServerExists); vServerAudit.setResourceURI(vserverURI.build()); - vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + vServerAudit.setAaiObjectType(Types.VSERVER.typeName()); auditList.getAuditList().add(vServerAudit); if (vServer.getLInterfaces() != null) { vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll( @@ -126,8 +127,9 @@ public class AuditVServer extends AbstractAudit { String cloudOwner, String cloudRegion) { AAIObjectAuditList auditList = new AAIObjectAuditList(); AAIObjectAudit lInterfaceAudit = new AAIObjectAudit(); - AAIResourceUri linterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegion, tenantId, vServerId, lInterface.getInterfaceName()); + AAIResourceUri linterfaceURI = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion) + .tenant(tenantId).vserver(vServerId).lInterface(lInterface.getInterfaceName())); Optional<LInterface> queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI); if (queriedLInterface.isPresent()) { lInterfaceAudit.setDoesObjectExist(true); @@ -135,7 +137,7 @@ public class AuditVServer extends AbstractAudit { } lInterfaceAudit.setAaiObject(lInterface); lInterfaceAudit.setResourceURI(linterfaceURI.build()); - lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName()); + lInterfaceAudit.setAaiObjectType(Types.L_INTERFACE.typeName()); auditList.getAuditList().add(lInterfaceAudit); logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(), lInterface.getInterfaceName(), lInterfaceAudit.isDoesObjectExist()); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java index 3ff15ffe2f..c58e568ea4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java @@ -37,8 +37,9 @@ import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vlan; import org.onap.aai.domain.yang.Vlans; import org.onap.aai.domain.yang.Vserver; -import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.openstack.utils.MsoHeatUtils; @@ -260,10 +261,12 @@ public class HeatStackAudit { Vserver vServerShallow = new Vserver(); BeanUtils.copyProperties(vServer, vServerShallow); aaiObjectAudit.setAaiObject(vServerShallow); - aaiObjectAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); - aaiObjectAudit.setResourceURI(AAIUriFactory - .createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenantId, vServer.getVserverId()) - .build()); + aaiObjectAudit.setAaiObjectType(Types.VSERVER.typeName()); + aaiObjectAudit + .setResourceURI(AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver(vServer.getVserverId())) + .build()); return aaiObjectAudit; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java index 12751f8c27..3f79c43bf8 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java @@ -64,9 +64,9 @@ public class CreateAAIInventory { List<String> oobMgtNetNames = new ArrayList<>(); - HeatBridgeApi heatBridgeClient = - new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, cloudInformation.getOwner(), - cloudInformation.getRegionId(), cloudSite.getRegionId(), cloudInformation.getTenantId()); + HeatBridgeApi heatBridgeClient = new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, + cloudInformation.getOwner(), cloudInformation.getRegionId(), cloudSite.getRegionId(), + cloudInformation.getTenantId(), cloudInformation.getNodeType()); heatBridgeClient.authenticate(); @@ -119,8 +119,8 @@ public class CreateAAIInventory { "Successfully queried neutron resources and built AAI actions to add l-interfaces to vservers."); // Update AAI - logger.debug("Current Dry Run Value: {}", env.getProperty("heatBridgeDryrun", Boolean.class, true)); - heatBridgeClient.submitToAai(env.getProperty("heatBridgeDryrun", Boolean.class, true)); + logger.debug("Current Dry Run Value: {}", env.getProperty("heatBridgeDryrun", Boolean.class, false)); + heatBridgeClient.submitToAai(env.getProperty("heatBridgeDryrun", Boolean.class, false)); } catch (Exception ex) { logger.debug("Heatbrige failed for stackId: " + cloudInformation.getTemplateInstanceId(), ex); } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java index a4e6cccc06..bafba3e901 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java @@ -155,7 +155,7 @@ public interface HeatBridgeApi { * @param cloudOwner */ void buildAddVserverLInterfacesToAaiAction(List<Resource> stackResources, List<String> oobMgtNetIds, - String cloudOwner); + String cloudOwner) throws HeatBridgeException; /** * Query and build AAI actions for Openstack Compute resources to AAI's pserver and pinterface objects diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java index 7e25ed600f..90a578d3b4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java @@ -32,6 +32,8 @@ */ package org.onap.so.heatbridge; +import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -60,22 +62,31 @@ import org.onap.aai.domain.yang.SriovPf; import org.onap.aai.domain.yang.SriovPfs; import org.onap.aai.domain.yang.Subnets; import org.onap.aai.domain.yang.SriovVf; -import org.onap.aai.domain.yang.SriovVfs; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.Vlan; -import org.onap.aai.domain.yang.Vlans; import org.onap.aai.domain.yang.Vserver; -import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIDSLQueryClient; import org.onap.aaiclient.client.aai.AAIResourcesClient; import org.onap.aaiclient.client.aai.AAISingleTransactionClient; import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.aaiclient.client.aai.entities.Relationships; +import org.onap.aaiclient.client.aai.entities.Results; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types; +import org.onap.aaiclient.client.graphinventory.Format; +import org.onap.aaiclient.client.graphinventory.entities.DSLQuery; +import org.onap.aaiclient.client.graphinventory.entities.DSLQueryBuilder; +import org.onap.aaiclient.client.graphinventory.entities.DSLStartNode; +import org.onap.aaiclient.client.graphinventory.entities.Node; +import org.onap.aaiclient.client.graphinventory.entities.Start; +import org.onap.aaiclient.client.graphinventory.entities.TraversalBuilder; +import org.onap.aaiclient.client.graphinventory.entities.__; import org.onap.aaiclient.client.graphinventory.entities.uri.Depth; import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed; import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.cloud.resource.beans.NodeType; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.ServerType; import org.onap.so.heatbridge.constants.HeatBridgeConstants; @@ -97,6 +108,8 @@ import org.openstack4j.model.network.Subnet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; @@ -111,21 +124,34 @@ public class HeatBridgeImpl implements HeatBridgeApi { private static final String ERR_MSG_NULL_OS_CLIENT = "Initialization error: Null openstack client. Authenticate with Keystone first."; private static final String OOB_MGT_NETWORK_IDENTIFIER = "Management"; + + protected static final String DIRECT = "direct"; + protected static final String PCI_SLOT = "pci_slot"; + protected static final String OVSNET = "ovsnet"; + protected static final String SRIOV = "SRIOV"; + protected static final String RESOURCE_LINK = "resource-link"; + + protected static final Object PRIVATE_VLANS = "private_vlans"; + protected static final Object PUBLIC_VLANS = "public_vlans"; + + protected ObjectMapper mapper = new ObjectMapper(); + private OpenstackClient osClient; private AAIResourcesClient resourcesClient; + private AAIDSLQueryClient aaiDSLClient; private AAISingleTransactionClient transaction; private String cloudOwner; private String cloudRegionId; private String regionId; private String tenantId; + private NodeType nodeType; private AaiHelper aaiHelper = new AaiHelper(); private CloudIdentity cloudIdentity; private Environment env; - public HeatBridgeImpl(AAIResourcesClient resourcesClient, final CloudIdentity cloudIdentity, @Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String regionId, - @Nonnull final String tenantId) { + @Nonnull final String tenantId, @Nonnull final NodeType nodeType) { Objects.requireNonNull(cloudOwner, "Null cloud-owner value!"); Objects.requireNonNull(cloudRegionId, "Null cloud-region identifier!"); Objects.requireNonNull(tenantId, "Null tenant identifier!"); @@ -137,6 +163,7 @@ public class HeatBridgeImpl implements HeatBridgeApi { this.regionId = regionId; this.tenantId = tenantId; this.resourcesClient = resourcesClient; + this.nodeType = nodeType; if (resourcesClient != null) this.transaction = resourcesClient.beginSingleTransaction(); if (SpringContextHelper.getAppContext() != null) @@ -202,6 +229,11 @@ public class HeatBridgeImpl implements HeatBridgeApi { return serverIds.stream().map(serverId -> osClient.getServerById(serverId)).collect(Collectors.toList()); } + + protected Server getOpenstackServerById(String deviceId) { + return osClient.getServerById(deviceId); + } + @Override public List<Network> getAllOpenstackProviderNetworks(final List<Resource> stackResources) { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); @@ -241,7 +273,8 @@ public class HeatBridgeImpl implements HeatBridgeApi { l3Network.setRelationshipList(relationshipList); transaction.createIfNotExists( - AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, l3Network.getNetworkId()), + AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.network().l3Network(l3Network.getNetworkId())), Optional.of(l3Network)); } }); @@ -253,8 +286,8 @@ public class HeatBridgeImpl implements HeatBridgeApi { for (org.openstack4j.model.compute.Image image : images) { Image aaiImage = aaiHelper.buildImage(image); try { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, cloudRegionId, - aaiImage.getImageId()); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegionId).image(aaiImage.getImageId())); if (!resourcesClient.exists(uri)) { transaction.create(uri, aaiImage); logger.debug("Queuing AAI command to add image: " + aaiImage.getImageId()); @@ -274,8 +307,8 @@ public class HeatBridgeImpl implements HeatBridgeApi { for (org.openstack4j.model.compute.Flavor flavor : flavors) { Flavor aaiFlavor = aaiHelper.buildFlavor(flavor); try { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, cloudRegionId, - aaiFlavor.getFlavorId()); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegionId).flavor(aaiFlavor.getFlavorId())); transaction.createIfNotExists(uri, Optional.of(aaiFlavor)); } catch (WebApplicationException e) { throw new HeatBridgeException( @@ -293,20 +326,24 @@ public class HeatBridgeImpl implements HeatBridgeApi { // Build vserver relationships to: image, flavor, pserver, vf-module vserver.setRelationshipList( aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId, vfModuleId, server)); - transaction.createIfNotExists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegionId, tenantId, vserver.getVserverId()), Optional.of(vserver)); + transaction.createIfNotExists( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId).vserver(vserver.getVserverId())), + Optional.of(vserver)); }); } @Override public void buildAddVserverLInterfacesToAaiAction(final List<Resource> stackResources, - final List<String> oobMgtNetIds, String cloudOwner) { + final List<String> oobMgtNetIds, String cloudOwner) throws HeatBridgeException { Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); List<String> portIds = extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_PORT_RESOURCE_TYPE); + if (portIds == null) return; for (String portId : portIds) { + boolean isL2Multicast = false; Port port = osClient.getPortById(portId); Network network = osClient.getNetworkById(port.getNetworkId()); LInterface lIf = new LInterface(); @@ -317,12 +354,7 @@ public class HeatBridgeImpl implements HeatBridgeApi { lIf.setIsPortMirrored(false); lIf.setIsIpUnnumbered(false); lIf.setInMaint(false); - if (oobMgtNetIds != null && oobMgtNetIds.contains(port.getNetworkId())) { - lIf.setInterfaceRole(OOB_MGT_NETWORK_IDENTIFIER); - } else { - lIf.setInterfaceRole(port.getvNicType()); - } - boolean isL2Multicast = false; + if (port.getProfile() != null && port.getProfile().get("trusted") != null) { String trusted = port.getProfile().get("trusted").toString(); if (Boolean.parseBoolean(trusted)) { @@ -330,19 +362,46 @@ public class HeatBridgeImpl implements HeatBridgeApi { } } lIf.setL2Multicasting(isL2Multicast); + lIf.setInterfaceType(getInterfaceType(nodeType, port.getvNicType())); + lIf.setRelationshipList(new RelationshipList()); - transaction.createIfNotExists(AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegionId, tenantId, port.getDeviceId(), lIf.getInterfaceName()), Optional.of(lIf)); + if (oobMgtNetIds != null && oobMgtNetIds.contains(port.getNetworkId())) { + lIf.setInterfaceRole(OOB_MGT_NETWORK_IDENTIFIER); + } else { + lIf.setInterfaceRole(port.getvNicType()); + } + + // Update l-interface to the vserver + transaction.createIfNotExists( + AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId) + .tenant(tenantId).vserver(port.getDeviceId()).lInterface(lIf.getInterfaceName())), + Optional.of(lIf)); updateLInterfaceIps(port, lIf); + if (cloudOwner.equals(env.getProperty("mso.cloudOwner.included", ""))) { - updateLInterfaceVlan(port, lIf); + Server server = getOpenstackServerById(port.getDeviceId()); + updateLInterfaceVlan(port, lIf, server.getHypervisorHostname()); } updateSriovPfToPserver(port, lIf); } } + protected String getInterfaceType(NodeType nodeType, String nicType) { + logger.debug("nicType: " + nicType + "nodeType: " + nodeType); + if (DIRECT.equalsIgnoreCase(nicType)) { + return SRIOV; + } else { + if (nodeType == NodeType.GREENFIELD) { + return NodeType.GREENFIELD.getNetworkTechnologyName(); + } else { + return NodeType.BROWNFIELD.getNetworkTechnologyName(); + } + } + } + @Override public void createPserversAndPinterfacesIfNotPresentInAai(final List<Resource> stackResources) throws HeatBridgeException { @@ -356,8 +415,10 @@ public class HeatBridgeImpl implements HeatBridgeApi { for (String portId : portIds) { Port port = osClient.getPortById(portId); if (port.getvNicType().equalsIgnoreCase(HeatBridgeConstants.OS_SRIOV_PORT_TYPE)) { - createPServerPInterfaceIfNotExists(serverHostnames.get(port.getHostId()).getHostname(), - aaiHelper.buildPInterface(port)); + Pserver foundServer = serverHostnames.get(port.getHostId()); + if (foundServer != null) { + createPServerPInterfaceIfNotExists(foundServer.getHostname(), aaiHelper.buildPInterface(port)); + } } } } @@ -369,6 +430,7 @@ public class HeatBridgeImpl implements HeatBridgeApi { for (Server server : osServers) { Pserver pserver = aaiHelper.buildPserver(server); if (pserver != null) { + logger.debug("Adding Pserver: " + server.getHost()); pserverMap.put(server.getHost(), pserver); } } @@ -392,18 +454,21 @@ public class HeatBridgeImpl implements HeatBridgeApi { private void createPServerIfNotExists(Map<String, Pserver> serverHostnames) { for (Pserver pserver : serverHostnames.values()) { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, pserver.getHostname()); + AAIResourceUri uri = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserver.getHostname())); resourcesClient.createIfNotExists(uri, Optional.of(pserver)); } } private void createPServerPInterfaceIfNotExists(String pserverHostname, PInterface pInterface) { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.P_INTERFACE, pserverHostname, - pInterface.getInterfaceName()); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .pserver(pserverHostname).pInterface(pInterface.getInterfaceName())); resourcesClient.createIfNotExists(uri, Optional.of(pInterface)); } - private void updateLInterfaceVlan(final Port port, final LInterface lIf) { + private void updateLInterfaceVlan(final Port port, final LInterface lIf, final String hostName) + throws HeatBridgeException { + // add back all vlan logic Vlan vlan = new Vlan(); Network network = osClient.getNetworkById(port.getNetworkId()); if (network.getNetworkType() != null && network.getNetworkType().equals(NetworkType.VLAN)) { @@ -413,7 +478,6 @@ public class HeatBridgeImpl implements HeatBridgeApi { vlan.setInMaint(false); vlan.setIsIpUnnumbered(false); vlan.setIsPrivate(false); - transaction .createIfNotExists( AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() @@ -422,6 +486,32 @@ public class HeatBridgeImpl implements HeatBridgeApi { Optional.of(vlan)); } + if (nodeType == NodeType.GREENFIELD) { + validatePhysicalNetwork(port, network); + processOVS(lIf, hostName, NodeType.GREENFIELD.getInterfaceName()); + } else { + processOVS(lIf, hostName, NodeType.BROWNFIELD.getInterfaceName()); + } + + List<String> privateVlans = (ArrayList<String>) port.getProfile().get(PRIVATE_VLANS); + List<String> publicVlans = (ArrayList<String>) port.getProfile().get(PUBLIC_VLANS); + List<String> vlans = null; + if (publicVlans != null && !publicVlans.isEmpty()) { + vlans = publicVlans.stream().filter(publicVlan -> !Strings.isNullOrEmpty(publicVlan)) + .collect(Collectors.toList()); + } else { + vlans = new ArrayList<>(); + } + + if (privateVlans != null && !privateVlans.isEmpty()) { + List<String> temp = privateVlans.stream().filter(privateVlan -> !Strings.isNullOrEmpty(privateVlan)) + .collect(Collectors.toList()); + vlans.addAll(temp); + } + vlans.stream().forEach(vlanLocal -> logger.debug("Vlan Id: {}", vlanLocal)); + + processVlanTag(lIf, vlans); + if (port.getvNicType() != null && port.getvNicType().equalsIgnoreCase(HeatBridgeConstants.OS_SRIOV_PORT_TYPE)) { SriovVf sriovVf = new SriovVf(); sriovVf.setPciId(port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString()); @@ -439,6 +529,49 @@ public class HeatBridgeImpl implements HeatBridgeApi { } } + protected String createVlanTagUri(String vlanIdOuter) throws HeatBridgeException { + int vlanOuterInt = Integer.parseInt(vlanIdOuter); + DSLQueryBuilder<Start, Node> builder = TraversalBuilder + .fragment(new DSLStartNode(Types.CLOUD_REGION, __.key("cloud-owner", cloudOwner), + __.key("cloud-region-id", cloudRegionId))) + .to(__.node(Types.VLAN_RANGE)) + .to(__.node(Types.VLAN_TAG, __.key("vlan-id-outer", vlanOuterInt)).output()); + String results = getAAIDSLClient().query(Format.PATHED, new DSLQuery(builder.build())); + Optional<String> vlanTagURI = findLinkedURI(results); + if (vlanTagURI.isPresent()) + return vlanTagURI.get(); + else + throw new HeatBridgeException("Cannot find VlanTag Related Link " + vlanIdOuter); + } + + + protected void processVlanTag(LInterface lInterface, List<String> vlanTags) throws HeatBridgeException { + for (String vlanTag : vlanTags) { + Relationship vlanTagRelationship = new Relationship(); + vlanTagRelationship.setRelatedLink(createVlanTagUri(vlanTag)); + lInterface.getRelationshipList().getRelationship().add(vlanTagRelationship); + } + } + + protected void validatePhysicalNetwork(Port neutronPort, Network network) throws HeatBridgeException { + String physicalNetworkType = network.getProviderPhyNet(); + if (!OVSNET.equalsIgnoreCase(physicalNetworkType)) { + String exceptionMessage = String.format( + "The OVS-DPDK port is expected to have a physical network of type ovsnet but was found to have %s instead.", + physicalNetworkType); + throw new HeatBridgeException(exceptionMessage); + } + } + + protected void processOVS(LInterface lInterface, String hostName, String interfaceName) { + Relationship lagRelationship = new Relationship(); + lagRelationship.setRelatedLink(AAIUriFactory + .createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().pserver(hostName).lagInterface(interfaceName)) + .build().toString()); + lInterface.getRelationshipList().getRelationship().add(lagRelationship); + } + /** * Needs to be corrected according to the specification that is in draft If pserver/p-interface does not have a * SRIOV-PF object matching the PCI-ID of the Openstack port object, then create it in AAI. Openstack SRIOV Port @@ -464,9 +597,11 @@ public class HeatBridgeImpl implements HeatBridgeApi { lIf.setInterfaceDescription( "Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get()); try { - Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class, AAIUriFactory - .createResourceUri(AAIObjectType.P_INTERFACE, pserverHostName, matchingPifName.get()) - .depth(Depth.ONE)); + Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class, + AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .pserver(pserverHostName).pInterface(matchingPifName.get())) + .depth(Depth.ONE)); if (matchingPIf.isPresent()) { SriovPfs pIfSriovPfs = matchingPIf.get().getSriovPfs(); if (pIfSriovPfs == null) { @@ -484,16 +619,18 @@ public class HeatBridgeImpl implements HeatBridgeApi { logger.debug("Queuing AAI command to update sriov-pf object to pserver: " + pserverHostName + "/" + matchingPifName.get()); - AAIResourceUri sriovPfUri = AAIUriFactory.createResourceUri(AAIObjectType.SRIOV_PF, - pserverHostName, matchingPifName.get(), sriovPf.getPfPciId()); + AAIResourceUri sriovPfUri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverHostName) + .pInterface(matchingPifName.get()).sriovPf(sriovPf.getPfPciId())); + if (!resourcesClient.exists(sriovPfUri)) { transaction.create(sriovPfUri, sriovPf); - AAIResourceUri sriovVfUri = AAIUriFactory.createResourceUri(AAIObjectType.SRIOV_VF, - cloudOwner, cloudRegionId, tenantId, port.getDeviceId(), lIf.getInterfaceName(), - port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString()); - + AAIResourceUri sriovVfUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId) + .vserver(port.getDeviceId()).lInterface(lIf.getInterfaceName()).sriovVf( + port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString())); transaction.connect(sriovPfUri, sriovVfUri); } } @@ -562,17 +699,16 @@ public class HeatBridgeImpl implements HeatBridgeApi { Objects.requireNonNull(vnfId, "Null vnf-id!"); Objects.requireNonNull(vfModuleId, "Null vf-module-id!"); try { - Optional<VfModule> vfModule = resourcesClient - .get(AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId).depth(Depth.ONE), - NotFoundException.class) - .asBean(VfModule.class); + Optional<VfModule> vfModule = resourcesClient.get(AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId).vfModule(vfModuleId)) + .depth(Depth.ONE), NotFoundException.class).asBean(VfModule.class); AAIResultWrapper resultWrapper = new AAIResultWrapper(vfModule.get()); Optional<Relationships> relationships = resultWrapper.getRelationships(); logger.debug("VfModule contains relationships in AAI: {}", relationships.isPresent()); if (relationships.isPresent()) { - List<AAIResourceUri> l3NetworkUris = relationships.get().getRelatedUris(AAIObjectType.L3_NETWORK); + List<AAIResourceUri> l3NetworkUris = relationships.get().getRelatedUris(Types.L3_NETWORK); logger.debug("L3Network contains {} relationships in AAI", l3NetworkUris.size()); if (!l3NetworkUris.isEmpty()) { @@ -585,13 +721,13 @@ public class HeatBridgeImpl implements HeatBridgeApi { } } - List<AAIResourceUri> vserverUris = relationships.get().getRelatedUris(AAIObjectType.VSERVER); + List<AAIResourceUri> vserverUris = relationships.get().getRelatedUris(Types.VSERVER); logger.debug("VServer contains {} relationships in AAI", vserverUris.size()); createTransactionToDeleteSriovPfFromPserver(vserverUris); if (!vserverUris.isEmpty()) { for (AAIResourceUri vserverUri : vserverUris) { - if (env.getProperty("heatBridgeDryrun", Boolean.class, true)) { + if (env.getProperty("heatBridgeDryrun", Boolean.class, false)) { logger.debug("Would delete Vserver: {}", vserverUri.build().toString()); } else { resourcesClient.delete(vserverUri); @@ -617,7 +753,8 @@ public class HeatBridgeImpl implements HeatBridgeApi { String pserverName = entry.getKey(); List<String> pciIds = entry.getValue(); Optional<Pserver> pserver = resourcesClient.get(Pserver.class, - AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, pserverName).depth(Depth.TWO)); + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverName)) + .depth(Depth.TWO)); if (pserver.isPresent()) { // For each pserver/p-interface match sriov-vfs by pic-id and delete them. pserver.get().getPInterfaces().getPInterface().stream().filter( @@ -626,15 +763,15 @@ public class HeatBridgeImpl implements HeatBridgeApi { if (pciIds.contains(sriovPf.getPfPciId())) { logger.debug("creating transaction to delete SR-IOV PF: " + pIf.getInterfaceName() + " from PServer: " + pserverName); - if (env.getProperty("heatBridgeDryrun", Boolean.class, true)) { + if (env.getProperty("heatBridgeDryrun", Boolean.class, false)) { logger.debug("Would delete Sriov Pf: {}", - AAIUriFactory - .createResourceUri(AAIObjectType.SRIOV_PF, pserverName, - pIf.getInterfaceName(), sriovPf.getPfPciId()) - .build().toString()); + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .pserver(pserverName).pInterface(pIf.getInterfaceName()) + .sriovPf(sriovPf.getPfPciId())).build()); } else { - resourcesClient.delete(AAIUriFactory.createResourceUri(AAIObjectType.SRIOV_PF, - pserverName, pIf.getInterfaceName(), sriovPf.getPfPciId())); + resourcesClient.delete(AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverName) + .pInterface(pIf.getInterfaceName()).sriovPf(sriovPf.getPfPciId()))); } } })); @@ -648,12 +785,11 @@ public class HeatBridgeImpl implements HeatBridgeApi { AAIResultWrapper vserverWrapper = resourcesClient.get(vserverUri.depth(Depth.TWO)); Optional<Relationships> vserverRelationships = vserverWrapper.getRelationships(); if (vserverRelationships.isPresent() - && CollectionUtils.isNotEmpty(vserverRelationships.get().getRelatedLinks(AAIObjectType.PSERVER))) { + && CollectionUtils.isNotEmpty(vserverRelationships.get().getRelatedLinks(Types.PSERVER))) { Vserver vserver = vserverWrapper.asBean(Vserver.class).get(); List<String> pciIds = HeatBridgeUtils.extractPciIdsFromVServer(vserver); if (CollectionUtils.isNotEmpty(pciIds)) { - List<AAIResourceUri> matchingPservers = - vserverRelationships.get().getRelatedUris(AAIObjectType.PSERVER); + List<AAIResourceUri> matchingPservers = vserverRelationships.get().getRelatedUris(Types.PSERVER); if (matchingPservers != null && matchingPservers.size() == 1) { pserverToPciIdMap.put(matchingPservers.get(0).getURIKeys().get("hostname"), pciIds); } @@ -667,4 +803,28 @@ public class HeatBridgeImpl implements HeatBridgeApi { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } + + protected Optional<String> findLinkedURI(String jsonResultsString) { + Results<Map<String, String>> results; + try { + results = mapper.readValue(jsonResultsString, new TypeReference<Results<Map<String, String>>>() {}); + if (results.getResult().size() == 1) { + return Optional.of(results.getResult().get(0).get(RESOURCE_LINK)); + } else if (results.getResult().isEmpty()) { + return Optional.empty(); + } else { + throw new IllegalStateException("more than one result returned"); + } + } catch (IOException e) { + logger.error("Error retrieving URI from Results JSON", e); + return Optional.empty(); + } + } + + protected AAIDSLQueryClient getAAIDSLClient() { + if (aaiDSLClient == null) { + aaiDSLClient = new AAIDSLQueryClient(); + } + return aaiDSLClient; + } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java index 7d4e92d9ad..c1a97cefc4 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java @@ -50,9 +50,9 @@ import org.onap.aai.domain.yang.RelationshipData; import org.onap.aai.domain.yang.RelationshipList; import org.onap.aai.domain.yang.SriovVf; import org.onap.aai.domain.yang.Vserver; -import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.so.heatbridge.constants.HeatBridgeConstants; import org.openstack4j.model.compute.Server; import org.openstack4j.model.network.Network; @@ -82,39 +82,39 @@ public class AaiHelper { // vserver to pserver relationship if (!StringUtils.isEmpty(server.getHypervisorHostname())) { - Relationship pserverRelationship = buildRelationship( - AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, server.getHypervisorHostname())); + Relationship pserverRelationship = buildRelationship(AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().pserver(server.getHypervisorHostname()))); relationships.add(pserverRelationship); } // vserver to generic-vnf relationship - Relationship genericVnfRelationship = - buildRelationship(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, genericVnfId)); + Relationship genericVnfRelationship = buildRelationship( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericVnfId))); relationships.add(genericVnfRelationship); // vserver to vnfc relationship if (!StringUtils.isEmpty(server.getName())) { - Relationship vnfcRelationship = - buildRelationship(AAIUriFactory.createResourceUri(AAIObjectType.VNFC, server.getName())); + Relationship vnfcRelationship = buildRelationship( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().vnfc(server.getName()))); relationships.add(vnfcRelationship); } // vserver to vf-module relationship - Relationship vfModuleRelationship = - buildRelationship(AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, genericVnfId, vfModuleId)); + Relationship vfModuleRelationship = buildRelationship(AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId))); relationships.add(vfModuleRelationship); // vserver to image relationship if (server.getImage() != null) { - Relationship imageRel = buildRelationship(AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, - cloudRegionId, server.getImage().getId())); + Relationship imageRel = buildRelationship(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).image(server.getImage().getId()))); relationships.add(imageRel); } // vserver to flavor relationship if (server.getFlavor() != null) { - Relationship flavorRel = buildRelationship(AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, - cloudRegionId, server.getFlavor().getId())); + Relationship flavorRel = buildRelationship(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).flavor(server.getFlavor().getId()))); relationships.add(flavorRel); } @@ -127,20 +127,21 @@ public class AaiHelper { List<Relationship> relationships = relationshipList.getRelationship(); // sriov-vf to sriov-pf relationship - Relationship sriovPfRelationship = buildRelationship( - AAIUriFactory.createResourceUri(AAIObjectType.SRIOV_PF, pserverName, pIfName, pfPciId)); + Relationship sriovPfRelationship = buildRelationship(AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverName).pInterface(pIfName).sriovPf(pfPciId))); relationships.add(sriovPfRelationship); return relationshipList; } public Relationship getRelationshipToVfModule(String vnfId, String vfModuleId) { - return buildRelationship(AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)); + return buildRelationship( + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId).vfModule(vfModuleId))); } public Relationship getRelationshipToTenant(String cloudOwner, String cloudRegionId, String tenantId) { - return buildRelationship( - AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegionId, tenantId)); + return buildRelationship(AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId))); } public org.onap.aai.domain.yang.Subnet buildSubnet(Subnet subnet) { @@ -252,6 +253,9 @@ public class AaiHelper { .filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)).findFirst() .ifPresent(link -> aaiImage.setImageSelflink(link.getHref())); } + if (aaiImage.getImageSelflink() == null || aaiImage.getImageSelflink().isEmpty()) { + aaiImage.setImageSelflink("NA"); + } return aaiImage; } diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java index 76bc8d2456..9d5a4c62b9 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java @@ -17,10 +17,10 @@ import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.CloudRegion; -import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.AAIResourcesClient; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.catalog.data.repository.NetworkTechnologyReferenceRepository; @@ -94,7 +94,8 @@ public class CloudRegionRestImplTest { public void createCloudRegionTest() { when(catalogDbClientMock.getCloudSite("region1")).thenReturn(null); when(catalogDbClientMock.postCloudSite(cloudSite)).thenReturn(cloudSite); - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "bob", "region1"); + AAIResourceUri uri = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion("bob", "region1")); cloudRestImpl.createCloudRegion(cloudSite); ArgumentCaptor<AAIResourceUri> actualURI = ArgumentCaptor.forClass(AAIResourceUri.class); ArgumentCaptor<Optional<Object>> actualCloudRegion = ArgumentCaptor.forClass(Optional.class); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java index e70b56dfc5..2e496c50cd 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java @@ -41,12 +41,12 @@ import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VfModules; import org.onap.aai.domain.yang.Vserver; -import org.onap.aaiclient.client.aai.AAIObjectPlurals; import org.onap.aaiclient.client.aai.AAIObjectType; import org.onap.aaiclient.client.aai.AAIResourcesClient; import org.onap.aaiclient.client.aai.entities.AAIResultWrapper; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; +import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; import org.skyscreamer.jsonassert.JSONAssert; @@ -70,35 +70,43 @@ public class AuditVServerTest extends AuditVServer { private String cloudRegion = "cloudRegion"; private String tenantId = "tenantId"; - private AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db"); + private AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db")); - private AAIResourceUri vserverURI2 = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz"); + private AAIResourceUri vserverURI2 = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz")); - private AAIResourceUri ssc_1_trusted_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_trusted_port_0"); + private AAIResourceUri ssc_1_trusted_port_0_uri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId) + .vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db").lInterface("ssc_1_trusted_port_0")); - private AAIResourceUri ssc_1_service1_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0"); + private AAIResourceUri ssc_1_service1_port_0_uri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId) + .vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db").lInterface("ssc_1_service1_port_0")); - private AAIResourceUri ssc_1_mgmt_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_1"); + private AAIResourceUri ssc_1_mgmt_port_1_uri = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion) + .tenant(tenantId).vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db").lInterface("ssc_1_mgmt_port_1")); - private AAIResourceUri ssc_1_mgmt_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_0"); + private AAIResourceUri ssc_1_mgmt_port_0_uri = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion) + .tenant(tenantId).vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db").lInterface("ssc_1_mgmt_port_0")); - private AAIResourceUri ssc_1_service2_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0"); + private AAIResourceUri ssc_1_service2_port_0_uri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId) + .vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db").lInterface("ssc_1_service2_port_0")); - private AAIResourceUri ssc_1_int_ha_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_int_ha_port_0"); + private AAIResourceUri ssc_1_int_ha_port_0_uri = AAIUriFactory.createResourceUri( + AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId) + .vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4db").lInterface("ssc_1_int_ha_port_0")); - private AAIResourceUri test_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_1"); + private AAIResourceUri test_port_1_uri = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion) + .tenant(tenantId).vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz").lInterface("test_port_1")); - private AAIResourceUri test_port_2_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_2"); + private AAIResourceUri test_port_2_uri = AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion) + .tenant(tenantId).vserver("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz").lInterface("test_port_2")); private AAIResourceUri service2_sub_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, @@ -368,17 +376,20 @@ public class AuditVServerTest extends AuditVServer { Vserver vserver = new Vserver(); vserver.setVserverId("testVserverId"); obj1.setAaiObject(vserver); - obj1.setResourceURI(AAIUriFactory - .createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenantId, "testVserverId").build()); + obj1.setResourceURI( + AAIUriFactory + .createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver("testVserverId")) + .build()); auditList.getAuditList().add(obj1); - doReturn(false).when(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegion, tenantId, "testVserverId")); + doReturn(false).when(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver("testVserverId"))); auditNova.auditVservers(auditList); - Mockito.verify(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegion, tenantId, "testVserverId")); + Mockito.verify(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder + .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegion).tenant(tenantId).vserver("testVserverId"))); Assert.assertEquals(false, auditList.getAuditList().get(0).isDoesObjectExist()); } @@ -392,8 +403,8 @@ public class AuditVServerTest extends AuditVServer { AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, - AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", - "vfModuleName")); + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf("genericVnfId").vfModules()) + .queryParam("vf-module-name", "vfModuleName")); Optional<AAIObjectAuditList> auditList = auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); @@ -410,11 +421,12 @@ public class AuditVServerTest extends AuditVServer { AAIResultWrapper vserverWrapper = new AAIResultWrapper(new Vserver()); doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, - AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", - "vfModuleName")); + AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf("genericVnfId").vfModules()) + .queryParam("vf-module-name", "vfModuleName")); - doReturn(vserverWrapper).when(aaiResourcesMock).get(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, - "cloud-owner", "cloud-region-id", "tenant-id", "VUSCHGA1")); + doReturn(vserverWrapper).when(aaiResourcesMock) + .get(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion("cloud-owner", "cloud-region-id").tenant("tenant-id").vserver("VUSCHGA1"))); Optional<AAIObjectAuditList> auditList = auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java index 18348f19d7..110faaf8ab 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java @@ -45,7 +45,6 @@ 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 static org.mockito.Mockito.doReturn; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -66,20 +65,19 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.L3InterfaceIpv6AddressList; import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.PInterface; import org.onap.aai.domain.yang.SriovPf; -import org.onap.aaiclient.client.aai.AAIObjectType; +import org.onap.aaiclient.client.aai.AAIDSLQueryClient; import org.onap.aaiclient.client.aai.AAIResourcesClient; import org.onap.aaiclient.client.aai.AAISingleTransactionClient; import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri; import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory; import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder; -import org.onap.aaiclient.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed; +import org.onap.so.cloud.resource.beans.NodeType; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.heatbridge.constants.HeatBridgeConstants; import org.onap.so.heatbridge.helpers.AaiHelper; @@ -103,10 +101,9 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; -import inet.ipaddr.IPAddressString; -@RunWith(MockitoJUnitRunner.class) +@RunWith(MockitoJUnitRunner.Silent.class) public class HeatBridgeImplTest { private static final String CLOUD_OWNER = "CloudOwner"; @@ -126,33 +123,24 @@ public class HeatBridgeImplTest { private AAISingleTransactionClient transaction; @Mock + private AAIDSLQueryClient mockDSLClient; + + @Mock private Environment env; + @Mock + private Server server; + @InjectMocks - private HeatBridgeImpl heatbridge = - new HeatBridgeImpl(resourcesClient, cloudIdentity, CLOUD_OWNER, REGION_ID, REGION_ID, TENANT_ID); + private HeatBridgeImpl heatbridge = new HeatBridgeImpl(resourcesClient, cloudIdentity, CLOUD_OWNER, REGION_ID, + REGION_ID, TENANT_ID, NodeType.GREENFIELD); @Before public void setUp() throws HeatBridgeException, OpenstackClientException, BulkProcessFailed { when(resourcesClient.beginSingleTransaction()).thenReturn(transaction); } - @Ignore - @Test - public void testQueryNestedHeatStackResources() throws HeatBridgeException { - // Arrange - String heatStackId = "1234567"; - List<Resource> expectedResourceList = (List<Resource>) extractTestStackResources(); - when(osClient.getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING)) - .thenReturn(expectedResourceList); - - // Act - List<Resource> resourceList = heatbridge.queryNestedHeatStackResources(heatStackId); - // Assert - verify(osClient).getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING); - assertEquals(resourceList, expectedResourceList); - } @Test public void testExtractStackResourceIdsByResourceType() throws HeatBridgeException { @@ -169,73 +157,6 @@ public class HeatBridgeImplTest { assertEquals(expectedServerIds, serverIds); } - @Ignore - @Test - public void testGetAllOpenstackServers() { - // Arrange - List<Resource> stackResources = (List<Resource>) extractTestStackResources(); - - Server server1 = mock(Server.class); - Server server2 = mock(Server.class); - List<Server> expectedServers = Arrays.asList(server1, server2); - - when(osClient.getServerById("43c2159b-2c04-46ac-bda5-594110cae2d3")).thenReturn(server1); - when(osClient.getServerById("7cff109a-b2b7-4933-97b4-ec44a8365568")).thenReturn(server2); - - // Act - List<Server> servers = heatbridge.getAllOpenstackServers(stackResources); - - // Assert - assertEquals(expectedServers, servers); - } - - @Ignore - @Test - public void testExtractOpenstackImagesFromServers() { - // Arrange - Server server1 = mock(Server.class); - Server server2 = mock(Server.class); - List<Server> servers = Arrays.asList(server1, server2); - - Image image1 = mock(Image.class); - Image image2 = mock(Image.class); - when(image1.getId()).thenReturn("1"); - when(image2.getId()).thenReturn("1"); - List<Image> expectedDistinctImages = Collections.singletonList(image1); - - when(server1.getImage()).thenReturn(image1); - when(server2.getImage()).thenReturn(image2); - - // Act - List<Image> images = heatbridge.extractOpenstackImagesFromServers(servers); - - // Assert - assertEquals(expectedDistinctImages, images); - } - - @Ignore - @Test - public void testExtractOpenstackFlavorsFromServers() { - // Arrange - Server server1 = mock(Server.class); - Server server2 = mock(Server.class); - List<Server> servers = Arrays.asList(server1, server2); - - Flavor flavor1 = mock(Flavor.class); - Flavor flavor2 = mock(Flavor.class); - when(flavor1.getId()).thenReturn("1"); - when(flavor2.getId()).thenReturn("2"); - List<Flavor> expectedFlavors = Arrays.asList(flavor1, flavor2); - - when(server1.getFlavor()).thenReturn(flavor1); - when(server2.getFlavor()).thenReturn(flavor2); - - // Act - List<Flavor> flavors = heatbridge.extractOpenstackFlavorsFromServers(servers); - - // Assert - assertEquals(expectedFlavors, flavors); - } @Test public void testUpdateVserversToAai() throws HeatBridgeException { @@ -276,10 +197,10 @@ public class HeatBridgeImplTest { verify(transaction, times(2)).createIfNotExists(captor.capture(), any(Optional.class)); List<AAIResourceUri> uris = captor.getAllValues(); - assertEquals(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, - server1.getId()), uris.get(0)); - assertEquals(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, - server2.getId()), uris.get(1)); + assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server1.getId())), uris.get(0)); + assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server2.getId())), uris.get(1)); } @@ -320,10 +241,10 @@ public class HeatBridgeImplTest { verify(transaction, times(2)).createIfNotExists(captor.capture(), any(Optional.class)); List<AAIResourceUri> uris = captor.getAllValues(); - assertEquals(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, - server1.getId()), uris.get(0)); - assertEquals(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, - server2.getId()), uris.get(1)); + assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server1.getId())), uris.get(0)); + assertEquals(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure() + .cloudRegion(CLOUD_OWNER, REGION_ID).tenant(TENANT_ID).vserver(server2.getId())), uris.get(1)); } @Test @@ -428,6 +349,9 @@ public class HeatBridgeImplTest { when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78"); when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a"); when(port.getDeviceId()).thenReturn("test-device-id"); + + when(osClient.getServerById("test-device-id")).thenReturn(server); + when(server.getHypervisorHostname()).thenReturn("test.server.name"); String pfPciId = "0000:08:00.0"; when(port.getProfile()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_PCI_SLOT_KEY, pfPciId, HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY, "physical_network_id")); @@ -448,6 +372,7 @@ public class HeatBridgeImplTest { when(network.getId()).thenReturn("test-network-id"); when(network.getNetworkType()).thenReturn(NetworkType.VLAN); when(network.getProviderSegID()).thenReturn("2345"); + when(network.getProviderPhyNet()).thenReturn("ovsnet"); when(osClient.getPortById("212a203a-9764-4f42-84ea-731536a8f13a")).thenReturn(port); when(osClient.getPortById("387e3904-8948-43d1-8635-b6c2042b54da")).thenReturn(port); |