diff options
Diffstat (limited to 'adapters')
83 files changed, 3526 insertions, 280 deletions
diff --git a/adapters/mso-adapter-utils/pom.xml b/adapters/mso-adapter-utils/pom.xml index aa9a1cea9e..b8dec73f80 100644 --- a/adapters/mso-adapter-utils/pom.xml +++ b/adapters/mso-adapter-utils/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-adapter-utils</artifactId> diff --git a/adapters/mso-adapters-rest-interface/pom.xml b/adapters/mso-adapters-rest-interface/pom.xml index 5f987e61ce..584c47fea6 100644 --- a/adapters/mso-adapters-rest-interface/pom.xml +++ b/adapters/mso-adapters-rest-interface/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-adapters-rest-interface</artifactId> diff --git a/adapters/mso-catalog-db-adapter/pom.xml b/adapters/mso-catalog-db-adapter/pom.xml index 9745935925..bcc523ab98 100644 --- a/adapters/mso-catalog-db-adapter/pom.xml +++ b/adapters/mso-catalog-db-adapter/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.4__AddBBNameSelectionReference.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.4__AddBBNameSelectionReference.sql new file mode 100644 index 0000000000..2b8d4ea69f --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.4__AddBBNameSelectionReference.sql @@ -0,0 +1,16 @@ +use catalogdb; + +CREATE TABLE IF NOT EXISTS `bbname_selection_reference` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `CONTROLLER_ACTOR` varchar(200) NOT NULL , + `SCOPE` varchar(200) NOT NULL, + `ACTION` varchar(200) NOT NULL, + `BB_NAME` varchar(200) NOT NULL, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +INSERT INTO bbname_selection_reference (CONTROLLER_ACTOR,SCOPE,ACTION,BB_NAME) +VALUES +('APPC', 'vfModule', 'healthCheck','GenericVnfHealthCheckBB'), +('APPC', 'vfModule', 'configScaleOut','ConfigurationScaleOutBB'), +('APPC', 'vnf', 'healthCheck','GenericVnfHealthCheckBB');
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java index 707a2a45af..03ef24ded0 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -22,8 +22,8 @@ package org.onap.so.db.catalog.client; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -33,6 +33,7 @@ import org.junit.Before; import org.junit.Test; import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest; import org.onap.so.db.catalog.beans.AuthenticationType; +import org.onap.so.db.catalog.beans.BBNameSelectionReference; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.CloudifyManager; @@ -428,7 +429,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { } @Test - public void testPostCloudSite() { + public void testCloudSiteClient() { CatalogDbClientPortChanger localClient = new CatalogDbClientPortChanger( "http://localhost:" + client.wiremockPort, msoAdaptersAuth, client.wiremockPort); CloudSite cloudSite = new CloudSite(); @@ -455,6 +456,19 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { assertEquals("TESTCLLI", getCloudSite.getClli()); assertEquals("regionId", getCloudSite.getRegionId()); assertEquals("RANDOMID", getCloudSite.getIdentityServiceId()); + + getCloudSite.setClli("clli2"); + getCloudSite.setRegionId("region2"); + + CloudSite updatedCloudSite = this.client.updateCloudSite(getCloudSite); + assertNotNull(updatedCloudSite); + assertNotNull(updatedCloudSite.getIdentityService()); + assertEquals("clli2", updatedCloudSite.getClli()); + assertEquals("region2", updatedCloudSite.getRegionId()); + + this.client.deleteCloudSite(getCloudSite.getId()); + getCloudSite = this.client.getCloudSite("MTN6"); + assertNull(getCloudSite); } @Test @@ -705,8 +719,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { } @Test - public void getWorkflowByModelUUID_validUuid_expectedOutput() { - List<Workflow> workflows = client.findWorkflowByModelUUID("ff2ae348-214a-11e7-93ae-92361f002671"); + public void getWorkflowByVnfModelUUID_validUuid_expectedOutput() { + List<Workflow> workflows = client.findWorkflowByVnfModelUUID("ff2ae348-214a-11e7-93ae-92361f002671"); assertTrue(workflows != null); assertTrue(workflows.size() != 0); @@ -741,5 +755,21 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { assertNotEquals(0, cloudSites.size()); } + @Test + public void getBBNameSelectionReference_validData_expectedOutput() { + BBNameSelectionReference bbNameSelectionReference = + client.getBBNameSelectionReference("APPC", "vfModule", "healthCheck"); + assertNotNull(bbNameSelectionReference); + assertEquals("GenericVnfHealthCheckBB", bbNameSelectionReference.getBbName()); + } + + @Test + public void getBBNameSelectionReference_invalidData_nullOutput() { + BBNameSelectionReference bbNameSelectionReference = + client.getBBNameSelectionReference("ABC", "vfModule", "healthCheck"); + assertNull(bbNameSelectionReference); + + } + } diff --git a/adapters/mso-nssmf-adapter/pom.xml b/adapters/mso-nssmf-adapter/pom.xml new file mode 100644 index 0000000000..b6b52ce7c5 --- /dev/null +++ b/adapters/mso-nssmf-adapter/pom.xml @@ -0,0 +1,149 @@ +<!-- + ~* + ~============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========================================================= + ~*/ + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.so</groupId> + <artifactId>adapters</artifactId> + <version>1.6.0-SNAPSHOT</version> + </parent> + <artifactId>mso-nssmf-adapter</artifactId> + <packaging>jar</packaging> + <name>mso-nssmf-adapter</name> + <description>Web service endpoint for nssmf operations</description> + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-dependencies</artifactId> + <version>${springboot.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> + <build> + <finalName>${project.artifactId}-${project.version}</finalName> + <plugins> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <configuration> + <mainClass>org.onap.so.adapters.nssmf.MSONssmfApplication</mainClass> + </configuration> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.jacoco</groupId> + <artifactId>jacoco-maven-plugin</artifactId> + </plugin> + </plugins> + </build> + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-actuator</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-jdbc</artifactId> + <exclusions> + <exclusion> + <groupId>org.apache.tomcat</groupId> + <artifactId>tomcat-jdbc</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-spring-boot-starter-jaxws</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-spring-boot-starter-jaxrs</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>org.apache.cxf</groupId> + <artifactId>cxf-rt-rs-service-description-swagger</artifactId> + <version>${cxf.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-data-jpa</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>mso-requests-db</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>mso-requests-db-repositories</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + </dependency> + <dependency> + <groupId>ch.vorburger.mariaDB4j</groupId> + <artifactId>mariaDB4j</artifactId> + <version>2.2.3</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-configuration-processor</artifactId> + <optional>true</optional> + </dependency> + <dependency> + <groupId>com.squareup.okhttp3</groupId> + <artifactId>okhttp</artifactId> + <version>3.14.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>1.18.2</version> + </dependency> + </dependencies> +</project> diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java new file mode 100644 index 0000000000..cd011e6437 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/MSONssmfApplication.java @@ -0,0 +1,32 @@ +/*- + * ============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.nssmf; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = {"org.onap.so"}) +public class MSONssmfApplication { + + public static void main(String... args) { + SpringApplication.run(MSONssmfApplication.class, args); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/RequestDbConfig.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/RequestDbConfig.java new file mode 100644 index 0000000000..484f7624aa --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/RequestDbConfig.java @@ -0,0 +1,68 @@ +/*- + * ============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.nssmf; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Profile({"!test"}) +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory", + transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"}) +public class RequestDbConfig { + + @Primary + @Bean(name = "requestDataSource") + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource dataSource() { + return DataSourceBuilder.create().build(); + } + + @Primary + @Bean(name = "requestEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("requestDataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB") + .build(); + } + + @Primary + @Bean(name = "requestTransactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/WebSecurityConfig.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/WebSecurityConfig.java new file mode 100644 index 0000000000..1522ca9c6d --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/WebSecurityConfig.java @@ -0,0 +1,37 @@ +/*- + * ============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.nssmf; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable(); + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiClientPropertiesImpl.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiClientPropertiesImpl.java new file mode 100644 index 0000000000..3333c64cd8 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiClientPropertiesImpl.java @@ -0,0 +1,69 @@ +/*- + * ============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.nssmf.extclients.aai; + +import java.net.MalformedURLException; +import java.net.URL; +import org.onap.so.client.aai.AAIProperties; +import org.onap.so.client.aai.AAIVersion; +import org.onap.so.spring.SpringContextHelper; +import org.springframework.context.ApplicationContext; + +public class AaiClientPropertiesImpl implements AAIProperties { + + private final String endpoint; + + private final String encryptedBasicAuth; + + private final String encrytptionKey; + + public AaiClientPropertiesImpl() { + final ApplicationContext context = SpringContextHelper.getAppContext(); + this.endpoint = context.getEnvironment().getProperty("aai.endpoint"); + this.encryptedBasicAuth = context.getEnvironment().getProperty("aai.auth"); + this.encrytptionKey = context.getEnvironment().getProperty("mso.key"); + } + + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } + + @Override + public String getAuth() { + return encryptedBasicAuth; + } + + @Override + public String getKey() { + return encrytptionKey; + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(endpoint); + } + + @Override + public String getSystemName() { + return "MSO"; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiClientProvider.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiClientProvider.java new file mode 100644 index 0000000000..48e3ef1666 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiClientProvider.java @@ -0,0 +1,34 @@ +/*- + * ============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.nssmf.extclients.aai; + +import org.onap.so.client.aai.AAIResourcesClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class AaiClientProvider { + + @Bean + public AAIResourcesClient getAaiClient() { + return new AAIResourcesClient(); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java new file mode 100644 index 0000000000..c737ba6440 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProvider.java @@ -0,0 +1,32 @@ +/*- + * ============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.nssmf.extclients.aai; + +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrThirdpartySdncList; + +public interface AaiServiceProvider { + + EsrThirdpartySdncList invokeGetThirdPartySdncList(); + + EsrSystemInfoList invokeGetThirdPartySdncEsrSystemInfo(String sdncId); + +} 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 new file mode 100644 index 0000000000..f8422e2a8f --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/extclients/aai/AaiServiceProviderImpl.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.nssmf.extclients.aai; + + +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrThirdpartySdncList; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class AaiServiceProviderImpl implements AaiServiceProvider { + + private static final Logger logger = LoggerFactory.getLogger(AaiServiceProviderImpl.class); + + private final AaiClientProvider aaiClientProvider; + + @Autowired + public AaiServiceProviderImpl(final AaiClientProvider aaiClientProvider) { + this.aaiClientProvider = aaiClientProvider; + } + + @Override + public EsrThirdpartySdncList invokeGetThirdPartySdncList() { + return aaiClientProvider.getAaiClient() + .get(EsrThirdpartySdncList.class, AAIUriFactory.createResourceUri(AAIObjectType.THIRDPARTY_SDNC_LIST)) + .orElseGet(() -> { + logger.debug("No VNFMs in AAI"); + return null; + }); + } + + @Override + public EsrSystemInfoList invokeGetThirdPartySdncEsrSystemInfo(String sdncId) { + return aaiClientProvider.getAaiClient() + .get(EsrSystemInfoList.class, + AAIUriFactory.createResourceUri(AAIObjectType.THIRDPARTY_SDNC_SYSTEM_INFO_LIST, sdncId)) + .orElseGet(() -> { + logger.debug("VNFM not found in AAI"); + return null; + }); + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/ErrorResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/ErrorResponse.java new file mode 100644 index 0000000000..188349c0bf --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/ErrorResponse.java @@ -0,0 +1,63 @@ +/*- + * ============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.nssmf.model; + +public class ErrorResponse { + + private int status; + + private String error; + + private String message; + + public ErrorResponse(int status, String message) { + this.status = status; + this.message = message; + this.error = "Bad Request"; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getError() { + if (status == 500) { + this.error = "Internal Server Error"; + } + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenRequest.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenRequest.java new file mode 100644 index 0000000000..3590c683e6 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenRequest.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.nssmf.model; + +public class TokenRequest { + + private String grantType; + + private String userName; + + private String value; + + public String getGrantType() { + return grantType; + } + + public void setGrantType(String grantType) { + this.grantType = grantType; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenResponse.java new file mode 100644 index 0000000000..8007075e04 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/model/TokenResponse.java @@ -0,0 +1,44 @@ +/*- + * ============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.nssmf.model; + +public class TokenResponse { + + private String accessToken; + + private int expires; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public int getExpires() { + return expires; + } + + public void setExpires(int expires) { + this.expires = expires; + } +} diff --git a/adapters/mso-openstack-adapters/pom.xml b/adapters/mso-openstack-adapters/pom.xml index f0c066aa05..a668b42106 100644 --- a/adapters/mso-openstack-adapters/pom.xml +++ b/adapters/mso-openstack-adapters/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-openstack-adapters</artifactId> <packaging>jar</packaging> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudException.java new file mode 100644 index 0000000000..9cdf7e3b2a --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudException.java @@ -0,0 +1,14 @@ +package org.onap.so.adapters.cloudregion; + +public class CloudException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -2631715095942372451L; + + public CloudException(String error, Exception e) { + super(error, e); + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java new file mode 100644 index 0000000000..780480507b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.cloudregion; + + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.http.HttpStatus; +import org.onap.so.db.catalog.beans.CloudSite; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; + + +@Path("/v1/cloud-region") +@Api(value = "/v1/cloud-region", description = "root of cloud region adapter") +@Component +public class CloudRegionRestV1 { + private static Logger logger = LoggerFactory.getLogger(CloudRegionRestV1.class); + + @Autowired + private CloudRestImpl cloudRestImpl; + + @POST + @Path("{cloud-region-id}/{cloud-owner}") + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateCloudRegion", response = Response.class, + notes = "Create a cloud site in MSO and Region In AAI") + @ApiResponses({@ApiResponse(code = 201, message = "Cloud Region has been created"), + @ApiResponse(code = 500, message = "Create Cloud Region has failed")}) + public Response createCloudRegion( + @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, + @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner, + @ApiParam(value = "CloudSite", required = true) final CloudSite cloudSite) { + cloudRestImpl.createCloudRegion(cloudSite, cloudOwner); + return Response.status(HttpStatus.SC_CREATED).build(); + } + + @DELETE + @Path("{cloud-region-id}/{cloud-owner}") + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateCloudRegion", response = Response.class, notes = "Delete an cloud Region in SO") + @ApiResponses({@ApiResponse(code = 204, message = "cloud Region has been deleted"), + @ApiResponse(code = 500, message = "Cloud Region delete has failed")}) + public Response deleteCloudRegion( + @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, + @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner) { + cloudRestImpl.deleteCloudRegion(cloudRegionId); + return Response.status(HttpStatus.SC_NO_CONTENT).build(); + } + + @PUT + @Path("{cloud-region-id}/{cloud-owner}") + @Consumes({MediaType.APPLICATION_JSON}) + @Produces({MediaType.APPLICATION_JSON}) + @ApiOperation(value = "CreateCloudRegion", response = Response.class, notes = "Update an existing Cloud Region") + @ApiResponses({@ApiResponse(code = 200, message = "Cloud Region has been updated"), + @ApiResponse(code = 500, message = "Update Cloud Region has failed examine entity object for details")}) + public Response updateCloudRegion( + @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, + @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner, + @ApiParam(value = "CloudSite", required = true) final CloudSite cloudSite) { + cloudRestImpl.updateCloudRegion(cloudSite, cloudOwner); + return Response.status(HttpStatus.SC_OK).build(); + } +} 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 new file mode 100644 index 0000000000..4cde8655ae --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java @@ -0,0 +1,97 @@ +package org.onap.so.adapters.cloudregion; + +import java.util.Optional; +import org.onap.aai.domain.yang.CloudRegion; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.db.catalog.beans.CloudSite; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + + +@Component +public class CloudRestImpl { + private static final Logger logger = LoggerFactory.getLogger(CloudRestImpl.class); + + private AAIResourcesClient aaiClient; + + @Autowired + private CatalogDbClient catalogDBClient; + + public void createCloudRegion(CloudSite cloudSite, String cloudOwner) throws CloudException { + createRegionInCatalogDb(cloudSite); + createCloudRegionInAAI(cloudSite, cloudOwner); + } + + public void updateCloudRegion(CloudSite cloudSite, String cloudOwner) throws CloudException { + updateRegionInCatalogDb(cloudSite); + } + + protected void updateRegionInCatalogDb(CloudSite cloudSite) { + try { + catalogDBClient.updateCloudSite(cloudSite); + } catch (Exception e) { + logger.error("Error updating cloud region in catalogdb", e); + throw new CloudException("Error updating cloud region in Catalog: " + e.getMessage(), e); + } + } + + public void deleteCloudRegion(String cloudRegionId) throws CloudException { + try { + catalogDBClient.deleteCloudSite(cloudRegionId); + } catch (Exception e) { + logger.error("Error deleting cloud region in catalogdb", e); + throw new CloudException("Error deleting cloud region in Catalog: " + e.getMessage(), e); + } + } + + protected void createCloudRegionInAAI(CloudSite cloudSite, String cloudOwner) { + try { + CloudRegion cloudRegion = mapCloudRegion(cloudSite, cloudOwner); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, + cloudRegion.getCloudOwner(), cloudRegion.getCloudRegionId()); + getAaiClient().createIfNotExists(uri, Optional.of(cloudRegion)); + } catch (Exception e) { + logger.error("Error creating cloud region in AAI", e); + throw new CloudException("Error creating cloud region in AAI: " + e.getMessage(), e); + } + } + + protected void createRegionInCatalogDb(CloudSite cloudSite) throws CloudException { + try { + CloudSite existingCloudSite = catalogDBClient.getCloudSite(cloudSite.getRegionId()); + if (existingCloudSite == null) { + catalogDBClient.postCloudSite(cloudSite); + } + } catch (Exception e) { + logger.error("Error creating cloud site in Catalog Adapter: " + e.getMessage(), e); + throw new CloudException("Error creating cloud site in Catalog Adapter", e); + } + } + + protected CloudRegion mapCloudRegion(CloudSite cloudSite, String cloudOwner) { + CloudRegion region = new CloudRegion(); + region.setCloudOwner(cloudOwner); + region.setCloudRegionId(cloudSite.getRegionId()); + region.setCloudRegionVersion(cloudSite.getCloudVersion()); + region.setOwnerDefinedType("cLCP"); + region.setOrchestrationDisabled(false); + region.setComplexName("NA"); + region.setInMaint(false); + region.setCloudType("openstack"); + return region; + } + + protected AAIResourcesClient getAaiClient() { + if (aaiClient == null) + return new AAIResourcesClient(); + else + return aaiClient; + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java index 9fc5c979d8..9badd795eb 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/CXFConfiguration.java @@ -32,6 +32,7 @@ import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; import org.apache.cxf.jaxws.EndpointImpl; import org.apache.cxf.transport.servlet.CXFServlet; +import org.onap.so.adapters.cloudregion.CloudRegionRestV1; import org.onap.so.adapters.network.MsoNetworkAdapterAsyncImpl; import org.onap.so.adapters.network.MsoNetworkAdapterImpl; import org.onap.so.adapters.network.NetworkAdapterRest; @@ -47,10 +48,12 @@ import org.onap.so.adapters.vnf.VolumeAdapterRestV2; import org.onap.so.client.policy.JettisonStyleMapperProvider; import org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor; import org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor; +import org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; @@ -81,7 +84,14 @@ public class CXFConfiguration { @Autowired private MsoVnfCloudifyAdapterImpl vnfCloudifyAdapterImpl; @Autowired + private CloudRegionRestV1 cloudRegionRestV1; + @Autowired private JettisonStyleMapperProvider jettisonStyleObjectMapper; + @Autowired + private ObjectMapper mapper; + @Autowired + private SOAuditLogContainerFilter soAuditLogContainerFilter; + @Bean(name = Bus.DEFAULT_BUS_ID) public SpringBus springBus() { @@ -170,6 +180,7 @@ public class CXFConfiguration { return endpoint; } + // Uses Jettson Style marshalling semantics @Bean public Server rsServer() { JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean(); @@ -178,7 +189,20 @@ public class CXFConfiguration { vnfAdapterRestV2, volumeAdapterRest, volumeAdapterRestV2)); endpoint.setAddress("/rest"); endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature())); - endpoint.setProvider(new JacksonJsonProvider(jettisonStyleObjectMapper.getMapper())); + endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(jettisonStyleObjectMapper.getMapper()), + soAuditLogContainerFilter)); + return endpoint.create(); + } + + // Uses normal Jackson marshalling semantics + @Bean + public Server rsServerApi() { + JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean(); + endpoint.setBus(springBus()); + endpoint.setServiceBeans(Arrays.<Object>asList(cloudRegionRestV1)); + endpoint.setAddress("/api"); + endpoint.setFeatures(Arrays.asList(new LoggingFeature())); + endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), soAuditLogContainerFilter)); return endpoint.create(); } 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 new file mode 100644 index 0000000000..9c62c286ac --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java @@ -0,0 +1,96 @@ +package org.onap.so.adapters.cloudregion; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.util.Optional; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.CloudRegion; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.db.catalog.beans.CloudSite; +import org.onap.so.db.catalog.client.CatalogDbClient; + + +@RunWith(MockitoJUnitRunner.class) +public class CloudRegionRestImplTest { + + @Spy + @InjectMocks + private CloudRestImpl cloudRestImpl; + + @Mock + private CatalogDbClient catalogDbClientMock; + + @Mock + private AAIResourcesClient aaiResClientMock; + + private CloudSite cloudSite = new CloudSite(); + + private CloudRegion testCloudRegion = new CloudRegion(); + + @Before + public void setup() { + cloudSite.setCloudVersion("1.0"); + cloudSite.setRegionId("region1"); + Mockito.doReturn(aaiResClientMock).when(cloudRestImpl).getAaiClient(); + testCloudRegion.setCloudOwner("bob"); + testCloudRegion.setCloudRegionId("region1"); + testCloudRegion.setCloudRegionVersion("1.0"); + testCloudRegion.setInMaint(false); + testCloudRegion.setOrchestrationDisabled(false); + testCloudRegion.setComplexName("NA"); + testCloudRegion.setCloudRegionVersion("1.0"); + testCloudRegion.setOwnerDefinedType("cLCP"); + testCloudRegion.setCloudType("openstack"); + } + + @Test + public void mapCloudRegionTest() { + CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite, "bob"); + assertThat(mappedRegion, sameBeanAs(testCloudRegion)); + } + + @Test + public void createCloudRegionTest() { + when(catalogDbClientMock.getCloudSite("region1")).thenReturn(null); + when(catalogDbClientMock.postCloudSite(cloudSite)).thenReturn(cloudSite); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "bob", "region1"); + cloudRestImpl.createCloudRegion(cloudSite, "bob"); + ArgumentCaptor<AAIResourceUri> actualURI = ArgumentCaptor.forClass(AAIResourceUri.class); + ArgumentCaptor<Optional<Object>> actualCloudRegion = ArgumentCaptor.forClass(Optional.class); + verify(catalogDbClientMock, times(1)).getCloudSite("region1"); + verify(catalogDbClientMock, times(1)).postCloudSite(cloudSite); + verify(aaiResClientMock, times(1)).createIfNotExists(Mockito.eq(uri), Mockito.any()); + verify(aaiResClientMock, times(1)).createIfNotExists(actualURI.capture(), actualCloudRegion.capture()); + assertThat((CloudRegion) actualCloudRegion.getValue().get(), sameBeanAs(testCloudRegion)); + } + + @Test + public void updateCloudRegionTest() { + when(catalogDbClientMock.updateCloudSite(cloudSite)).thenReturn(cloudSite); + cloudRestImpl.updateCloudRegion(cloudSite, "bob"); + verify(catalogDbClientMock, times(1)).updateCloudSite(cloudSite); + } + + @Test + public void deleteCloudRegionTest() { + doNothing().when(catalogDbClientMock).deleteCloudSite("region1"); + cloudRestImpl.deleteCloudRegion(cloudSite.getRegionId()); + verify(catalogDbClientMock, times(1)).deleteCloudSite("region1"); + } + +} diff --git a/adapters/mso-requests-db-adapter/pom.xml b/adapters/mso-requests-db-adapter/pom.xml index 366a207d60..2354272756 100644 --- a/adapters/mso-requests-db-adapter/pom.xml +++ b/adapters/mso-requests-db-adapter/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java index 3deabb3ce1..24dab2fc5b 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/ArchiveInfraRequestsScheduler.java @@ -145,6 +145,8 @@ public class ArchiveInfraRequestsScheduler { archivedInfra.setVnfType(iar.getVnfType()); archivedInfra.setVolumeGroupId(iar.getVolumeGroupId()); archivedInfra.setVolumeGroupName(iar.getVolumeGroupName()); + archivedInfra.setProductFamilyName(iar.getProductFamilyName()); + archivedInfra.setTenantName(iar.getTenantName()); newArchivedReqs.add(archivedInfra); oldInfraReqs.add(iar); diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/OrchestrationTaskRepositoryCustomController.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/OrchestrationTaskRepositoryCustomController.java new file mode 100644 index 0000000000..e32d90b137 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/OrchestrationTaskRepositoryCustomController.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.requestsdb; + +import org.onap.so.adapters.requestsdb.exceptions.MsoRequestsDbException; +import org.onap.so.db.request.beans.OrchestrationTask; +import org.onap.so.db.request.data.repository.OrchestrationTaskRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import java.util.List; + +@RestController +public class OrchestrationTaskRepositoryCustomController { + + @Autowired + private OrchestrationTaskRepository orchestrationTaskRepository; + + @RequestMapping(method = RequestMethod.GET, value = "/orchestrationTask") + public List<OrchestrationTask> getAllOrchestrationTask() { + return orchestrationTaskRepository.findAll(); + } + + @RequestMapping(method = RequestMethod.GET, value = "/orchestrationTask/{taskId}") + public OrchestrationTask getOrchestrationTask(@PathVariable("taskId") String taskId) throws MsoRequestsDbException { + return orchestrationTaskRepository.findById(taskId) + .orElseThrow(() -> new MsoRequestsDbException("orchestration task not found: " + taskId)); + } + + @RequestMapping(method = RequestMethod.POST, value = "/orchestrationTask/") + public OrchestrationTask createOrchestrationTask(@RequestBody OrchestrationTask orchestrationTask) { + return orchestrationTaskRepository.save(orchestrationTask); + } + + @RequestMapping(method = RequestMethod.PUT, value = "/orchestrationTask/{taskId}") + public OrchestrationTask updateOrchestrationTask(@PathVariable("taskId") String taskId, + @RequestBody OrchestrationTask orchestrationTask) throws MsoRequestsDbException { + return orchestrationTaskRepository.save(orchestrationTask); + } + + @RequestMapping(method = RequestMethod.DELETE, value = "/orchestrationTask/{taskId}") + public void deleteOrchestrationTask(@PathVariable("taskId") String taskId) { + orchestrationTaskRepository.deleteById(taskId); + } +} diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2.1__Add_PNF_Column_Infra_Requests_archive_tables.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2.1__Add_PNF_Column_Infra_Requests_archive_tables.sql new file mode 100644 index 0000000000..8c042dcbaf --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2.1__Add_PNF_Column_Infra_Requests_archive_tables.sql @@ -0,0 +1,4 @@ +use requestdb; + +ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS PNF_NAME varchar(45); +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_NAME varchar(45); diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql index dbdc925dae..d82e666855 100644 --- a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__Add_PNF_Column_Infra_Requests_archive_tables.sql @@ -1,4 +1,4 @@ use requestdb; ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS PNF_ID varchar(45); -ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_ID varchar(45);
\ No newline at end of file +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_ID varchar(45); diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.3__Add_Columns_Tenant_Name_Product_Family_Name.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.3__Add_Columns_Tenant_Name_Product_Family_Name.sql new file mode 100644 index 0000000000..a79b1a86c1 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.3__Add_Columns_Tenant_Name_Product_Family_Name.sql @@ -0,0 +1,7 @@ +use requestdb; + +ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS TENANT_NAME varchar(200); +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS TENANT_NAME varchar(200); + +ALTER TABLE infra_active_requests ADD COLUMN IF NOT EXISTS PRODUCT_FAMILY_NAME varchar(200); +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PRODUCT_FAMILY_NAME varchar(200);
\ No newline at end of file diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.1__Add_Orchestration_Task_Table.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.1__Add_Orchestration_Task_Table.sql new file mode 100644 index 0000000000..0d7cb7a62b --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.1__Add_Orchestration_Task_Table.sql @@ -0,0 +1,12 @@ +USE `requestdb`; + +CREATE TABLE `orchestration_task` ( + `TASK_ID` varchar(200) NOT NULL, + `REQUEST_ID` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `CREATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `STATUS` varchar(200) NOT NULL, + `IS_MANUAL` varchar(20) NOT NULL, + `PARAMS` varchar(20000) DEFAULT NULL, + PRIMARY KEY (`TASK_ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; diff --git a/adapters/mso-sdnc-adapter/pom.xml b/adapters/mso-sdnc-adapter/pom.xml index 07c8ed5eab..7fd1aa62d4 100644 --- a/adapters/mso-sdnc-adapter/pom.xml +++ b/adapters/mso-sdnc-adapter/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-sdnc-adapter</artifactId> <properties> diff --git a/adapters/mso-ve-vnfm-adapter/pom.xml b/adapters/mso-ve-vnfm-adapter/pom.xml index 3518445b45..3d054d9eca 100644 --- a/adapters/mso-ve-vnfm-adapter/pom.xml +++ b/adapters/mso-ve-vnfm-adapter/pom.xml @@ -8,7 +8,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> @@ -30,6 +30,10 @@ <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> + <groupId>org.springframework.retry</groupId> + <artifactId>spring-retry</artifactId> + </dependency> + <dependency> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vnfm-adapter-ext-clients</artifactId> <version>${project.version}</version> @@ -52,6 +56,10 @@ <artifactId>jersey-hk2</artifactId> </dependency> <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + </dependency> + <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> @@ -59,10 +67,21 @@ </dependencies> <build> + <finalName>${project.artifactId}-${project.version}</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> + <configuration> + <mainClass>org.onap.so.adapters.vevnfm.Application</mainClass> + </configuration> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> </plugin> </plugins> </build> diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java index 188b6718f2..a2bd603ae6 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/AaiConnection.java @@ -22,11 +22,14 @@ package org.onap.so.adapters.vevnfm.aai; import java.util.List; import java.util.Optional; +import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.aai.domain.yang.EsrVnfmList; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.graphinventory.entities.uri.Depth; import org.slf4j.Logger; @@ -40,10 +43,30 @@ public class AaiConnection { private static final int FIRST_INDEX = 0; - public EsrSystemInfo receiveVnfm() { + private static void isValid(final EsrSystemInfo info) throws VeVnfmException { + if (info == null || Strings.isBlank(info.getServiceUrl())) { + throw new VeVnfmException("No 'url' field in VNFM info"); + } + } + + public EsrSystemInfo receiveVnfm() throws VeVnfmException { + EsrSystemInfo info; + + try { + info = receiveVnfmInternal(); + } catch (Exception e) { + throw new VeVnfmException(e); + } + + isValid(info); + + return info; + } + + private EsrSystemInfo receiveVnfmInternal() { final AAIResourcesClient resourcesClient = new AAIResourcesClient(); - final Optional<EsrVnfmList> response = - resourcesClient.get(EsrVnfmList.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST)); + final AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.VNFM_LIST); + final Optional<EsrVnfmList> response = resourcesClient.get(EsrVnfmList.class, resourceUri); if (response.isPresent()) { final EsrVnfmList esrVnfmList = response.get(); diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java index f7b7283c59..ae330f7ed6 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/configuration/StartupConfiguration.java @@ -20,7 +20,9 @@ package org.onap.so.adapters.vevnfm.configuration; +import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.service.StartupService; +import org.onap.so.adapters.vevnfm.service.SubscriptionScheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.annotation.Configuration; @@ -39,10 +41,14 @@ public class StartupConfiguration { @Autowired private StartupService startupService; + @Autowired + private SubscriptionScheduler subscriptionScheduler; + @EventListener(ApplicationReadyEvent.class) public void onApplicationReadyEvent() throws Exception { if (!environment.acceptsProfiles(Profiles.of(TEST_PROFILE))) { - startupService.run(); + final EsrSystemInfo info = startupService.receiveVnfm(); + subscriptionScheduler.setInfo(info); } } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java index 1882b4e183..cb324c32a9 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/controller/NotificationController.java @@ -38,7 +38,7 @@ public class NotificationController { @Autowired private DmaapService dmaapService; - @PostMapping("${notification.url}") + @PostMapping("${vnfm.notification}") public ResponseEntity receiveNotification(@RequestBody final VnfLcmOperationOccurrenceNotification notification) { logger.info("Notification received {}", notification); dmaapService.send(notification); diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java index abd9ff9d33..a0c1c1e9db 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/exception/VeVnfmException.java @@ -25,4 +25,8 @@ public class VeVnfmException extends Exception { public VeVnfmException(final String message) { super(message); } + + public VeVnfmException(final Throwable cause) { + super(cause); + } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java index eca5240cb5..838a67d115 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProvider.java @@ -20,29 +20,20 @@ package org.onap.so.adapters.vevnfm.provider; -import java.util.List; import org.apache.logging.log4j.util.Strings; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.springframework.http.HttpHeaders; public class AuthorizationHeadersProvider extends BasicHttpHeadersProvider { - private List<String> previousAuthorization; - public void addAuthorization(final String authorization) { - final HttpHeaders headers = getHttpHeaders(); - previousAuthorization = headers.get(AUTHORIZATION_HEADER); - headers.set(AUTHORIZATION_HEADER, authorization); - } - - public void resetPrevious() { - if (!isPreviousAuthorizationBlank()) { - getHttpHeaders().addAll(AUTHORIZATION_HEADER, previousAuthorization); + if (Strings.isBlank(authorization)) { + return; } + + getHttpHeaders().set(AUTHORIZATION_HEADER, authorization); } - private boolean isPreviousAuthorizationBlank() { - return previousAuthorization == null || previousAuthorization.isEmpty() - || Strings.isBlank(previousAuthorization.get(0)); + public void removeAuthorization() { + getHttpHeaders().remove(AUTHORIZATION_HEADER); } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java index dfbafa223c..3d215148f2 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/StartupService.java @@ -20,35 +20,43 @@ package org.onap.so.adapters.vevnfm.service; -import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.aai.AaiConnection; import org.onap.so.adapters.vevnfm.exception.VeVnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.retry.annotation.Backoff; +import org.springframework.retry.annotation.EnableRetry; +import org.springframework.retry.annotation.Recover; +import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @Service +@EnableRetry public class StartupService { - @Autowired - private AaiConnection aaiConnection; + private static final Logger logger = LoggerFactory.getLogger(StartupService.class); + + @Value("${vnfm.default-endpoint}") + private String vnfmDefaultEndpoint; @Autowired - private SubscriberService subscriberService; + private AaiConnection aaiConnection; - private static void isValid(final EsrSystemInfo info) throws VeVnfmException { - if (Strings.isBlank(info.getServiceUrl())) { - throw new VeVnfmException("No 'url' field in VNFM info"); - } + @Retryable(value = {VeVnfmException.class}, maxAttempts = 5, backoff = @Backoff(delay = 5000, multiplier = 10)) + public EsrSystemInfo receiveVnfm() throws VeVnfmException { + return aaiConnection.receiveVnfm(); } - public void run() throws Exception { - final EsrSystemInfo info = aaiConnection.receiveVnfm(); - isValid(info); - final boolean done = subscriberService.subscribe(info); + @Recover + public EsrSystemInfo recoverReceiveVnfm(final Throwable e) { + logger.warn("Connection to AAI failed"); + final EsrSystemInfo info = new EsrSystemInfo(); + info.setServiceUrl(vnfmDefaultEndpoint); + logger.warn("This EsrSystemInfo is used by default: {}", info); - if (!done) { - throw new VeVnfmException("Could not subscribe to VNFM"); - } + return info; } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSender.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscribeSender.java index 8fdfb41d26..d01c3c8f66 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSender.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscribeSender.java @@ -18,9 +18,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.vevnfm.subscription; +package org.onap.so.adapters.vevnfm.service; +import com.fasterxml.jackson.annotation.JsonProperty; import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.onap.so.rest.service.HttpRestServiceProvider; import org.slf4j.Logger; @@ -29,11 +31,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; +import lombok.ToString; -@Component +@Service public class SubscribeSender { + public static final String SLASH = "/"; + private static final Logger logger = LoggerFactory.getLogger(SubscribeSender.class); @Value("${vnfm.subscription}") @@ -42,18 +47,37 @@ public class SubscribeSender { @Autowired private HttpRestServiceProvider restProvider; - public boolean send(final EsrSystemInfo info, final LccnSubscriptionRequest request) { - final ResponseEntity<String> response = restProvider.postHttpRequest(request, getUrl(info), String.class); + public String send(final EsrSystemInfo info, final LccnSubscriptionRequest request) throws VeVnfmException { + final ResponseEntity<SubscribeToManoResponse> response = + restProvider.postHttpRequest(request, getUrl(info), SubscribeToManoResponse.class); final HttpStatus statusCode = response.getStatusCode(); - final String body = response.getBody(); + final SubscribeToManoResponse body = response.getBody(); logger.info("The VNFM replied with the code {} and the body {}", statusCode, body); - return HttpStatus.CREATED == statusCode; + if (HttpStatus.CREATED != statusCode) { + throw new VeVnfmException("The status code was different than " + HttpStatus.CREATED); + } + + return body.id; + } + + public boolean check(final EsrSystemInfo info, final String id) { + final ResponseEntity<SubscribeToManoResponse> response = + restProvider.getHttpResponse(getUrl(info) + SLASH + id, SubscribeToManoResponse.class); + return response.getBody() != null && response.getBody().id.equals(id); } private String getUrl(final EsrSystemInfo info) { return info.getServiceUrl() + vnfmSubscription; } + + @ToString + static class SubscribeToManoResponse { + @JsonProperty("id") + String id; + @JsonProperty("callbackUri") + String callbackUri; + } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java index 0e77ce4073..9760584d7a 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriberService.java @@ -22,9 +22,10 @@ package org.onap.so.adapters.vevnfm.service; import com.squareup.okhttp.Credentials; import java.util.Collections; +import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.adapters.vevnfm.provider.AuthorizationHeadersProvider; -import org.onap.so.adapters.vevnfm.subscription.SubscribeSender; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthentication; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsAuthenticationParamsBasic; @@ -35,16 +36,11 @@ import org.springframework.stereotype.Service; @Service public class SubscriberService { - private static final char COLON = ':'; + @Value("${vevnfmadapter.endpoint}") + private String endpoint; - @Value("${system.url}") - private String systemUrl; - - @Value("${server.port}") - private String serverPort; - - @Value("${notification.url}") - private String notificationUrl; + @Value("${vnfm.notification}") + private String notification; @Value("${spring.security.usercredentials[0].username}") private String username; @@ -59,16 +55,37 @@ public class SubscriberService { private SubscribeSender sender; private static String getAuthorization(final EsrSystemInfo info) { - return Credentials.basic(info.getUserName(), info.getPassword()); + if (info == null) { + return null; + } + + final String userName = info.getUserName(); + + if (Strings.isBlank(userName)) { + return null; + } + + final String password = info.getPassword(); + return Credentials.basic(userName, password); } - public boolean subscribe(final EsrSystemInfo info) { + public String subscribe(final EsrSystemInfo info) throws VeVnfmException { try { headersProvider.addAuthorization(getAuthorization(info)); final LccnSubscriptionRequest request = createRequest(); return sender.send(info, request); + } catch (Exception e) { + throw new VeVnfmException(e); } finally { - headersProvider.resetPrevious(); + headersProvider.removeAuthorization(); + } + } + + public boolean checkSubscription(final EsrSystemInfo info, final String id) throws VeVnfmException { + try { + return sender.check(info, id); + } catch (Exception e) { + throw new VeVnfmException(e); } } @@ -87,6 +104,6 @@ public class SubscriberService { } private String getCallbackUri() { - return systemUrl + COLON + serverPort + notificationUrl; + return endpoint + notification; } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java new file mode 100644 index 0000000000..16427437fc --- /dev/null +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * SO + * ================================================================================ + * Copyright (C) 2020 Samsung. 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.vevnfm.service; + +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +@Service +@EnableScheduling +public class SubscriptionScheduler { + + private static final Logger logger = LoggerFactory.getLogger(SubscriptionScheduler.class); + + @Autowired + private SubscriberService subscriberService; + + private String subscribedId; + + private EsrSystemInfo info; + + public void setInfo(final EsrSystemInfo info) { + this.info = info; + } + + @Scheduled(fixedRate = 5000, initialDelay = 2000) + void subscribeTask() throws VeVnfmException { + if (info != null) { + if (subscribedId == null) { + logger.info("Starting subscribe task"); + subscribedId = subscriberService.subscribe(info); + } + } + } + + @Scheduled(fixedRate = 20000) + void checkSubscribeTask() throws VeVnfmException { + if (info != null) { + if (subscribedId != null) { + logger.info("Checking subscription: {}", subscribedId); + if (!subscriberService.checkSubscription(info, subscribedId)) { + logger.info("Subscription {} not available", subscribedId); + subscribedId = null; + } + } + } + } +} diff --git a/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml b/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml index 35871c51ac..72198b83c1 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml +++ b/adapters/mso-ve-vnfm-adapter/src/main/resources/application.yaml @@ -15,13 +15,10 @@ # limitations under the License. server: - port: 8080 + port: 9098 -system: - url: http://localhost - -notification: - url: /lcm/v1/vnf/instances/notifications +vevnfmadapter: + endpoint: http://so-ve-vnfm-adapter.onap:9098 mso: key: 07a7159d3bf51a0e53be7a8f89699be7 @@ -31,10 +28,12 @@ aai: auth: 75C4483F9C05E2C33A8602635FA532397EC44AB667A2B64DED4FEE08DD932F2E3C1FEE vnfm: + default-endpoint: https://so-vnfm-simulator.onap:9093 subscription: /vnflcm/v1/subscriptions + notification: /lcm/v1/vnf/instances/notifications dmaap: - endpoint: http://message-router:30227 + endpoint: http://message-router.onap:30227 topic: /events/unauthenticated.DCAE_CL_OUTPUT spring: diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java index 57638a165a..974e6ec544 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/controller/NotificationControllerTest.java @@ -53,8 +53,8 @@ public class NotificationControllerTest { private static final String MINIMAL_JSON_CONTENT = "{}"; private static final int ZERO = 0; - @Value("${notification.url}") - private String notificationUrl; + @Value("${vnfm.notification}") + private String notification; @Autowired private WebApplicationContext webApplicationContext; @@ -74,7 +74,7 @@ public class NotificationControllerTest { @Test public void testReceiveNotification() throws Exception { // given - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(notificationUrl) + final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(notification) .contentType(MediaType.APPLICATION_JSON).content(MINIMAL_JSON_CONTENT); mockRestServer.expect(once(), anything()).andRespond(withSuccess()); diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java new file mode 100644 index 0000000000..f9ae427086 --- /dev/null +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/provider/AuthorizationHeadersProviderTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * SO + * ================================================================================ + * Copyright (C) 2020 Samsung. 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.vevnfm.provider; + +import static org.junit.Assert.*; +import static org.onap.so.configuration.rest.BasicHttpHeadersProvider.AUTHORIZATION_HEADER; +import org.junit.Test; +import org.springframework.http.HttpHeaders; + +public class AuthorizationHeadersProviderTest { + + private static final String AUTHORIZATION_EXAMPLE = "authorization"; + private static final String BLANK_EXAMPLE = "\t\n"; + private static final String EMPTY = ""; + + private final AuthorizationHeadersProvider provider = new AuthorizationHeadersProvider(); + + @Test + public void testSuccessValidAuthorizationAndRemoval() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(AUTHORIZATION_EXAMPLE); + assertEquals(size + 1, headers.size()); + assertTrue(headers.containsKey(AUTHORIZATION_HEADER)); + + provider.removeAuthorization(); + assertEquals(size, headers.size()); + assertFalse(headers.containsKey(AUTHORIZATION_HEADER)); + } + + @Test + public void testBlankAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(BLANK_EXAMPLE); + assertEquals(size, headers.size()); + } + + @Test + public void testEmptyAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(EMPTY); + assertEquals(size, headers.size()); + } + + @Test + public void testNullAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.addAuthorization(null); + assertEquals(size, headers.size()); + } + + @Test + public void testRemoveAuthorization() { + final HttpHeaders headers = provider.getHttpHeaders(); + final int size = headers.size(); + + provider.removeAuthorization(); + provider.removeAuthorization(); + assertEquals(size, headers.size()); + } +} diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java index 0f9c23e261..d1d34a706f 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/StartupServiceTest.java @@ -20,7 +20,9 @@ package org.onap.so.adapters.vevnfm.service; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -30,62 +32,34 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.aai.AaiConnection; -import org.onap.so.adapters.vevnfm.exception.VeVnfmException; @RunWith(MockitoJUnitRunner.class) public class StartupServiceTest { - @Mock - private AaiConnection aaiConnection; + private static final String URL = "rt"; + + @Rule + public ExpectedException thrown = ExpectedException.none(); @Mock - private SubscriberService subscriberService; + private AaiConnection aaiConnection; @InjectMocks private StartupService startupService; - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test public void testSuccess() throws Exception { // given final EsrSystemInfo info = new EsrSystemInfo(); - info.setServiceUrl("lh"); - when(aaiConnection.receiveVnfm()).thenReturn(info); - when(subscriberService.subscribe(info)).thenReturn(true); - - // when - startupService.run(); - - // then - verify(aaiConnection, times(1)).receiveVnfm(); - verify(subscriberService, times(1)).subscribe(info); - } + info.setServiceUrl(URL); - @Test - public void testFailureAai() throws Exception { - // given - final EsrSystemInfo info = new EsrSystemInfo(); when(aaiConnection.receiveVnfm()).thenReturn(info); - thrown.expect(VeVnfmException.class); - // when - startupService.run(); - } - - @Test - public void testFailureSubscriber() throws Exception { - // given - final EsrSystemInfo info = new EsrSystemInfo(); - info.setServiceUrl("lh"); - when(aaiConnection.receiveVnfm()).thenReturn(info); - when(subscriberService.subscribe(info)).thenReturn(false); + final EsrSystemInfo systemInfo = startupService.receiveVnfm(); - thrown.expect(VeVnfmException.class); - - // when - startupService.run(); + // then + verify(aaiConnection).receiveVnfm(); + assertEquals(info, systemInfo); } } diff --git a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSenderTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscribeSenderTest.java index d1fda0eee6..b7f1f982a2 100644 --- a/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/subscription/SubscribeSenderTest.java +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscribeSenderTest.java @@ -18,9 +18,10 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.vevnfm.subscription; +package org.onap.so.adapters.vevnfm.service; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.onap.so.adapters.vevnfm.service.SubscribeSender.SLASH; import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.test.web.client.ExpectedCount.once; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; @@ -33,6 +34,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.so.adapters.vevnfm.configuration.StartupConfiguration; +import org.onap.so.adapters.vevnfm.exception.VeVnfmException; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.LccnSubscriptionRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -50,8 +52,9 @@ import org.springframework.web.client.RestTemplate; @ActiveProfiles(StartupConfiguration.TEST_PROFILE) public class SubscribeSenderTest { - private static final String SLASH = "/"; - private static final String MINIMAL_JSON_CONTENT = "{}"; + private static final String URL = "lh"; + private static final String ID = "1a2s3d4f"; + private static final String JSON = "{\"id\":\"" + ID + "\"}"; private static final Gson GSON; @@ -78,22 +81,22 @@ public class SubscribeSenderTest { } @Test - public void testSuccess() { + public void testSuccess() throws VeVnfmException { // given final EsrSystemInfo info = new EsrSystemInfo(); - info.setServiceUrl("lh"); + info.setServiceUrl(URL); final LccnSubscriptionRequest request = new LccnSubscriptionRequest(); mockRestServer.expect(once(), requestTo(SLASH + info.getServiceUrl() + vnfmSubscription)) .andExpect(header(CONTENT_TYPE, CoreMatchers.containsString(MediaType.APPLICATION_JSON_VALUE))) .andExpect(method(HttpMethod.POST)).andExpect(content().json(GSON.toJson(request))) - .andRespond(withStatus(HttpStatus.CREATED).body(MINIMAL_JSON_CONTENT)); + .andRespond(withStatus(HttpStatus.CREATED).body(JSON).contentType(MediaType.APPLICATION_JSON)); // when - final boolean done = sender.send(info, request); + final String id = sender.send(info, request); // then - assertTrue(done); mockRestServer.verify(); + assertEquals(ID, id); } } diff --git a/adapters/mso-vfc-adapter/pom.xml b/adapters/mso-vfc-adapter/pom.xml index 09dd512629..451831f966 100644 --- a/adapters/mso-vfc-adapter/pom.xml +++ b/adapters/mso-vfc-adapter/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vfc-adapter</artifactId> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml index bf293e5f4b..bb322eb1d8 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vnfm-adapter</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-vnfm-adapter-api</artifactId> <properties> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/src/main/resources/ETSI-Catalog-Notification-API.json b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/src/main/resources/ETSI-Catalog-Notification-API.json index 6f9b2c3bbe..6db54435d2 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/src/main/resources/ETSI-Catalog-Notification-API.json +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/src/main/resources/ETSI-Catalog-Notification-API.json @@ -6,18 +6,26 @@ "version": "v1" }, "host": "127.0.0.1:8000", - "schemes": ["http"], + "schemes": [ + "http" + ], "basePath": "/", - "consumes": ["application/json"], - "produces": ["application/json"], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], "securityDefinitions": { "Basic": { "type": "basic" } }, - "security": [{ - "Basic": [] - }], + "security": [ + { + "Basic": [] + } + ], "paths": { "/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification": { "get": { @@ -35,25 +43,31 @@ } } }, - "tags": ["VNF Package Management interface"] + "tags": [ + "VNF Package Management interface" + ] }, "post": { "operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification_create", "description": "", - "parameters": [{ - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/PkgChangeNotification" + "parameters": [ + { + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/PkgChangeNotification" + } } - }], + ], "responses": { "204": { "description": "" } }, - "tags": ["VNF Package Management interface"] + "tags": [ + "VNF Package Management interface" + ] }, "parameters": [] }, @@ -73,25 +87,31 @@ } } }, - "tags": ["VNF Package Management interface"] + "tags": [ + "VNF Package Management interface" + ] }, "post": { "operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification_create", "description": "", - "parameters": [{ - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/PkgOnboardingNotification" + "parameters": [ + { + "name": "data", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/PkgOnboardingNotification" + } } - }], + ], "responses": { "204": { "description": "" } }, - "tags": ["VNF Package Management interface"] + "tags": [ + "VNF Package Management interface" + ] }, "parameters": [] } @@ -100,7 +120,9 @@ "NOTIFICATION_LINKSERIALIZER": { "title": "Vnfpackage", "description": "Link to the resource representing the VNF package to which the notified change applies.", - "required": ["href"], + "required": [ + "href" + ], "type": "object", "properties": { "href": { @@ -125,7 +147,16 @@ } }, "PkgChangeNotification": { - "required": ["id", "notificationType", "timeStamp", "subscriptionId", "vnfPkgId", "changeType", "vnfdId", "_links"], + "required": [ + "id", + "notificationType", + "timeStamp", + "subscriptionId", + "vnfPkgId", + "changeType", + "vnfdId", + "_links" + ], "type": "object", "properties": { "id": { @@ -138,7 +169,9 @@ "title": "Notificationtype", "description": "Discriminator for the different notification types.", "type": "string", - "enum": ["VnfPackageChangeNotification"] + "enum": [ + "VnfPackageChangeNotification" + ] }, "timeStamp": { "title": "Timestamp", @@ -156,19 +189,25 @@ "title": "Vnfpkgid", "description": "Identifier of the VNF package.", "type": "string", - "format": "uuid" + "minLength": 1 }, "changeType": { "title": "Changetype", "description": "The type of change of the VNF package.", "type": "string", - "enum": ["OP_STATE_CHANGE", "PKG_DELETE"] + "enum": [ + "OP_STATE_CHANGE", + "PKG_DELETE" + ] }, "operationalState": { "title": "Operationalstate", "description": "New operational state of the VNF package.", "type": "string", - "enum": ["ENABLED", "DISABLED"] + "enum": [ + "ENABLED", + "DISABLED" + ] }, "vnfdId": { "title": "Vnfdid", @@ -182,7 +221,15 @@ } }, "PkgOnboardingNotification": { - "required": ["id", "notificationType", "subscriptionId", "timeStamp", "vnfPkgId", "vnfdId", "_links"], + "required": [ + "id", + "notificationType", + "subscriptionId", + "timeStamp", + "vnfPkgId", + "vnfdId", + "_links" + ], "type": "object", "properties": { "id": { @@ -195,7 +242,9 @@ "title": "Notificationtype", "description": "Discriminator for the different notification types.", "type": "string", - "enum": ["VnfPackageOnboardingNotification"] + "enum": [ + "VnfPackageOnboardingNotification" + ] }, "subscriptionId": { "title": "Subscriptionid", @@ -213,13 +262,13 @@ "title": "Vnfpkgid", "description": "Identifier of the VNF package.", "type": "string", - "format": "uuid" + "minLength": 1 }, "vnfdId": { "title": "Vnfdid", "description": "This identifier, which is managed by the VNF provider, identifies the VNF package and the VNFD in a globally unique way.", "type": "string", - "format": "uuid" + "minLength": 1 }, "_links": { "$ref": "#/definitions/PkgmLinks" @@ -227,4 +276,4 @@ } } } -}
\ No newline at end of file +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml index 8e2cfd2be4..a643aaa5b8 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vnfm-adapter</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-vnfm-adapter-ext-clients</artifactId> <properties> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml index bc491a6fc5..66b1d2e12e 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vnfm-adapter</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-vnfm-etsi-adapter</artifactId> <properties> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Constants.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Constants.java index fb32fb9605..d798267918 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Constants.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/Constants.java @@ -32,8 +32,12 @@ public class Constants { public static final String SERVICE_VERSION = "v1"; public static final String BASE_URL = "/so/" + SERVICE_NAME + "/" + SERVICE_VERSION; public static final String PACKAGE_MANAGEMENT_BASE_URL = BASE_URL + "/vnfpkgm/v1"; - public static final String ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL = BASE_URL + "/etsicatalogmanager/notification"; - public static final String ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL = BASE_URL + "/etsicatalogmanager"; + public static final String ETSI_CATALOG_MANAGER_BASE_ENDPOINT = "/etsicatalogmanager"; + public static final String ETSI_SUBSCRIPTION_NOTIFICATION_ENDPOINT = "/notification"; + public static final String ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL = + BASE_URL + ETSI_CATALOG_MANAGER_BASE_ENDPOINT; + public static final String ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL = + ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL + ETSI_SUBSCRIPTION_NOTIFICATION_ENDPOINT; public static final String APPLICATION_ZIP = "application/zip"; public static final String OPERATION_NOTIFICATION_ENDPOINT = "/lcn/VnfLcmOperationOccurrenceNotification"; diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java index 61d5adf9d8..87e8bb4d57 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java @@ -23,6 +23,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.Collection; +import org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003.PkgChangeNotificationConverter; +import org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003.PkgOnboardingNotificationConverter; import org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003.VnfPkgInfoConverter; import org.onap.so.adapters.vnfmadapter.converters.sol003.etsicatalog.PkgmSubscriptionRequestConverter; import org.onap.so.adapters.vnfmadapter.oauth.OAuth2AccessTokenAdapter; @@ -46,6 +48,8 @@ public class MessageConverterConfiguration { final DefaultConversionService service = new DefaultConversionService(); service.addConverter(new VnfPkgInfoConverter()); service.addConverter(new PkgmSubscriptionRequestConverter()); + service.addConverter(new PkgChangeNotificationConverter()); + service.addConverter(new PkgOnboardingNotificationConverter()); return service; } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmBasicHttpSecurityConfigurer.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmBasicHttpSecurityConfigurer.java index 1e0a18a339..f1815054e3 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmBasicHttpSecurityConfigurer.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmBasicHttpSecurityConfigurer.java @@ -9,9 +9,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,7 +35,6 @@ import org.springframework.util.StringUtils; /** * @author Waqas Ikram (waqas.ikram@est.tech) * @author Gareth Roper (gareth.roper@est.tech) - * */ @Primary @Component @@ -53,10 +52,10 @@ public class VnfmBasicHttpSecurityConfigurer implements HttpSecurityConfigurer { http.csrf().disable().authorizeRequests().anyRequest().permitAll(); } else { http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers(HttpMethod.GET, "/etsi/subscription/notification").permitAll().antMatchers("/**") + .antMatchers(HttpMethod.GET, Constants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL).permitAll() + .antMatchers("/**") .hasAnyRole(StringUtils.collectionToDelimitedString(soUserCredentialConfiguration.getRoles(), ",")) .and().httpBasic(); - } } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java new file mode 100644 index 0000000000..e1c43098f8 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/AbstractPkgNotificationConverter.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003; + +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgmLinks; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage; + +/** + * A base class that can be extended by classes for converting Etsi Catalog Manager Pkg Notification classes. Provides + * common methods that will be useful to those classes. + * + * @author andrew.a.lamb@est.tech + */ +abstract public class AbstractPkgNotificationConverter { + + protected URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks convert( + final PkgmLinks pkgmLinks) { + final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage linksVnfPackage = + new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage(); + if (pkgmLinks.getVnfPackage() != null) { + linksVnfPackage.setHref(pkgmLinks.getVnfPackage().getHref()); + } + + final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage linksSubscription = + new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinksVnfPackage(); + if (pkgmLinks.getSubscription() != null) { + linksSubscription.setHref(pkgmLinks.getSubscription().getHref()); + } + + final URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks links = + new URIisprovidedbytheclientwhencreatingthesubscriptionVnfPackageOnboardingNotificationLinks(); + links.setVnfPackage(linksVnfPackage); + links.setSubscription(linksSubscription); + return links; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java new file mode 100644 index 0000000000..8c4168632b --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/PkgChangeNotificationConverter.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.VnfPackageChangeNotification; +import org.slf4j.Logger; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; + +/** + * Converter to convert from an Etsi Catalog Manager {@link PkgChangeNotification} Object to its equivalent SOL003 + * {@link VnfPackageChangeNotification} Object + * + * @author andrew.a.lamb@est.tech + */ +@Service +public class PkgChangeNotificationConverter extends AbstractPkgNotificationConverter + implements Converter<PkgChangeNotification, VnfPackageChangeNotification> { + private static final Logger logger = getLogger(PkgChangeNotificationConverter.class); + + /** + * Convert a {@link PkgChangeNotification} Object to an {@link VnfPackageChangeNotification} Object + * + * @param pkgChangeNotification The PkgChangeNotification Object to Convert + * @return The Converted VnfPackageChangeNotification Object + */ + @Override + public VnfPackageChangeNotification convert(final PkgChangeNotification pkgChangeNotification) { + logger.info("Converting PkgChangeNotification\n{}", pkgChangeNotification.toString()); + final VnfPackageChangeNotification vnfPackageChangeNotification = new VnfPackageChangeNotification(); + vnfPackageChangeNotification.setId(pkgChangeNotification.getId()); + + if (pkgChangeNotification.getNotificationType() != null) { + vnfPackageChangeNotification.setNotificationType(VnfPackageChangeNotification.NotificationTypeEnum + .fromValue(pkgChangeNotification.getNotificationType().getValue())); + } + + vnfPackageChangeNotification.setSubscriptionId(pkgChangeNotification.getSubscriptionId()); + vnfPackageChangeNotification.setTimeStamp(pkgChangeNotification.getTimeStamp()); + vnfPackageChangeNotification.setVnfPkgId(pkgChangeNotification.getVnfPkgId()); + + vnfPackageChangeNotification.setVnfdId(pkgChangeNotification.getVnfdId()); + + if (pkgChangeNotification.getChangeType() != null) { + vnfPackageChangeNotification.setChangeType(VnfPackageChangeNotification.ChangeTypeEnum + .fromValue(pkgChangeNotification.getChangeType().getValue())); + } + + if (pkgChangeNotification.getOperationalState() != null) { + vnfPackageChangeNotification.setOperationalState(VnfPackageChangeNotification.OperationalStateEnum + .fromValue(pkgChangeNotification.getOperationalState().getValue())); + } + + vnfPackageChangeNotification.setLinks(convert((pkgChangeNotification.getLinks()))); + + return vnfPackageChangeNotification; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java new file mode 100644 index 0000000000..836acb6d36 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/PkgOnboardingNotificationConverter.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.VnfPackageOnboardingNotification; +import org.slf4j.Logger; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; + +/** + * Converter to convert from an Etsi Catalog Manager {@link PkgOnboardingNotification} Object to its equivalent SOL003 + * {@link VnfPackageOnboardingNotification} Object + * + * @author andrew.a.lamb@est.tech + */ +@Service +public class PkgOnboardingNotificationConverter extends AbstractPkgNotificationConverter + implements Converter<PkgOnboardingNotification, VnfPackageOnboardingNotification> { + private static final Logger logger = getLogger(PkgOnboardingNotificationConverter.class); + + /** + * Convert a {@link PkgOnboardingNotification} Object to an {@link VnfPackageOnboardingNotification} Object + * + * @param pkgOnboardingNotification The PkgOnboardingNotification Object to Convert + * @return The Converted VnfPackageOnboardingNotification Object + */ + @Override + public VnfPackageOnboardingNotification convert(final PkgOnboardingNotification pkgOnboardingNotification) { + logger.info("Converting PkgChangeNotification\n{}", pkgOnboardingNotification.toString()); + final VnfPackageOnboardingNotification vnfPackageOnboardingNotification = + new VnfPackageOnboardingNotification(); + vnfPackageOnboardingNotification.setId(pkgOnboardingNotification.getId()); + + if (pkgOnboardingNotification.getNotificationType() != null) { + vnfPackageOnboardingNotification.setNotificationType(VnfPackageOnboardingNotification.NotificationTypeEnum + .fromValue(pkgOnboardingNotification.getNotificationType().getValue())); + } + + vnfPackageOnboardingNotification.setSubscriptionId(pkgOnboardingNotification.getSubscriptionId()); + vnfPackageOnboardingNotification.setTimeStamp(pkgOnboardingNotification.getTimeStamp()); + vnfPackageOnboardingNotification.setVnfPkgId(pkgOnboardingNotification.getVnfPkgId()); + vnfPackageOnboardingNotification.setVnfdId(pkgOnboardingNotification.getVnfdId()); + + vnfPackageOnboardingNotification.setLinks(convert((pkgOnboardingNotification.getLinks()))); + + return vnfPackageOnboardingNotification; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java index c6d51c99aa..d0fd4c9e7c 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/sol003/etsicatalog/PkgmSubscriptionRequestConverter.java @@ -20,14 +20,10 @@ package org.onap.so.adapters.vnfmadapter.converters.sol003.etsicatalog; -import static org.slf4j.LoggerFactory.getLogger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Optional; -import java.util.UUID; -import javax.swing.text.html.Option; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.Version; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfProducts; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfProductsProviders; @@ -38,7 +34,6 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model. import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsFilterVersions; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsFilterVnfProducts; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsFilterVnfProductsFromProviders; -import org.slf4j.Logger; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Service; @@ -48,14 +43,11 @@ import org.springframework.stereotype.Service; * * @author Ronan Kenny (ronan.kenny@est.tech) * @author Gareth Roper (gareth.roper@est.tech) - * */ @Service public class PkgmSubscriptionRequestConverter implements Converter<PkgmSubscriptionRequest, org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest> { - private static final Logger logger = getLogger(PkgmSubscriptionRequestConverter.class); - @Override public org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest convert( PkgmSubscriptionRequest pkgmSubscriptionRequest) { @@ -133,7 +125,8 @@ public class PkgmSubscriptionRequestConverter implements final List<VnfProductsProviders> etsiCatalogManagerVnfProductsProviders = new ArrayList<>(); filterProductsFromProvider.forEach(vnfProduct -> { etsiCatalogManagerVnfProductsProviders - .add(new VnfProductsProviders().vnfProducts(getVnfProducts(vnfProduct.getVnfProducts()))); + .add(new VnfProductsProviders().vnfProvider(vnfProduct.getVnfProvider()) + .vnfProducts(getVnfProducts(vnfProduct.getVnfProducts()))); }); return etsiCatalogManagerVnfProductsProviders; } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java index 62b365745c..0dcc49eeac 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java @@ -21,9 +21,9 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; -import org.springframework.http.ResponseEntity; /** * Provides methods for invoking REST calls to the ETSI Catalog Manager. @@ -74,11 +74,26 @@ public interface EtsiCatalogServiceProvider { Optional<byte[]> getVnfPackageArtifact(final String vnfPkgId, final String artifactPath); /** - * Post the SubscriptionRequest Object. + * POST the SubscriptionRequest Object. * - * @return The ResponseEntity containing the ETSI Catalog Manager's PkgmSubscription object. + * @return The ETSI Catalog Manager's PkgmSubscription object. */ Optional<PkgmSubscription> postSubscription( final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest); + /** + * Get the Subscription from ETSI Catalog. + * + * @param subscriptionId Subscription ID + * @return The Subscription {@link NsdmSubscription} from ETSI Catalog + */ + Optional<NsdmSubscription> getSubscription(final String subscriptionId); + + /** + * DELETE the SubscriptionRequest Object. + * + * @return A Boolean representing if the delete was successful or not. + */ + boolean deleteSubscription(final String subscriptionId); + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java index 1a48494e1a..30d084629c 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java @@ -21,11 +21,16 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; import java.util.Optional; -import javax.swing.text.html.Option; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPkgInfo; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.*; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.EtsiCatalogManagerBadRequestException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.EtsiCatalogManagerRequestFailureException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionNotFoundException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgBadRequestException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgConflictException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgNotFoundException; import org.onap.so.rest.exceptions.HttpResouceNotFoundException; import org.onap.so.rest.exceptions.InvalidRestRequestException; import org.onap.so.rest.exceptions.RestProcessingException; @@ -76,7 +81,7 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide etsiCatalogUrlProvider.getVnfPackageArtifactUrl(vnfPkgId, artifactPath), byte[].class); logger.info("getVnfPackageArtifact Request to ETSI Catalog Manager Status Code: {}", response.getStatusCodeValue()); - if (response.getStatusCode() == HttpStatus.OK) { + if (response.getStatusCode().is2xxSuccessful()) { return Optional.ofNullable(response.getBody()); } } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { @@ -101,7 +106,7 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide httpServiceProvider.getHttpResponse(etsiCatalogUrlProvider.getVnfPackagesUrl(), VnfPkgInfo[].class); logger.info("getVnfPackages Request to ETSI Catalog Manager Status Code: {}", response.getStatusCodeValue()); - if (response.getStatusCode() == HttpStatus.OK) { + if (response.getStatusCode().is2xxSuccessful()) { if (response.hasBody()) { final VnfPkgInfo[] vnfPackages = response.getBody(); assert (vnfPackages != null); @@ -142,7 +147,7 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide .getHttpResponse(etsiCatalogUrlProvider.getVnfPackageUrl(vnfPkgId), VnfPkgInfo.class); logger.info("getVnfPackage Request for vnfPkgId {} to ETSI Catalog Manager Status Code: {}", vnfPkgId, response.getStatusCodeValue()); - if (response.getStatusCode() == HttpStatus.OK) { + if (response.getStatusCode().is2xxSuccessful()) { if (response.hasBody()) { final VnfPkgInfo vnfPkgInfo = response.getBody(); if (conversionService.canConvert(vnfPkgInfo.getClass(), InlineResponse2001.class)) { @@ -180,7 +185,7 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide final ResponseEntity<PkgmSubscription> responseEntity = httpServiceProvider.postHttpRequest(etsiCatalogManagerSubscriptionRequest, etsiCatalogUrlProvider.getSubscriptionUrl(), PkgmSubscription.class); - if (responseEntity.getStatusCode() == HttpStatus.OK) { + if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.hasBody()) { return Optional.of(responseEntity.getBody()); } @@ -190,7 +195,8 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide return Optional.empty(); } catch (final InvalidRestRequestException invalidRestRequestException) { logger.error("Caught InvalidRestRequestException", invalidRestRequestException); - throw new EtsiCatalogManagerBadRequestException("Bad Request Received on postSubscription call."); + throw new EtsiCatalogManagerBadRequestException( + "Bad Request Received on postSubscription call to ETSI Catalog Manager."); } catch (final RestProcessingException restProcessingException) { logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), restProcessingException); @@ -200,6 +206,53 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide } } + @Override + public boolean deleteSubscription(final String subscriptionId) { + try { + final ResponseEntity<Void> responseEntity = httpServiceProvider + .deleteHttpRequest(etsiCatalogUrlProvider.getSubscriptionUrl() + "/" + subscriptionId, Void.class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.info("Subscription with ID: {} has been successfully deleted from the ETSI Catalog Manager", + subscriptionId); + return true; + } + logger.error("Unexpected Status Code Received on deleteSubscription: {}", responseEntity.getStatusCode()); + return false; + } catch (final HttpResouceNotFoundException resouceNotFoundException) { + final String message = "Unable to find subscription in ETSI Catalog Manager using id: " + subscriptionId; + logger.error(message); + throw new SubscriptionNotFoundException(message); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException on deleteSubscription call to ETSI Catalog Manager.", + invalidRestRequestException); + throw new EtsiCatalogManagerBadRequestException( + "Bad Request Received on deleteSubscription call to ETSI Catalog Manager."); + } + } + + @Override + public Optional<NsdmSubscription> getSubscription(final String subscriptionId) { + try { + final ResponseEntity<NsdmSubscription> responseEntity = httpServiceProvider.getHttpResponse( + etsiCatalogUrlProvider.getSubscriptionUrl() + "/" + subscriptionId, NsdmSubscription.class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.debug("Found subscription with ID: {} in ETSI Catalog Manager", subscriptionId); + return Optional.ofNullable(responseEntity.getBody()); + } + logger.error("Unexpected Status Code Received on getting subscription from ETSI Catalog Manager: {}", + responseEntity.getStatusCode()); + } catch (final HttpResouceNotFoundException resouceNotFoundException) { + logger.error("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId); + return Optional.empty(); + } catch (final RestProcessingException | InvalidRestRequestException exception) { + logger.error("Unable to query ETSI Catalog Manager for subscription using id: {}", subscriptionId, + exception); + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + private Optional<byte[]> requestVnfElement(final String vnfPkgId, final String vnfRequestUrl, final String vnfRequestName) { try { diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java new file mode 100644 index 0000000000..86ca59cffe --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import java.nio.charset.StandardCharsets; +import org.apache.commons.codec.binary.Base64; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.web.client.RestTemplate; + +/** + * A base class that can be extended by classes for providing notification services. Provides common methods that will + * be useful to those classes. + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +public abstract class AbstractNotificationServiceProvider { + + @Autowired + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate restTemplate; + + protected HttpRestServiceProvider getHttpRestServiceProvider(final HttpHeadersProvider httpHeadersProvider) { + final HttpRestServiceProvider httpRestServiceProvider = + new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + return httpRestServiceProvider; + } + + protected BasicHttpHeadersProvider getBasicHttpHeadersProviderWithBasicAuth(final String username, + final String password) { + final byte[] encodedAuth = getBasicAuth(username, password); + final String authHeader = "Basic " + new String(encodedAuth); + return new BasicHttpHeadersProvider(authHeader); + } + + protected byte[] getBasicAuth(final String username, final String password) { + final String auth = username + ":" + password; + return Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java new file mode 100644 index 0000000000..6f9d94e9de --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * Implementation of a NotificationServiceProvider which supports Basic Authentication + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Service +public class BasicAuthNotificationServiceProvider extends AbstractNotificationServiceProvider + implements NotificationServiceProvider { + + private static final Logger logger = getLogger(BasicAuthNotificationServiceProvider.class); + + @Override + public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri) { + logger.info("Sending notification to uri: {}", callbackUri); + final HttpHeadersProvider httpHeadersProvider = + getBasicHttpHeadersProviderWithBasicAuth(subscriptionsAuthentication.getParamsBasic().getUserName(), + subscriptionsAuthentication.getParamsBasic().getPassword()); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); + + final ResponseEntity<Void> responseEntity = + httpRestServiceProvider.postHttpRequest(notification, callbackUri, Void.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.info("Notification sent successfully."); + return true; + } + + logger.error("Failed to send notification."); + return false; + } + + @Override + public AuthTypeEnum getAuthType() { + return AuthTypeEnum.BASIC; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationManager.java new file mode 100644 index 0000000000..c1051d1c9d --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationManager.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.List; +import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.VnfPackageChangeNotification; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.VnfPackageOnboardingNotification; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.AuthenticationTypeNotSupportedException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.ConversionFailedException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.NotificationTypeNotSupportedException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionNotFoundException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.ConversionService; +import org.springframework.stereotype.Service; + +/** + * Manages package management subscription notifications to the VNFMs + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + * + */ +@Service +public class NotificationManager { + + private static final Logger logger = getLogger(NotificationManager.class); + private final ConversionService conversionService; + private final SubscriptionManager subscriptionManager; + private final NotificationServiceProviderFactory notificationServiceProviderFactory; + + @Autowired + public NotificationManager(final SubscriptionManager subscriptionManager, final ConversionService conversionService, + final NotificationServiceProviderFactory notificationServiceProviderFactory) { + this.subscriptionManager = subscriptionManager; + this.conversionService = conversionService; + this.notificationServiceProviderFactory = notificationServiceProviderFactory; + } + + /** + * Process a subscription notification. Checks for a subscription request stored in the adapter and if there is, it + * sends the notification to the subscribed vnfm. + * + * @param notification the notification to send to the vnfm + * @param subscriptionId the id of the subscription request + * @return true if the notification is successfully sent + */ + public boolean processSubscriptionNotification(final Object notification, final String subscriptionId) { + final Optional<PkgmSubscriptionRequest> optionalSubscription = + subscriptionManager.getSubscriptionRequest(subscriptionId); + if (optionalSubscription.isPresent()) { + final PkgmSubscriptionRequest subscriptionRequest = optionalSubscription.get(); + return notifyVnfm(subscriptionRequest, notification); + } + final String errorMessage = "No subscription found with subscriptionId " + subscriptionId + + ". Unable to forward notification to subscriber."; + logger.error(errorMessage); + throw new SubscriptionNotFoundException(errorMessage); + } + + private boolean notifyVnfm(final PkgmSubscriptionRequest subscriptionRequest, final Object notification) { + if (!(notification instanceof PkgOnboardingNotification) && !(notification instanceof PkgChangeNotification)) { + final String errorMessage = + "An error occurred. Notification type not supported for: " + notification.getClass(); + logger.error(errorMessage); + throw new NotificationTypeNotSupportedException(errorMessage); + } + + final SubscriptionsAuthentication subscriptionsAuthentication = subscriptionRequest.getAuthentication(); + final AuthTypeEnum authType = getAuthType(subscriptionsAuthentication.getAuthType()); + final NotificationServiceProvider sender = notificationServiceProviderFactory.getNotificationSender(authType); + + final Object vnfmNotificationObject = convertEtsiCatalogNotification(notification); + + if (sender.send(vnfmNotificationObject, subscriptionsAuthentication, subscriptionRequest.getCallbackUri())) { + logger.info("Notification delivered successfully {}", notification); + return true; + } + + logger.error("Failed to deliver notification."); + return false; + } + + private SubscriptionsAuthentication.AuthTypeEnum getAuthType(final List<AuthTypeEnum> authTypes) { + if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT)) { + return SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT; + } + if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS)) { + return SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS; + } + if (authTypes.contains(SubscriptionsAuthentication.AuthTypeEnum.BASIC)) { + return SubscriptionsAuthentication.AuthTypeEnum.BASIC; + } + final String errorMessage = + "An error occurred. No supported authentication type provided in subscription request."; + logger.error(errorMessage); + throw new AuthenticationTypeNotSupportedException(errorMessage); + } + + private Object convertEtsiCatalogNotification(final Object etsiCatalogNotification) { + logger.info("Converting notification:\n {}", etsiCatalogNotification); + if (conversionService.canConvert(etsiCatalogNotification.getClass(), VnfPackageOnboardingNotification.class)) { + return conversionService.convert(etsiCatalogNotification, VnfPackageOnboardingNotification.class); + } else if (conversionService.canConvert(etsiCatalogNotification.getClass(), + VnfPackageChangeNotification.class)) { + return conversionService.convert(etsiCatalogNotification, VnfPackageChangeNotification.class); + } + final String errorMessage = "An error occurred. Unable to convert provided notification object."; + logger.error(errorMessage + "\n" + etsiCatalogNotification); + throw new ConversionFailedException(errorMessage); + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java new file mode 100644 index 0000000000..2be80eec75 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationServiceProvider.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; + +/** + * Interface which lays out requirements for a Notification Service Provider + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +public interface NotificationServiceProvider { + + /** + * Method to send a notification to a uri, given the subscription authentication + * + * @param notification The notification to send + * @param subscriptionsAuthentication Object containing the authentication details + * @param callbackUri The uri to send the notification to + * @return true if notification is delivered successfully, otherwise false + */ + boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri); + + /** + * Method to get the supported authorization type of the service provider + * + * @return the supported AuthTypeEnum + */ + AuthTypeEnum getAuthType(); + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java new file mode 100644 index 0000000000..ab67afed82 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/NotificationServiceProviderFactory.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.AuthenticationTypeNotSupportedException; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Factory to provide a notification services + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Component +public class NotificationServiceProviderFactory { + + private static final Logger logger = getLogger(NotificationServiceProviderFactory.class); + private static final Map<AuthTypeEnum, NotificationServiceProvider> CACHE = new HashMap<>(); + + @Autowired + public NotificationServiceProviderFactory(final List<NotificationServiceProvider> services) { + for (final NotificationServiceProvider notificationServiceProvider : services) { + logger.debug("Adding {} of type {} to cache", notificationServiceProvider.getClass().getCanonicalName(), + notificationServiceProvider.getAuthType()); + CACHE.put(notificationServiceProvider.getAuthType(), notificationServiceProvider); + } + } + + /** + * Get a notification service for a given authorization type + * + * @param type the type of authentication required + * @return the notification service + */ + public NotificationServiceProvider getNotificationSender(final AuthTypeEnum type) { + final NotificationServiceProvider service = CACHE.get(type); + if (service == null) { + throw new AuthenticationTypeNotSupportedException("Unknown type: " + type); + } + return service; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java new file mode 100644 index 0000000000..496fb083cf --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.InternalServerErrorException; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + * + */ +@Service +public class OAuthNotificationServiceProvider extends AbstractNotificationServiceProvider + implements NotificationServiceProvider { + + private static final Logger logger = getLogger(OAuthNotificationServiceProvider.class); + + @Override + public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri) { + logger.info("Sending notification to uri: {}", callbackUri); + final String token = getAccessToken(subscriptionsAuthentication); + + if (token == null) { + return false; + } + + final HttpHeadersProvider httpHeadersProvider = getHttpHeadersProvider(token); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); + final ResponseEntity<Void> responseEntity = + httpRestServiceProvider.postHttpRequest(notification, callbackUri, Void.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + logger.info("Notification sent successfully."); + return true; + } + + logger.error("Failed to send notification."); + return false; + } + + @Override + public AuthTypeEnum getAuthType() { + return AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS; + } + + private BasicHttpHeadersProvider getHttpHeadersProvider(final String token) { + final String authHeader = "Bearer " + token; + return new BasicHttpHeadersProvider(authHeader); + } + + private String getAccessToken(final SubscriptionsAuthentication subscriptionsAuthentication) { + logger.info("Requesting Access Token."); + + final String tokenEndpoint = subscriptionsAuthentication.getParamsOauth2ClientCredentials().getTokenEndpoint(); + + final HttpHeadersProvider httpHeadersProvider = getBasicHttpHeadersProviderWithBasicAuth( + subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientId(), + subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientPassword()); + + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); + final ResponseEntity<OAuthTokenResponse> responseEntity = + httpRestServiceProvider.postHttpRequest(null, tokenEndpoint, OAuthTokenResponse.class); + if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (responseEntity.getBody() != null) { + logger.info("Returning Access Token."); + return responseEntity.getBody().getAccessToken(); + } + } + + final String errorMessage = "An error occurred. Unable to retrieve OAuth Token from VNFM for notification."; + logger.error(errorMessage); + throw new InternalServerErrorException(errorMessage); + } + + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java new file mode 100644 index 0000000000..146641cc7c --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthTokenResponse.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlElement; +import com.google.gson.annotations.SerializedName; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +public class OAuthTokenResponse implements Serializable { + + private static final long serialVersionUID = -6455742984985959926L; + + @XmlElement(name = "access_token") + @SerializedName("access_token") + private String accessToken; + + /** + * Get the Accees Token + * + * @return the Access Token + */ + public String getAccessToken() { + return accessToken; + } + + /** + * Set the Access Token + * + * @param accessToken + */ + public void setAccessToken(final String accessToken) { + this.accessToken = accessToken; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java index 30a16f70a8..a4c52fd13d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java @@ -31,8 +31,8 @@ import java.util.Objects; import java.util.Optional; import org.onap.so.adapters.vnfmadapter.Constants; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProvider; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogUrlProvider; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.BasicAuth; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2002; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest; @@ -40,13 +40,12 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model. import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinksSelf; import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement.cache.PackageManagementCacheServiceProvider; import org.onap.so.adapters.vnfmadapter.rest.exceptions.InternalServerErrorException; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionRequestConversionException; -import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionNotFoundException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.ConversionFailedException; import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.convert.ConversionException; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Service; @@ -55,34 +54,26 @@ import org.springframework.stereotype.Service; * * @author Ronan Kenny (ronan.kenny@est.tech) * @author Gareth Roper (gareth.roper@est.tech) - * */ @Service public class SubscriptionManager { private static final Logger logger = getLogger(SubscriptionManager.class); private final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider; - private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; - private final HttpRestServiceProvider httpServiceProvider; private final ConversionService conversionService; private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; private final String vnfmAdapterEndpoint; private final String msoKeyString; private final String vnfmAdapterAuth; - @Autowired public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider, - final ConversionService conversionService, final HttpRestServiceProvider httpServiceProvider, - final EtsiCatalogUrlProvider etsiCatalogUrlProvider, - final EtsiCatalogServiceProvider etsiCatalogServiceProvider, + final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider, @Value("${vnfmadapter.endpoint}") final String vnfmAdapterEndpoint, @Value("${mso.key}") final String msoKeyString, - @Value("${vnfmadapter.auth:D6CFE56451508B75536C5E8A1E7AE06D0346006A693BF29293A6E1C762EFD59C671911DB6E9294E4FE15E4C1C5524B}") final String vnfmAdapterAuth) { + @Value("${vnfmadapter.auth:BF29BA36F0CFE1C05507781F6B97EFBCA7EFAC9F595954D465FC43F646883EF585C20A58CBB02528A6FAAC}") final String vnfmAdapterAuth) { this.packageManagementCacheServiceProvider = packageManagementCacheServiceProvider; - this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; this.conversionService = conversionService; - this.httpServiceProvider = httpServiceProvider; this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; this.vnfmAdapterEndpoint = vnfmAdapterEndpoint; this.vnfmAdapterAuth = vnfmAdapterAuth; @@ -99,10 +90,10 @@ public class SubscriptionManager { etsiCatalogServiceProvider.postSubscription(etsiCatalogManagerSubscriptionRequest); if (optionalEtsiCatalogManagerSubscription.isPresent()) { - PkgmSubscription etsiCatalogManagerSubscription = optionalEtsiCatalogManagerSubscription.get(); + final PkgmSubscription etsiCatalogManagerSubscription = optionalEtsiCatalogManagerSubscription.get(); logger.debug("postPkgmSubscriptionRequest Response SubscriptionId: {}", - Objects.requireNonNull(etsiCatalogManagerSubscription.getId().toString())); - final String subscriptionId = etsiCatalogManagerSubscription.getId().toString(); + Objects.requireNonNull(etsiCatalogManagerSubscription.getId())); + final String subscriptionId = etsiCatalogManagerSubscription.getId(); packageManagementCacheServiceProvider.addSubscription(subscriptionId, pkgmSubscriptionRequest); @@ -119,13 +110,24 @@ public class SubscriptionManager { "Received empty response from POST to ETSI Catalog Manager Subscription Endpoint."); } - - public Optional<String> getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) { return packageManagementCacheServiceProvider.getSubscriptionId(pkgmSubscriptionRequest); } public Optional<InlineResponse2002> getSubscription(final String subscriptionId) { + + logger.debug("Checking if subscrition with id: {} exists in ETSI Catalog Manager", subscriptionId); + final Optional<NsdmSubscription> etsiCatalogSubscriptionOption = + etsiCatalogServiceProvider.getSubscription(subscriptionId); + + if (!etsiCatalogSubscriptionOption.isPresent()) { + logger.debug("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId); + if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) { + logger.debug("will remove subcription with id: {} from local cache", subscriptionId); + packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); + } + } + final Optional<PkgmSubscriptionRequest> optional = packageManagementCacheServiceProvider.getSubscription(subscriptionId); if (optional.isPresent()) { @@ -139,32 +141,57 @@ public class SubscriptionManager { final Map<String, PkgmSubscriptionRequest> subscriptions = packageManagementCacheServiceProvider.getSubscriptions(); final List<InlineResponse2002> response = new ArrayList<>(); - subscriptions.forEach((key, value) -> response.add(getInlineResponse2002(key, value))); + subscriptions.forEach((key, value) -> { + final Optional<InlineResponse2002> optional = getSubscription(key); + if (optional.isPresent()) { + response.add(optional.get()); + } + }); return response; } + public boolean deleteSubscription(final String subscriptionId) { + if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) { + try { + if (etsiCatalogServiceProvider.deleteSubscription(subscriptionId)) { + return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); + } + } catch (final SubscriptionNotFoundException subscriptionNotFoundException) { + logger.error( + "Unable to find subscription in ETSI Catalog Manager using id: {} will delete it from local cache", + subscriptionId); + return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId); + } + } + return false; + } + public URI getSubscriptionUri(final String subscriptionId) { return URI.create( vnfmAdapterEndpoint + Constants.PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions/" + subscriptionId); } + public Optional<PkgmSubscriptionRequest> getSubscriptionRequest(final String subscriptionId) { + return packageManagementCacheServiceProvider.getSubscription(subscriptionId); + } + private InlineResponse2002 getInlineResponse2002(final String id, final PkgmSubscriptionRequest subscription) { return new InlineResponse2002().id(id).filter(subscription.getFilter()) .callbackUri(subscription.getCallbackUri()); } private org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest buildEtsiCatalogManagerPkgmSubscriptionRequest( - PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException { final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest; try { etsiCatalogManagerSubscriptionRequest = conversionService.convert(pkgmSubscriptionRequest, org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest.class); - } catch (ConversionException conversionException) { + } catch (final org.springframework.core.convert.ConversionException conversionException) { logger.error(conversionException.getMessage()); - throw new SubscriptionRequestConversionException( + throw new ConversionFailedException( "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); - } catch (Exception exception) { + } catch (final Exception exception) { logger.error(exception.getMessage()); throw new InternalServerErrorException( "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); @@ -183,7 +210,7 @@ public class SubscriptionManager { .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(username).password(password))); return etsiCatalogManagerSubscriptionRequest; } - throw new SubscriptionRequestConversionException( + throw new ConversionFailedException( "Failed to convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java new file mode 100644 index 0000000000..c9babbd345 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/TlsNotificationServiceProvider.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication.AuthTypeEnum; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.AuthenticationTypeNotSupportedException; +import org.slf4j.Logger; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@Service +public class TlsNotificationServiceProvider extends AbstractNotificationServiceProvider + implements NotificationServiceProvider { + + private static final Logger logger = getLogger(TlsNotificationServiceProvider.class); + + @Override + public boolean send(final Object notification, final SubscriptionsAuthentication subscriptionsAuthentication, + final String callbackUri) { + final String errorMessage = "An error occurred. Authentication type " + + subscriptionsAuthentication.getAuthType().toString() + " not currently supported."; + logger.error(errorMessage); + throw new AuthenticationTypeNotSupportedException(errorMessage); + } + + + @Override + public AuthTypeEnum getAuthType() { + return AuthTypeEnum.TLS_CERT; + } + + + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java index 6042513a50..437d20e593 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/cache/PackageManagementCacheServiceProvider.java @@ -60,7 +60,7 @@ public interface PackageManagementCacheServiceProvider { * Delete subscription from cache * * @param subscriptionId - * @return true if subscription exists and able to be removed, otherwise returns false + * @return Boolean */ boolean deleteSubscription(final String subscriptionId); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationController.java index c5bd5bc14e..a97f04bcc8 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationController.java @@ -22,30 +22,110 @@ package org.onap.so.adapters.vnfmadapter.rest; import static org.onap.so.adapters.vnfmadapter.Constants.ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL; import static org.slf4j.LoggerFactory.getLogger; +import java.util.AbstractMap; +import java.util.Map.Entry; import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement.NotificationManager; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.InternalServerErrorException; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.NotificationTypeNotSupportedException; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; /** * This controller handles the ETSI Subscription Notification Endpoints. * * @author Ronan Kenny (ronan.kenny@est.tech) * @author Gareth Roper (gareth.roper@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) */ @Controller -@RequestMapping(value = ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL, - produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, - consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +@RequestMapping(value = ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL) public class EtsiSubscriptionNotificationController { private static final Logger logger = getLogger(EtsiSubscriptionNotificationController.class); + private final NotificationManager notificationManager; + private final Gson gson; + + @Autowired + public EtsiSubscriptionNotificationController(final NotificationManager notificationManager) { + this.notificationManager = notificationManager; + this.gson = new GsonBuilder().create(); + } @GetMapping(value = "/notification") public ResponseEntity<Void> testSubscriptionNotificationEndPoint() { logger.debug("Testing Notification Endpoint"); return ResponseEntity.noContent().build(); } + + /** + * POST notification on to subscriber. + * + * @param notification The notification to send. + * @return Response Code: 204 No Content if Successful, ProblemDetails Object if not. + */ + @PostMapping(value = "/notification", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON) + public ResponseEntity<?> postSubscriptionNotification(@RequestBody final String notification) { + logger.info("Posting subscription notification \n{}", notification); + + final Entry<String, Object> notificationObject = getNotificationObject(notification); + if (notificationManager.processSubscriptionNotification(notificationObject.getValue(), + notificationObject.getKey())) { + logger.info("Notification Delivered Successfully"); + return ResponseEntity.noContent().build(); + } + final String errorMessage = "An error occurred. Sending of notification to VNFM failed."; + logger.error(errorMessage); + throw new InternalServerErrorException(errorMessage); + } + + private Entry<String, Object> getNotificationObject(final String notification) { + final String notificationType = getNotificationType(notification); + if (PkgOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION.getValue() + .equals(notificationType)) { + final PkgOnboardingNotification pkgOnboardingNotification = + gson.fromJson(notification, PkgOnboardingNotification.class); + logger.info("Onboarding notification received:\n{}", pkgOnboardingNotification); + return new AbstractMap.SimpleEntry<>(pkgOnboardingNotification.getSubscriptionId(), + pkgOnboardingNotification); + } + if (PkgChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue() + .equals(notificationType)) { + final PkgChangeNotification pkgChangeNotification = + gson.fromJson(notification, PkgChangeNotification.class); + logger.info("Change notification received:\n{}", pkgChangeNotification); + return new AbstractMap.SimpleEntry<>(pkgChangeNotification.getSubscriptionId(), pkgChangeNotification); + + } + + final String errorMessage = "An error occurred. Notification type not supported for: " + notificationType; + logger.error(errorMessage); + throw new NotificationTypeNotSupportedException(errorMessage); + + } + + private String getNotificationType(final String notification) { + try { + final JsonParser parser = new JsonParser(); + final JsonObject element = (JsonObject) parser.parse(notification); + return element.get("notificationType").getAsString(); + } catch (final Exception e) { + logger.error("An error occurred processing notificiation: {}", e.getMessage()); + } + throw new NotificationTypeNotSupportedException( + "Unable to parse notification type in object \n" + notification); + } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java index 3ead98fce2..21b20b0134 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003GrantController.java @@ -50,8 +50,6 @@ import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value = BASE_URL, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON) public class Sol003GrantController { - private static final String SEPARATOR = "_"; - private static final String VIM_TYPE = "OPENSTACK"; private static final Logger logger = LoggerFactory.getLogger(Sol003GrantController.class); public final AaiServiceProvider aaiServiceProvider; public final AaiHelper aaiHelper; diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java index cce7241757..f1d20c65ef 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java @@ -109,19 +109,19 @@ public class Sol003PackageManagementController { */ @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP, MediaType.APPLICATION_JSON}) - public ResponseEntity<byte[]> getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { + public ResponseEntity<?> getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd Endpoint Invoked with VNF Package ID: ", vnfPkgId); final Optional<byte[]> response = etsiCatalogServiceProvider.getVnfPackageVnfd(vnfPkgId); if (response.isPresent()) { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd Response: ", HttpStatus.OK); - return new ResponseEntity(response.get(), HttpStatus.OK); + return new ResponseEntity<>(response.get(), HttpStatus.OK); } final String errorMessage = "An error occurred, a null response was received by the\n" + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnfd\" \n" + "endpoint."; logger.error(errorMessage); - return new ResponseEntity(new ProblemDetails().detail(errorMessage), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new ProblemDetails().detail(errorMessage), HttpStatus.INTERNAL_SERVER_ERROR); } /** diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionController.java index cbad564210..6db3797f9b 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionController.java @@ -23,14 +23,13 @@ package org.onap.so.adapters.vnfmadapter.rest; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; import static org.slf4j.LoggerFactory.getLogger; import java.net.URI; -import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.util.List; import java.util.Optional; import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2002; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement.SubscriptionManager; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -38,6 +37,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -79,7 +79,7 @@ public class Sol003PackageManagementSubscriptionController { @PostMapping(value = "/subscriptions") public ResponseEntity<?> postSubscriptionRequest(@RequestBody final PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException { - logger.info(LOG_REQUEST_RECEIVED, " postSubscriptionRequest Endpoint Called"); + logger.info(LOG_REQUEST_RECEIVED, " postSubscriptionRequest Endpoint Called", pkgmSubscriptionRequest); // Check if subscription exists already. final Optional<String> exists = subscriptionManager.getSubscriptionId(pkgmSubscriptionRequest); @@ -140,6 +140,24 @@ public class Sol003PackageManagementSubscriptionController { } /** + * DELETE a specific subscription, by subscriptionId. Section Number: 10.4.8.3.5 + * + * @param subscriptionId The ID of the subscription that you wish to delete. + * @return Empty response if successful. Object: Void Response Code: 204 No Content + */ + @DeleteMapping(value = "/subscriptions/{subscriptionId}") + public ResponseEntity<?> deleteSubscription(@PathVariable("subscriptionId") final String subscriptionId) { + if (subscriptionManager.deleteSubscription(subscriptionId)) { + logger.debug("Successfully deleted subscription with id {}", subscriptionId); + return ResponseEntity.noContent().build(); + } + final String errorMessage = + "The requested subscription: " + subscriptionId + " was not found on call deleteSubscription"; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ProblemDetails().detail(errorMessage)); + } + + /** * Method to set the Location in the header with the URI parameter * * @param subscriptionUri diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/AuthenticationTypeNotSupportedException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/AuthenticationTypeNotSupportedException.java new file mode 100644 index 0000000000..303420f1e8 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/AuthenticationTypeNotSupportedException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an unsupported authentication type + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class AuthenticationTypeNotSupportedException extends RuntimeException { + + private static final long serialVersionUID = 2939423208362066902L; + + public AuthenticationTypeNotSupportedException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/SubscriptionRequestConversionException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/ConversionFailedException.java index daa544f928..e19a53d1dc 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/SubscriptionRequestConversionException.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/ConversionFailedException.java @@ -23,16 +23,17 @@ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** - * Exception for an ETSI Catalog Manager Request Failure + * Exception for Conversion Failures * - * @author gareth.roper@est.tech + * @author Gareth Roper (gareth.roper@est.tech) + * @author Andrew Lamb (andrew.a.lamb@est.tech) */ @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) -public class SubscriptionRequestConversionException extends RuntimeException { +public class ConversionFailedException extends RuntimeException { private static final long serialVersionUID = 45898561453196895L; - public SubscriptionRequestConversionException(final String message) { + public ConversionFailedException(final String message) { super(message); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java new file mode 100644 index 0000000000..e8e1ce35b9 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiSubscriptionNotificationControllerExceptionHandler.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import static org.slf4j.LoggerFactory.getLogger; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.vnfmadapter.rest.EtsiSubscriptionNotificationController; +import org.onap.so.rest.exceptions.HttpResouceNotFoundException; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.slf4j.Logger; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** + * Exception Handler for the Etsi Subscription Notification Controller {@link EtsiSubscriptionNotificationController + * EtsiSubscriptionNotificationController} + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ControllerAdvice(assignableTypes = EtsiSubscriptionNotificationController.class) +public class EtsiSubscriptionNotificationControllerExceptionHandler { + + private static final Logger logger = getLogger(EtsiSubscriptionNotificationControllerExceptionHandler.class); + + @ExceptionHandler(InvalidRestRequestException.class) + public ResponseEntity<ProblemDetails> handleInvalidRestRequestException( + final InvalidRestRequestException invalidRestRequestException) { + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.BAD_REQUEST + ".\n" + invalidRestRequestException.getMessage(); + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + @ExceptionHandler(HttpResouceNotFoundException.class) + public ResponseEntity<ProblemDetails> handleHttpResourceNotFoundException( + final HttpResouceNotFoundException httpResourceNotFoundException) { + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.NOT_FOUND + ".\n" + httpResourceNotFoundException.getMessage(); + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + @ExceptionHandler(RestProcessingException.class) + public ResponseEntity<ProblemDetails> handleRestProcessingException( + final RestProcessingException restProcessingException) { + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + restProcessingException.getStatusCode() + ".\n" + restProcessingException.getMessage(); + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); + } + + @ExceptionHandler(InternalServerErrorException.class) + public ResponseEntity<ProblemDetails> handleInternalServerErrorException( + final InternalServerErrorException internalServerErrorException) { + logger.error(internalServerErrorException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(internalServerErrorException.getMessage())); + } + + @ExceptionHandler(AuthenticationTypeNotSupportedException.class) + public ResponseEntity<ProblemDetails> handleAuthenticationTypeNotSupportedException( + final AuthenticationTypeNotSupportedException authenticationTypeNotSupportedException) { + logger.error(authenticationTypeNotSupportedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(authenticationTypeNotSupportedException.getMessage())); + } + + @ExceptionHandler(ConversionFailedException.class) + public ResponseEntity<ProblemDetails> handleConversionFailedException( + final ConversionFailedException conversionFailedException) { + logger.error(conversionFailedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(conversionFailedException.getMessage())); + } + + @ExceptionHandler(NotificationTypeNotSupportedException.class) + public ResponseEntity<ProblemDetails> handleNotificationTypeNotSupportedException( + final NotificationTypeNotSupportedException notificationTypeNotSupportedException) { + logger.error(notificationTypeNotSupportedException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(notificationTypeNotSupportedException.getMessage())); + } + + @ExceptionHandler(SubscriptionNotFoundException.class) + public ResponseEntity<ProblemDetails> handleSubscriptionNotFoundException( + final SubscriptionNotFoundException subscriptionNotFoundException) { + logger.error(subscriptionNotFoundException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(new ProblemDetails().detail(subscriptionNotFoundException.getMessage())); + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/NotificationTypeNotSupportedException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/NotificationTypeNotSupportedException.java new file mode 100644 index 0000000000..dcc98864aa --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/NotificationTypeNotSupportedException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an unsupported notification type + * + * @author Andrew Lamb (andrew.a.lamb@est.tech) + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class NotificationTypeNotSupportedException extends RuntimeException { + + private static final long serialVersionUID = 2939423208362066902L; + + public NotificationTypeNotSupportedException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java index da8b0cbff2..8091f35da6 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java @@ -22,10 +22,6 @@ package org.onap.so.adapters.vnfmadapter.rest.exceptions; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; import org.onap.so.adapters.vnfmadapter.rest.Sol003PackageManagementController; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.EtsiCatalogManagerRequestFailureException; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgBadRequestException; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgConflictException; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfPkgNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; @@ -64,11 +60,11 @@ public class Sol003PackageManagementControllerExceptionHandler { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); } - @ExceptionHandler(SubscriptionRequestConversionException.class) - public ResponseEntity<ProblemDetails> handleSubscriptionRequestConversionException( - final SubscriptionRequestConversionException subscriptionRequestConversionException) { + @ExceptionHandler(ConversionFailedException.class) + public ResponseEntity<ProblemDetails> handleConversionFailedException( + final ConversionFailedException conversionFailedException) { final ProblemDetails problemDetails = new ProblemDetails(); - problemDetails.setDetail(subscriptionRequestConversionException.getMessage()); + problemDetails.setDetail(conversionFailedException.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java new file mode 100644 index 0000000000..322251e753 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java @@ -0,0 +1,595 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onap.so.adapters.vnfmadapter.Constants.ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.adapters.vnfmadapter.Constants; +import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.NOTIFICATIONLINKSERIALIZER; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgChangeNotification; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgOnboardingNotification; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model.PkgmLinks; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthentication; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthenticationParamsBasic; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsAuthenticationParamsOauth2ClientCredentials; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.VnfPackageChangeNotification; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.notification.model.VnfPackageOnboardingNotification; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.http.*; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; +import org.threeten.bp.LocalDateTime; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneOffset; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +/** + * @author Andrew Lamb (andrew.a.lamb@est.tech) + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +@DirtiesContext(classMode = BEFORE_CLASS) +public class EtsiSubscriptionNotificationControllerTest { + + @LocalServerPort + private int port; + + private static final URI CALLBACK_URI = URI.create("http://test_callback_uri/notification"); + private static final String TOKEN_ENDPOINT = "http://test_token_endpoint_uri/"; + private static final String TOKEN = "dXNlcm5hbWU6cGFzc3dvcmQ=......"; + private static final String JSON_TOKEN = "{\"access_token\":\"" + TOKEN + "\"}"; + private static final String LOCALHOST_URL = "http://localhost:"; + private static final String NOTIFICATION_BASE_URL = + ETSI_SUBSCRIPTION_NOTIFICATION_CONTROLLER_BASE_URL + "/notification"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String EXPECTED_BASIC_AUTHORIZATION = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; + private static final String EXPECTED_OAUTH_AUTHORIZATION = "Bearer " + TOKEN; + private static final String NOTIFICATION_ID = "NOTIFICATION_ID"; + private static final String SUBSCRIPTION_ID = "SUBSCRIPTION_ID"; + private static final OffsetDateTime TIMESTAMP = + OffsetDateTime.of(LocalDateTime.of(2020, 1, 1, 1, 1, 1, 1), ZoneOffset.ofHours(1)); + private static final String VNFPKG_ID = UUID.randomUUID().toString(); + private static final String VNFD_ID = UUID.randomUUID().toString(); + + private BasicHttpHeadersProvider basicHttpHeadersProvider; + private final Gson gson = new GsonBuilder().create();; + + @Autowired + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate restTemplate; + private MockRestServiceServer mockRestServer; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Autowired + private CacheManager cacheServiceProvider; + private Cache cache; + + @Before + public void setUp() { + mockRestServer = MockRestServiceServer.bindTo(restTemplate).build(); + basicHttpHeadersProvider = new BasicHttpHeadersProvider(); + cache = cacheServiceProvider.getCache(Constants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); + cache.clear(); + } + + @After + public void tearDown() { + cache.clear(); + } + + @Test + public void testSubscriptionNotificationEndPoint_ReturnsNoContent() { + final ResponseEntity<?> response = sendHttpGet(NOTIFICATION_BASE_URL); + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_SubscriptionRequestInCache_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType") + .value(VnfPackageOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION + .toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIMESTAMP.toString())) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID.toString())) + .andExpect(jsonPath("$.vnfdId").value(VNFD_ID.toString())) + .andExpect(jsonPath("$._links").value(buildPkgmLinks())) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testOnboardingNotificationNotSentOnToVnfmCallbackUri_SubscriptionRequestNotInCache_Fail() { + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "No subscription found with subscriptionId " + SUBSCRIPTION_ID + + ". Unable to forward notification to subscriber."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_BadRequestResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.BAD_REQUEST + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_301MovedPermanentlyResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.MOVED_PERMANENTLY)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_NotFoundResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.NOT_FOUND + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testOnboardingNotificationSentOnToVnfmCallbackUri_InternalServerErrorResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.INTERNAL_SERVER_ERROR.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_SubscriptionRequestInCache_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType").value( + VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIMESTAMP.toString())) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID.toString())) + .andExpect(jsonPath("$.vnfdId").value(VNFD_ID.toString())) + .andExpect( + jsonPath("$.changeType").value(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE.toString())) + .andExpect(jsonPath("$.operationalState") + .value(PkgChangeNotification.OperationalStateEnum.ENABLED.toString())) + .andExpect(jsonPath("$._links").value(buildPkgmLinks())) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testChangeNotificationNotSentOnToVnfmCallbackUri_SubscriptionRequestNotInCache_Fail() { + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "No subscription found with subscriptionId " + SUBSCRIPTION_ID + + ". Unable to forward notification to subscriber."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_BadRequestResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.BAD_REQUEST + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_NotFoundResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.NOT_FOUND + ".\n" + "No result found for given url: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testChangeNotificationSentOnToVnfmCallbackUri_InternalServerErrorResponseFromCallbackUri_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.INTERNAL_SERVER_ERROR.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testNotificationSentOnToVnfm_BasicAuthUserPasswordAuthorized_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgOnboardingNotification notification = buildPkgOnboardingNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType") + .value(VnfPackageOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION + .toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIMESTAMP.toString())) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID.toString())) + .andExpect(jsonPath("$.vnfdId").value(VNFD_ID.toString())) + .andExpect(jsonPath("$._links").value(buildPkgmLinks())) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testNotificationSentOnToVnfm_BasicAuthUserPasswordNotAuthorized_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.BASIC); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)) + .andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Sending of notification to VNFM failed with response: " + + HttpStatus.UNAUTHORIZED.value() + ".\n" + "Unable to invoke HTTP POST using URL: " + CALLBACK_URI; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testNotificationSentOnToVnfm_OAuthAuthorized_Success() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(TOKEN_ENDPOINT)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)) + .andRespond(withSuccess(JSON_TOKEN, MediaType.APPLICATION_JSON)); + + mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_OAUTH_AUTHORIZATION)) + .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) + .andExpect(jsonPath("$.notificationType").value( + VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.toString())) + .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) + .andExpect(jsonPath("$.timeStamp").value(TIMESTAMP.toString())) + .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID.toString())) + .andExpect(jsonPath("$.vnfdId").value(VNFD_ID.toString())) + .andExpect( + jsonPath("$.changeType").value(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE.toString())) + .andExpect(jsonPath("$.operationalState") + .value(PkgChangeNotification.OperationalStateEnum.ENABLED.toString())) + .andExpect(jsonPath("$._links").value(buildPkgmLinks())).andRespond(withSuccess()); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + } + + @Test + public void testNotificationSentOnToVnfm_OAuthTokenNotReceived_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + mockRestServer.expect(requestTo(TOKEN_ENDPOINT)).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", EXPECTED_BASIC_AUTHORIZATION)).andRespond(withSuccess()); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Unable to retrieve OAuth Token from VNFM for notification."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + @Test + public void testNotificationSentOnToVnfm_TLSCertNotYetSupported_Fail() { + final PkgmSubscriptionRequest subscriptionRequest = + buildPkgmSubscriptionRequest(SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT); + cache.put(SUBSCRIPTION_ID, subscriptionRequest); + final PkgChangeNotification notification = buildPkgChangeNotification(); + final String notificationString = gson.toJson(notification); + + final ResponseEntity<?> response = sendHttpPost(notificationString); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertTrue(response.getBody() instanceof ProblemDetails); + + final ProblemDetails problemDetails = (ProblemDetails) response.getBody(); + final String errorMessage = "An error occurred. Authentication type " + + subscriptionRequest.getAuthentication().getAuthType().toString() + " not currently supported."; + + assertEquals(errorMessage, problemDetails.getDetail()); + } + + private PkgOnboardingNotification buildPkgOnboardingNotification() { + final PkgOnboardingNotification notification = new PkgOnboardingNotification(); + notification.setId(NOTIFICATION_ID); + notification + .setNotificationType(PkgOnboardingNotification.NotificationTypeEnum.VNFPACKAGEONBOARDINGNOTIFICATION); + notification.setSubscriptionId(SUBSCRIPTION_ID); + notification.setTimeStamp(TIMESTAMP); + notification.setVnfPkgId(VNFPKG_ID); + notification.setVnfdId(VNFD_ID); + notification.setLinks(buildPkgmLinks()); + return notification; + } + + private PkgChangeNotification buildPkgChangeNotification() { + final PkgChangeNotification notification = new PkgChangeNotification(); + notification.setId(NOTIFICATION_ID); + notification.setNotificationType(PkgChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION); + notification.setSubscriptionId(SUBSCRIPTION_ID); + notification.setTimeStamp(TIMESTAMP); + notification.setVnfPkgId(VNFPKG_ID); + notification.setVnfdId(VNFD_ID); + notification.setChangeType(PkgChangeNotification.ChangeTypeEnum.OP_STATE_CHANGE); + notification.setOperationalState(PkgChangeNotification.OperationalStateEnum.ENABLED); + notification.setLinks(buildPkgmLinks()); + return notification; + } + + private PkgmLinks buildPkgmLinks() { + final PkgmLinks pkgmLinks = new PkgmLinks(); + + final NOTIFICATIONLINKSERIALIZER subscriptionLinkSerializer = new NOTIFICATIONLINKSERIALIZER(); + subscriptionLinkSerializer.setHref("subscription_href"); + pkgmLinks.setSubscription(subscriptionLinkSerializer); + + final NOTIFICATIONLINKSERIALIZER vnfPackageLinkSerializer = new NOTIFICATIONLINKSERIALIZER(); + vnfPackageLinkSerializer.setHref("vnf_package_href"); + pkgmLinks.setVnfPackage(vnfPackageLinkSerializer); + + return pkgmLinks; + } + + private PkgmSubscriptionRequest buildPkgmSubscriptionRequest( + final SubscriptionsAuthentication.AuthTypeEnum authTypeEnum) { + final PkgmSubscriptionRequest subscriptionRequest = new PkgmSubscriptionRequest(); + subscriptionRequest.setCallbackUri(CALLBACK_URI.toString()); + subscriptionRequest.setAuthentication(buildSubscriptionsAuthentication(authTypeEnum)); + return subscriptionRequest; + } + + // TODO update for auth types other than basicAuth + private SubscriptionsAuthentication buildSubscriptionsAuthentication( + final SubscriptionsAuthentication.AuthTypeEnum authTypeEnum) { + final SubscriptionsAuthentication subscriptionsAuthentication = new SubscriptionsAuthentication(); + final List<SubscriptionsAuthentication.AuthTypeEnum> authTypes = new ArrayList<>(); + authTypes.add(authTypeEnum); + subscriptionsAuthentication.setAuthType(authTypes); + if (authTypeEnum == SubscriptionsAuthentication.AuthTypeEnum.TLS_CERT) { + // TODO: remove basic params and code for TLS + final SubscriptionsAuthenticationParamsBasic basicParams = + new SubscriptionsAuthenticationParamsBasic().userName(USERNAME).password(PASSWORD); + subscriptionsAuthentication.setParamsBasic(basicParams); + } else if (authTypeEnum == SubscriptionsAuthentication.AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS) { + final SubscriptionsAuthenticationParamsOauth2ClientCredentials oathParams = + new SubscriptionsAuthenticationParamsOauth2ClientCredentials().clientId(USERNAME) + .clientPassword(PASSWORD).tokenEndpoint(TOKEN_ENDPOINT); + subscriptionsAuthentication.setParamsOauth2ClientCredentials(oathParams); + } else { + final SubscriptionsAuthenticationParamsBasic basicParams = + new SubscriptionsAuthenticationParamsBasic().userName(USERNAME).password(PASSWORD); + subscriptionsAuthentication.setParamsBasic(basicParams); + } + + return subscriptionsAuthentication; + } + + private <T> ResponseEntity<ProblemDetails> sendHttpPost(final T notification) { + final String testURL = LOCALHOST_URL + port + NOTIFICATION_BASE_URL; + final HttpEntity<?> request = new HttpEntity<>(notification, basicHttpHeadersProvider.getHttpHeaders()); + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.POST, request, + ProblemDetails.class); + } + + private ResponseEntity<Void> sendHttpGet(final String url) { + final String testURL = LOCALHOST_URL + port + url; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, Void.class); + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java index f90978e0d5..ba1bf71936 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java @@ -20,27 +20,32 @@ package org.onap.so.adapters.vnfmadapter.rest; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import java.security.GeneralSecurityException; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; import java.net.URI; import java.net.URISyntaxException; +import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; -import com.google.gson.Gson; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.adapters.vnfmadapter.Constants; import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.LinkSelf; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmNotificationsFilter; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2002; @@ -51,13 +56,13 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model. import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsFilterVnfProductsFromProviders; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsLinks; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinksSelf; -import org.onap.so.utils.CryptoUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -65,41 +70,33 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; -import org.springframework.http.HttpMethod; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; -import static org.hamcrest.Matchers.is; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import com.google.gson.Gson; /** * @author Ronan Kenny (ronan.kenny@est.tech) * @author Gareth Roper (gareth.roper@est.tech) - * */ @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") -@SuppressWarnings("unchecked") public class Sol003PackageManagementSubscriptionControllerTest { - private static String subscriptionId; private final Gson gson = new Gson(); - + private final URI msbEndpoint = URI.create("http://msb-iag.onap:80/api/vnfpkgm/v1/subscriptions"); @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate testRestTemplate; - - private MockRestServiceServer mockRestServer; - + private RestTemplate restTemplate; + private MockRestServiceServer mockRestServiceServer; @Autowired private CacheManager cacheServiceProvider; - private final URI msbEndpoint = URI.create("http://msb-iag.onap:80/api/vnfpkgm/v1/subscriptions"); - @Autowired private Sol003PackageManagementSubscriptionController sol003PackageManagementSubscriptionController; + private static final String ID = UUID.randomUUID().toString(); + @Before public void setUp() { - mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); + mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build(); final Cache cache = cacheServiceProvider.getCache(Constants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); cache.clear(); } @@ -113,8 +110,8 @@ public class Sol003PackageManagementSubscriptionControllerTest { final HttpHeaders headers = buildHttpHeaders(Objects.requireNonNull(response.getBody()).getCallbackUri()); - SubscriptionsLinks subscriptionsLinks = new SubscriptionsLinks(); - VnfPackagesLinksSelf vnfPackagesLinksSelf = new VnfPackagesLinksSelf(); + final SubscriptionsLinks subscriptionsLinks = new SubscriptionsLinks(); + final VnfPackagesLinksSelf vnfPackagesLinksSelf = new VnfPackagesLinksSelf(); vnfPackagesLinksSelf.setHref("https://so-vnfm-adapter.onap:30406" + PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions/" + response.getBody().getId()); subscriptionsLinks.setSelf(vnfPackagesLinksSelf); @@ -134,7 +131,6 @@ public class Sol003PackageManagementSubscriptionControllerTest { final ResponseEntity<InlineResponse2002> response = (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController .postSubscriptionRequest(pkgmSubscriptionRequest); - subscriptionId = Objects.requireNonNull(response.getBody()).getId(); // Create duplicate entry final PkgmSubscriptionRequest pkgmSubscriptionRequest2 = buildPkgmSubscriptionRequest(); @@ -148,12 +144,18 @@ public class Sol003PackageManagementSubscriptionControllerTest { @Test public void testSuccessGetSubscriptionWithSubscriptionId() throws GeneralSecurityException, URISyntaxException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = postSubscriptionForTest(); + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(ID)), MediaType.APPLICATION_JSON)); + final ResponseEntity<InlineResponse2002> response = (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController .postSubscriptionRequest(pkgmSubscriptionRequest); - subscriptionId = Objects.requireNonNull(response.getBody()).getId(); + final String subscriptionId = response.getBody().getId(); + + final ResponseEntity<InlineResponse2002> response2002 = (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController @@ -161,9 +163,8 @@ public class Sol003PackageManagementSubscriptionControllerTest { final HttpHeaders headers = buildHttpHeaders(response.getBody().getCallbackUri()); - assertEquals(response.getBody().getFilter(), pkgmSubscriptionRequest.getFilter()); - assert (response.getHeaders().equals(headers)); + assertEquals(response.getHeaders(), headers); assertEquals(HttpStatus.OK, response2002.getStatusCode()); assertEquals(pkgmSubscriptionRequest.getFilter(), response.getBody().getFilter()); // Ensure CallBackUri is set to new URI @@ -172,9 +173,12 @@ public class Sol003PackageManagementSubscriptionControllerTest { @Test public void testFailGetSubscriptionWithInvalidSubscriptionId() { + final String invalidId = "invalidSubscriptionId"; + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + invalidId)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); final ResponseEntity<InlineResponse2002> response = (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController - .getSubscription("invalidSubscriptionId"); + .getSubscription(invalidId); assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); } @@ -183,14 +187,16 @@ public class Sol003PackageManagementSubscriptionControllerTest { final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); - mockRestServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(ID)), MediaType.APPLICATION_JSON)); sol003PackageManagementSubscriptionController.postSubscriptionRequest(pkgmSubscriptionRequest); - ResponseEntity<List<InlineResponse2002>> response = + final ResponseEntity<List<InlineResponse2002>> response = sol003PackageManagementSubscriptionController.getSubscriptions(); - List<InlineResponse2002> subscriptionsList = response.getBody(); + final List<InlineResponse2002> subscriptionsList = response.getBody(); assertEquals(Objects.requireNonNull(response.getBody()).get(0).getFilter(), pkgmSubscriptionRequest.getFilter()); @@ -199,6 +205,70 @@ public class Sol003PackageManagementSubscriptionControllerTest { assertEquals(HttpStatus.OK, response.getStatusCode()); } + @Test + public void testSuccessDeleteSubscriptionWithSubscriptionId() throws GeneralSecurityException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); + final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); + final String subscriptionId = pkgmSubscription.getId(); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + subscriptionId)).andExpect(method(HttpMethod.DELETE)) + .andRespond(withStatus(HttpStatus.NO_CONTENT)); + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + subscriptionId)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(new NsdmSubscription().id(subscriptionId)), + MediaType.APPLICATION_JSON)); + + final ResponseEntity<InlineResponse2002> responsePost = + (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + + final ResponseEntity responseDelete = + sol003PackageManagementSubscriptionController.deleteSubscription(subscriptionId); + + // Attempt to retrieve the subscription after delete + final ResponseEntity<InlineResponse2002> responseGetSubscription = + (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController + .getSubscription(subscriptionId); + + assertEquals(HttpStatus.NOT_FOUND, responseGetSubscription.getStatusCode()); + assertEquals(HttpStatus.NO_CONTENT, responseDelete.getStatusCode()); + } + + @Test + public void testDeleteSubscription_SubscripitonNotFoundInEtsiCatalogManager_SubscriptionDeletedFromLocalCache() + throws GeneralSecurityException { + final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); + final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); + + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); + + mockRestServiceServer.expect(requestTo(msbEndpoint + "/" + ID)).andExpect(method(HttpMethod.DELETE)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<InlineResponse2002> responsePost = + (ResponseEntity<InlineResponse2002>) sol003PackageManagementSubscriptionController + .postSubscriptionRequest(pkgmSubscriptionRequest); + + final Cache cache = cacheServiceProvider.getCache(Constants.PACKAGE_MANAGEMENT_SUBSCRIPTION_CACHE); + assertNotNull(cache.get(ID)); + + final ResponseEntity responseDelete = sol003PackageManagementSubscriptionController.deleteSubscription(ID); + + assertEquals(HttpStatus.NO_CONTENT, responseDelete.getStatusCode()); + assertNull(cache.get(ID)); + + } + + @Test + public void testFailDeleteSubscriptionWithInvalidSubscriptionId() throws URISyntaxException, InterruptedException { + final ResponseEntity<Void> responseDelete = (ResponseEntity<Void>) sol003PackageManagementSubscriptionController + .deleteSubscription("invalidSubscriptionId"); + assertEquals(HttpStatus.NOT_FOUND, responseDelete.getStatusCode()); + } + private PkgmSubscriptionRequest buildPkgmSubscriptionRequest() { final PkgmSubscriptionRequest pkgmSubscriptionRequest = new PkgmSubscriptionRequest(); final SubscriptionsFilter sub = buildSubscriptionsFilter(); @@ -227,11 +297,11 @@ public class Sol003PackageManagementSubscriptionControllerTest { } private PkgmSubscription buildPkgmSubscription() { - PkgmSubscription pkgmSubscription = new PkgmSubscription(); - PkgmNotificationsFilter pkgmNotificationsFilter = new PkgmNotificationsFilter(); - LinkSelf linkSelf = new LinkSelf(); - String id = UUID.randomUUID().toString(); - pkgmSubscription.setId(id); + final PkgmSubscription pkgmSubscription = new PkgmSubscription(); + final PkgmNotificationsFilter pkgmNotificationsFilter = new PkgmNotificationsFilter(); + final LinkSelf linkSelf = new LinkSelf(); + + pkgmSubscription.setId(ID); pkgmSubscription.setCallbackUri(msbEndpoint + "/" + pkgmSubscription.getId().toString()); pkgmSubscription.setFilter(pkgmNotificationsFilter); pkgmSubscription.setLinks(linkSelf); @@ -242,14 +312,14 @@ public class Sol003PackageManagementSubscriptionControllerTest { final PkgmSubscriptionRequest pkgmSubscriptionRequest = buildPkgmSubscriptionRequest(); final PkgmSubscription pkgmSubscription = buildPkgmSubscription(); - mockRestServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) + mockRestServiceServer.expect(requestTo(msbEndpoint)).andExpect(method(HttpMethod.POST)) .andRespond(withSuccess(gson.toJson(pkgmSubscription), MediaType.APPLICATION_JSON)); return pkgmSubscriptionRequest; } - private HttpHeaders buildHttpHeaders(String uri) throws URISyntaxException { + private HttpHeaders buildHttpHeaders(final String uri) throws URISyntaxException { final HttpHeaders headers = new HttpHeaders(); - URI myUri = new URI(uri); + final URI myUri = new URI(uri); headers.setLocation(myUri); return headers; } diff --git a/adapters/mso-vnfm-adapter/pom.xml b/adapters/mso-vnfm-adapter/pom.xml index 962b3b4fb7..3e295aa184 100644 --- a/adapters/mso-vnfm-adapter/pom.xml +++ b/adapters/mso-vnfm-adapter/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-vnfm-adapter</artifactId> diff --git a/adapters/pom.xml b/adapters/pom.xml index b96c3744c3..8acc7012ba 100644 --- a/adapters/pom.xml +++ b/adapters/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>adapters</artifactId> diff --git a/adapters/so-appc-orchestrator/pom.xml b/adapters/so-appc-orchestrator/pom.xml index 717bcee3fc..e8e5808eca 100644 --- a/adapters/so-appc-orchestrator/pom.xml +++ b/adapters/so-appc-orchestrator/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>adapters</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.adapters</groupId> |