diff options
218 files changed, 12714 insertions, 628 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-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java index 7f0f6e4a8b..4dc139f37d 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/NovaClientImpl.java @@ -26,14 +26,20 @@ import org.onap.so.openstack.exceptions.MsoException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.base.client.Entity; +import com.woorea.openstack.base.client.HttpMethod; import com.woorea.openstack.base.client.OpenStackRequest; import com.woorea.openstack.nova.Nova; import com.woorea.openstack.nova.model.Flavor; import com.woorea.openstack.nova.model.Flavors; import com.woorea.openstack.nova.model.HostAggregate; import com.woorea.openstack.nova.model.HostAggregates; +import com.woorea.openstack.nova.model.Hypervisors; import com.woorea.openstack.nova.model.QuotaSet; import com.woorea.openstack.nova.model.Server; +import com.woorea.openstack.nova.model.VolumeAttachment; @Component @@ -216,4 +222,61 @@ public class NovaClientImpl extends MsoCommonUtils { throw new NovaClientException("Error building Nova Client", e); } } + + public void postActionToServer(String cloudSiteId, String tenantId, String id, String request) + throws NovaClientException { + try { + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(request); + Entity<JsonNode> openstackEntity = new Entity<>(actualObj, "application/json"); + CharSequence actionPath = "/servers/" + id + "/action"; + Nova novaClient = getNovaClient(cloudSiteId, tenantId); + OpenStackRequest<Void> OSRequest = + new OpenStackRequest<>(novaClient, HttpMethod.POST, actionPath, openstackEntity, Void.class); + executeAndRecordOpenstackRequest(OSRequest, false); + } catch (Exception e) { + logger.error("Error building Nova Client", e); + throw new NovaClientException("Error building Nova Client", e); + } + } + + public void attachVolume(String cloudSiteId, String tenantId, String serverId, VolumeAttachment volumeAttachment) + throws NovaClientException { + Nova novaClient; + try { + novaClient = getNovaClient(cloudSiteId, tenantId); + OpenStackRequest<Void> request = novaClient.servers().attachVolume(serverId, volumeAttachment.getVolumeId(), + volumeAttachment.getDevice()); + executeAndRecordOpenstackRequest(request, false); + } catch (MsoException e) { + logger.error("Error building Nova Client", e); + throw new NovaClientException("Error building Nova Client", e); + } + } + + public void detachVolume(String cloudSiteId, String tenantId, String serverId, String volumeId) + throws NovaClientException { + Nova novaClient; + try { + novaClient = getNovaClient(cloudSiteId, tenantId); + OpenStackRequest<Void> request = novaClient.servers().detachVolume(serverId, volumeId); + executeAndRecordOpenstackRequest(request, false); + } catch (MsoException e) { + logger.error("Error building Nova Client", e); + throw new NovaClientException("Error building Nova Client", e); + } + } + + public Hypervisors getHypervisorDetails(String cloudSiteId, String tenantId) throws NovaClientException { + Nova novaClient; + try { + novaClient = getNovaClient(cloudSiteId, tenantId); + OpenStackRequest<Hypervisors> request = novaClient.hypervisors().listDetail(); + return executeAndRecordOpenstackRequest(request, false); + } catch (MsoException e) { + logger.error("Error building Nova Client", e); + throw new NovaClientException("Error building Nova Client", e); + } + } + } 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/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceArtifact.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceArtifact.java new file mode 100644 index 0000000000..ce39b9713a --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceArtifact.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019, CMCC Technologies Co., Ltd. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.catalogdb.catalogrest; + +import org.onap.so.db.catalog.beans.ServiceArtifact; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@XmlRootElement(name = "serviceArtifacts") +public class QueryServiceArtifact extends CatalogQuery { + + protected static Logger logger = LoggerFactory.getLogger(QueryServiceArtifact.class); + + private List<ServiceArtifact> serviceArtifactList; + + private static final String TEMPLATE = "\t{\n" + "\t\t\"artifactUUID\" : <ARTIFACT_UUID>,\n" + + "\t\t\"name\" : <NAME>,\n" + "\t\t\"version\" : <VERSION>,\n" + + "\t\t\"checksum\" : <CHECKSUM>,\n" + "\t\t\"type\" : <TYPE>,\n" + + "\t\t\"content\" : <CONTENT>,\n" + "\t\t\"description\" : <DESCRIPTION>\n" + "\t}"; + + public QueryServiceArtifact() { + super(); + serviceArtifactList = new ArrayList<>(); + } + + public QueryServiceArtifact(List<ServiceArtifact> alist) { + serviceArtifactList = new ArrayList<>(); + for (ServiceArtifact o : alist) { + if (logger.isDebugEnabled()) + logger.debug(o.toString()); + serviceArtifactList.add(o); + } + } + + public List<ServiceArtifact> getServiceArtifact() { + return this.serviceArtifactList; + } + + public void setServiceArtifact(List<ServiceArtifact> a) { + this.serviceArtifactList = a; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + boolean first = true; + int i = 1; + for (ServiceArtifact o : serviceArtifactList) { + sb.append(i).append("\t"); + if (!first) + sb.append("\n"); + first = false; + sb.append(o); + } + return sb.toString(); + } + + @Override + public String JSON2(boolean isArray, boolean isEmbed) { + StringBuilder sb = new StringBuilder(); + if (!isEmbed && isArray) + sb.append("{ "); + if (isArray) + sb.append("\"serviceArtifact\": ["); + Map<String, String> valueMap = new HashMap<>(); + String sep = ""; + boolean first = true; + + for (ServiceArtifact o : serviceArtifactList) { + if (first) + sb.append("\n"); + first = false; + + boolean vrNull = o == null; + + put(valueMap, "ARTIFACT_UUID", vrNull ? null : o.getArtifactUUID()); + put(valueMap, "TYPE", vrNull ? null : o.getType()); + put(valueMap, "NAME", vrNull ? null : o.getName()); + put(valueMap, "VERSION", vrNull ? null : o.getVersion()); + put(valueMap, "DESCRIPTION", vrNull ? null : o.getDescription()); + put(valueMap, "CONTENT", vrNull ? null : o.getContent()); + put(valueMap, "CHECKSUM", vrNull ? null : o.getChecksum()); + sb.append(sep).append(this.setTemplate(TEMPLATE, valueMap)); + sep = ",\n"; + } + if (!first) + sb.append("\n"); + if (isArray) + sb.append("]"); + if (!isEmbed && isArray) + sb.append("}"); + return sb.toString(); + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java new file mode 100644 index 0000000000..b1911654c4 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019, CMCC Technologies Co., Ltd. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.catalogdb.catalogrest; + +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.catalog.beans.ServiceInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.HashMap; +import java.util.Map; + +@XmlRootElement(name = "serviceInfo") +public class QueryServiceInfo extends CatalogQuery { + + protected static Logger logger = LoggerFactory.getLogger(QueryServiceInfo.class); + + private ServiceInfo serviceInfo; + + private static final String TEMPLATE = + "\n" + "\t{" + "\t\t\"id\" : <ID>,\n" + "\t\t\"serviceInput\" : <SERVICE_INPUT>,\n" + + "\t\"serviceProperties\" : <SERVICE_PROPERTIES>,\n" + "<_SERVICEARTIFACT_>\n"; + + + public QueryServiceInfo() { + super(); + this.serviceInfo = new ServiceInfo(); + } + + public QueryServiceInfo(ServiceInfo serviceInfo) { + this.serviceInfo = serviceInfo; + } + + public ServiceInfo getServiceInfo() { + return this.serviceInfo; + } + + public void setServiceInfo(ServiceInfo serviceInfo) { + this.serviceInfo = serviceInfo; + } + + @Override + public String toString() { + + return serviceInfo.toString(); + } + + @Override + public String JSON2(boolean isArray, boolean isEmbed) { + StringBuilder sb = new StringBuilder(); + sb.append("\"serviceInfo\": "); + sb.append("\n"); + Map<String, String> valueMap = new HashMap<>(); + Service service = serviceInfo.getService(); + put(valueMap, "ID", null == serviceInfo ? null : serviceInfo.getId()); + put(valueMap, "SERVICE_INPUT", null == serviceInfo ? null : serviceInfo.getServiceInput()); + put(valueMap, "SERVICE_PROPERTIES", null == serviceInfo ? null : serviceInfo.getServiceProperties()); + // String subitem = new QueryServiceArtifact(service.getServiceArtifactList()).JSON2(true, true); + // valueMap.put("_SERVICEARTIFACT_", subitem.replaceAll("(?m)^", "\t\t"));m + sb.append(this.setTemplate(TEMPLATE, valueMap)); + sb.append("}"); + return sb.toString(); + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5__AddServiceArtifact.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5__AddServiceArtifact.sql new file mode 100644 index 0000000000..d32c4666c5 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5__AddServiceArtifact.sql @@ -0,0 +1,30 @@ +use catalogdb; + +CREATE TABLE IF NOT EXISTS `service_info` ( + `ID` int (11) AUTO_INCREMENT, + `SERVICE_INPUT` varchar (5000), + `SERVICE_PROPERTIES` varchar (5000), + PRIMARY KEY (`ID`) +)ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `service_artifact`( + `ARTIFACT_UUID` varchar (200) NOT NULL, + `TYPE` varchar (200) NOT NULL, + `NAME` varchar (200) NOT NULL, + `VERSION` varchar (200) NOT NULL, + `DESCRIPTION` varchar (200) DEFAULT NULL, + `CONTENT` LONGTEXT DEFAULT NULL, + `CHECKSUM` varchar (200) DEFAULT NULL, + `CREATION_TIMESTAMP` DATETIME DEFAULT CURRENT_TIMESTAMP, + `SERVICE_MODEL_UUID` varchar (200) NOT NULL, + PRIMARY KEY (`ARTIFACT_UUID`), + CONSTRAINT `fk_service_artifact_service_info1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +)ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `service_to_service_info` ( + `SERVICE_MODEL_UUID` varchar (200) NOT NULL, + `SERVICE_INFO_ID` INT (11) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`SERVICE_INFO_ID`), + CONSTRAINT `fk_service_to_service_info__service1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_service_to_service_info__service_info1` FOREIGN KEY (`SERVICE_INFO_ID`) REFERENCES `service_info` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +)
\ No newline at end of file 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/exceptions/ApplicationException.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.java new file mode 100644 index 0000000000..f63ba356a1 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/exceptions/ApplicationException.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.exceptions; + +import org.onap.so.adapters.nssmf.model.ErrorResponse; +import org.springframework.http.ResponseEntity; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; + +public class ApplicationException extends Exception { + + private static final long serialVersionUID = 1L; + + private int errorCode; + + private String errorMsg; + + public ApplicationException(int errorCode, String errorMsg) { + this.errorCode = errorCode; + this.errorMsg = errorMsg; + } + + public int getErrorCode() { + return errorCode; + } + + public void setErrorCode(int errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMsg() { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) { + this.errorMsg = errorMsg; + } + + public ResponseEntity buildErrorResponse() { + String message; + try { + ErrorResponse err = new ErrorResponse(errorCode, errorMsg); + message = marshal(err); + } catch (ApplicationException e) { + return ResponseEntity.status(500).body("Internal Server Error"); + } + return ResponseEntity.status(errorCode).body(message); + } +} 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-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java new file mode 100644 index 0000000000..f6abd98794 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/HttpMethod.java @@ -0,0 +1,41 @@ +/*- + * ============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.rest; + +public enum HttpMethod { + GET, POST, PUT, DELETE, PATCH; + + public static HttpMethod fromString(String s) { + if (s == null) + return null; + if (("get").equalsIgnoreCase(s)) + return GET; + if (("post").equalsIgnoreCase(s)) + return POST; + if (("put").equalsIgnoreCase(s)) + return PUT; + if (("delete").equalsIgnoreCase(s)) + return DELETE; + if (("patch").equalsIgnoreCase(s)) + return PATCH; + throw new IllegalArgumentException("Invalid value for HTTP Method: " + s); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java new file mode 100644 index 0000000000..f2e651fd6e --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/JobStatus.java @@ -0,0 +1,42 @@ +/*- + * ============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.rest; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; + + +public enum JobStatus { + STARTED, PROCESSING, FINISHED, ERROR; + + public static JobStatus fromString(String s) throws ApplicationException { + if (s == null) + return null; + if (("started").equalsIgnoreCase(s)) + return STARTED; + if (("processing").equalsIgnoreCase(s)) + return PROCESSING; + if (("finished").equalsIgnoreCase(s)) + return FINISHED; + if (("error").equalsIgnoreCase(s)) + return ERROR; + throw new ApplicationException(500, "Invalid value for Job " + "Status: " + s); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java new file mode 100644 index 0000000000..d8e1e36058 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfAdapterRest.java @@ -0,0 +1,205 @@ +/*- + * ============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.rest; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.beans.nsmf.JobStatusRequest; +import org.onap.so.beans.nsmf.NssiActDeActRequest; +import org.onap.so.beans.nsmf.NssiAllocateRequest; +import org.onap.so.beans.nsmf.NssiCreateRequest; +import org.onap.so.beans.nsmf.NssiDeAllocateRequest; +import org.onap.so.beans.nsmf.NssiTerminateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequestById; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.assertObjectNotNull; + +@Controller +@RequestMapping(value = "/api/rest/provMns/v1", produces = {APPLICATION_JSON}, consumes = {APPLICATION_JSON}) +public class NssmfAdapterRest { + + private static final Logger logger = LoggerFactory.getLogger(NssmfAdapterRest.class); + + @Autowired + private NssmfManager nssmfMgr; + + @PostMapping(value = "/NSS/SliceProfiles") + public ResponseEntity allocateNssi(@RequestBody NssiAllocateRequest allocate) { + try { + logger.info("Nssmi allocate request is invoked"); + assertObjectNotNull(allocate); + RestResponse rsp = getNssmfMgr().allocateNssi(allocate); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/nssi") + public ResponseEntity createNssi(@RequestBody NssiCreateRequest create) { + try { + logger.info("Nssmf create request is invoked"); + assertObjectNotNull(create); + RestResponse rsp = getNssmfMgr().createNssi(create); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/SliceProfiles/{sliceProfileId}") + public ResponseEntity deAllocateNssi(@RequestBody NssiDeAllocateRequest deAllocate, + @PathVariable("sliceProfileId") final String sliceId) { + try { + logger.info("Nssmf deallocate request is invoked"); + assertObjectNotNull(deAllocate); + RestResponse rsp = getNssmfMgr().deAllocateNssi(deAllocate, sliceId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/nssi/{nssiId}") + public ResponseEntity terminateNssi(@RequestBody NssiTerminateRequest terminate, + @PathVariable("nssiId") String nssiId) { + try { + logger.info("Nssmf terminate request is invoked"); + assertObjectNotNull(terminate); + RestResponse rsp = getNssmfMgr().terminateNssi(terminate, nssiId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PutMapping(value = "/NSS/SliceProfiles/{sliceProfileId}") + public ResponseEntity modifyNssi(@RequestBody NssiUpdateRequest update, + @PathVariable("sliceProfileId") String sliceId) { + try { + logger.info("Nssmf modify request is invoked"); + assertObjectNotNull(update); + RestResponse rsp = getNssmfMgr().updateNssi(update, sliceId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PutMapping(value = "/NSS/nssi/{nssiId}") + public ResponseEntity modifyNssiById(@RequestBody NssiUpdateRequestById updateById, + @PathVariable("nssiId") String nssiId) { + try { + logger.info("Nssmf modify by ID request is invoked"); + assertObjectNotNull(updateById); + RestResponse rsp = getNssmfMgr().updateNssiById(updateById, nssiId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/{snssai}/activation") + public ResponseEntity activateNssi(@RequestBody NssiActDeActRequest activate, + @PathVariable("snssai") String snssai) { + try { + logger.info("Nssmf activate request is invoked"); + assertObjectNotNull(activate); + RestResponse rsp = getNssmfMgr().activateNssi(activate, snssai); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/{snssai}/deactivation") + public ResponseEntity deactivateNssi(@RequestBody NssiActDeActRequest deActivate, + @PathVariable("snssai") String snssai) { + try { + logger.info("Nssmf activate request is invoked"); + assertObjectNotNull(deActivate); + RestResponse rsp = getNssmfMgr().deActivateNssi(deActivate, snssai); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @PostMapping(value = "/NSS/jobs/{jobId}") + public ResponseEntity queryJobStatus(@RequestBody JobStatusRequest jobStatusReq, + @PathVariable("jobId") String jobId) { + try { + logger.info("Nssmf query job status request is invoked"); + assertObjectNotNull(jobStatusReq); + RestResponse rsp = getNssmfMgr().queryJobStatus(jobStatusReq, jobId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @GetMapping(value = "/vendor/{vendorName}/type/{networkType}/NSS" + "/SliceProfiles/{sliceProfileId}") + public ResponseEntity queryNssi(@PathVariable("vendorName") String vendorName, + @PathVariable("networktype") String networkType, @PathVariable("sliceProfileId") String sliceId) { + try { + logger.info("Nssmf query nssi request is invoked"); + RestResponse rsp = getNssmfMgr().queryNssi(vendorName, networkType, sliceId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + @GetMapping(value = "/vendor/{vendorName}/type/{networkType}/NSS/nssi" + "/{nssiId}") + public ResponseEntity queryNssiById(@PathVariable("vendorName") String vendorName, + @PathVariable("networkTtype") String networkType, @PathVariable("nssiId") String nssiId) { + try { + logger.info("Nssmf query nssi by ID request is invoked"); + RestResponse rsp = getNssmfMgr().queryNssiById(vendorName, networkType, nssiId); + return buildResponse(rsp); + } catch (ApplicationException e) { + return e.buildErrorResponse(); + } + } + + public void setNssmfMgr(NssmfManager nssmfMgr) { + this.nssmfMgr = nssmfMgr; + } + + public NssmfManager getNssmfMgr() { + return nssmfMgr; + } + + private ResponseEntity buildResponse(RestResponse rsp) { + return ResponseEntity.status(rsp.getStatus()).body(rsp.getResponseContent()); + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java new file mode 100644 index 0000000000..6306643a97 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfInfo.java @@ -0,0 +1,94 @@ +/*- + * ============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.rest; + +public class NssmfInfo { + + private String url; + + private String ipAddress; + + private String port; + + private String insecure; + + private String cacert; + + private String userName; + + private String password; + + public String getInsecure() { + return insecure; + } + + public void setInsecure(String insecure) { + this.insecure = insecure; + } + + public String getCacert() { + return cacert; + } + + public void setCacert(String cacert) { + this.cacert = cacert; + } + + public String getIpAddress() { + return ipAddress; + } + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java new file mode 100644 index 0000000000..0e25729610 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/NssmfManager.java @@ -0,0 +1,541 @@ +/*- + * ============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.rest; + +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.beans.nsmf.ActDeActNssi; +import org.onap.so.beans.nsmf.AllocateAnNssi; +import org.onap.so.beans.nsmf.AllocateCnNssi; +import org.onap.so.beans.nsmf.AllocateTnNssi; +import org.onap.so.beans.nsmf.CreateCnNssi; +import org.onap.so.beans.nsmf.DeAllocateNssi; +import org.onap.so.beans.nsmf.EsrInfo; +import org.onap.so.beans.nsmf.JobStatusRequest; +import org.onap.so.beans.nsmf.JobStatusResponse; +import org.onap.so.beans.nsmf.NetworkType; +import org.onap.so.beans.nsmf.NssiActDeActRequest; +import org.onap.so.beans.nsmf.NssiAllocateRequest; +import org.onap.so.beans.nsmf.NssiCreateRequest; +import org.onap.so.beans.nsmf.NssiDeAllocateRequest; +import org.onap.so.beans.nsmf.NssiResponse; +import org.onap.so.beans.nsmf.NssiTerminateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequest; +import org.onap.so.beans.nsmf.NssiUpdateRequestById; +import org.onap.so.beans.nsmf.ResponseDescriptor; +import org.onap.so.beans.nsmf.TerminateNssi; +import org.onap.so.beans.nsmf.UpdateCnNssi; +import org.onap.so.beans.nsmf.UpdateCnNssiById; +import org.onap.so.db.request.beans.ResourceOperationStatus; +import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.data.domain.Example; +import org.springframework.stereotype.Component; +import static java.lang.String.valueOf; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.DELETE; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.GET; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.PUT; +import static org.onap.so.adapters.nssmf.rest.JobStatus.ERROR; +import static org.onap.so.adapters.nssmf.rest.JobStatus.FINISHED; +import static org.onap.so.adapters.nssmf.rest.JobStatus.PROCESSING; +import static org.onap.so.adapters.nssmf.rest.JobStatus.STARTED; +import static org.onap.so.adapters.nssmf.rest.JobStatus.fromString; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ACTIVATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.ALLOCATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.CREATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.DEACTIVATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.DEALLOCATE_NSS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.QUERY_JOB_STATUS_FAILED; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.StatusDesc.QUERY_JOB_STATUS_SUCCESS; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.assertObjectNotNull; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; +import static org.onap.so.beans.nsmf.ActDeActNssi.ACT_URL; +import static org.onap.so.beans.nsmf.ActDeActNssi.DE_ACT_URL; + +@Component +@Primary +public class NssmfManager { + + private static final Logger logger = LoggerFactory.getLogger(NssmfManager.class); + + public final static String QUERY = "/api/rest/provMns/v1/NSS" + "/SliceProfiles/{sliceProfileId}"; + + public final static String QUERY_BY_ID = "/api/rest/provMns/v1/NSS/nssi" + "/{nssiId}"; + + @Autowired + private ResourceOperationStatusRepository rscOperStatusRepo; + + @Autowired + private RestUtil restUtil; + + + public RestResponse allocateNssi(NssiAllocateRequest nssmiAllocate) throws ApplicationException { + + assertObjectNotNull(nssmiAllocate.getEsrInfo()); + assertObjectNotNull(nssmiAllocate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssmiAllocate.getEsrInfo().getVendor()); + + String nsiId = null; + String allocateReq = null; + String allocateUrl = null; + logger.info("Allocate Nssi for " + nssmiAllocate.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssmiAllocate.getEsrInfo().getNetworkType()) { + + case CORE: + AllocateCnNssi cn = nssmiAllocate.getAllocateCnNssi(); + assertObjectNotNull(cn); + assertObjectNotNull(cn.getNsiInfo()); + assertObjectNotNull(cn.getNsiInfo().getNsiId()); + nsiId = cn.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + allocateReq = marshal(cn); + allocateUrl = AllocateCnNssi.URL; + break; + + case ACCESS: + AllocateAnNssi an = nssmiAllocate.getAllocateAnNssi(); + assertObjectNotNull(an); + assertObjectNotNull(an.getNsiInfo()); + assertObjectNotNull(an.getNsiInfo().getNsiId()); + nsiId = an.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + allocateReq = marshal(an); + allocateUrl = AllocateAnNssi.URL; + break; + + case TRANSPORT: + AllocateTnNssi tn = nssmiAllocate.getAllocateTnNssi(); + assertObjectNotNull(tn); + assertObjectNotNull(tn.getNsiInfo()); + assertObjectNotNull(tn.getNsiInfo().getNsiId()); + nsiId = tn.getNsiInfo().getNsiId(); + allocateReq = marshal(tn); + allocateUrl = AllocateTnNssi.URL; + break; + + } + RestResponse rsp = restUtil.sendRequest(allocateUrl, POST, allocateReq, nssmiAllocate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(allocateRes.getNssiId(), allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ALLOCATE_NSS_SUCCESS); + logger.info("save segment and operation info -> end"); + } + return rsp; + } + + public RestResponse createNssi(NssiCreateRequest nssiCreate) throws ApplicationException { + + assertObjectNotNull(nssiCreate.getEsrInfo()); + assertObjectNotNull(nssiCreate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiCreate.getEsrInfo().getVendor()); + + String nsiId = null; + String createReq = null; + String createUrl = null; + logger.info("Create Nssi for " + nssiCreate.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssiCreate.getEsrInfo().getNetworkType()) { + case CORE: + CreateCnNssi cn = nssiCreate.getCreateCnNssi(); + nsiId = cn.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + createReq = marshal(cn); + createUrl = AllocateCnNssi.URL; + break; + + case ACCESS: + case TRANSPORT: + throw new ApplicationException(1, "Create Nssi doesn't " + "support the Network type:" + + nssiCreate.getEsrInfo().getNetworkType()); + } + RestResponse rsp = restUtil.sendRequest(createUrl, POST, createReq, nssiCreate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(allocateRes.getNssiId(), allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, CREATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse deAllocateNssi(NssiDeAllocateRequest nssiDeallocate, String sliceId) + throws ApplicationException { + + assertObjectNotNull(nssiDeallocate.getEsrInfo()); + assertObjectNotNull(nssiDeallocate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiDeallocate.getEsrInfo().getVendor()); + + DeAllocateNssi deAllocate = nssiDeallocate.getDeAllocateNssi(); + + assertObjectNotNull(sliceId); + assertObjectNotNull(deAllocate.getNssiId()); + assertObjectNotNull(deAllocate.getNsiId()); + + String deallocateUrl = formTnAndAnUrl(nssiDeallocate.getEsrInfo(), DeAllocateNssi.URL, sliceId); + String deAllocateReq = marshal(deAllocate); + + logger.info("Deallocate Nssi has begun"); + + RestResponse rsp = restUtil.sendRequest(deallocateUrl, DELETE, deAllocateReq, nssiDeallocate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse res = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(deAllocate.getNssiId(), res.getJobId(), deAllocate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, DEALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + private String formTnAndAnUrl(EsrInfo esrInfo, String origUrl, String variable) { + + origUrl = formatUrl(origUrl, variable); + String[] val; + + switch (esrInfo.getNetworkType()) { + + case TRANSPORT: + val = origUrl.split("v1"); + return val[0] + "v1/tn" + val[1]; + + case ACCESS: + val = origUrl.split("v1"); + return val[0] + "v1/an" + val[1]; + + case CORE: + return origUrl; + } + return origUrl; + } + + private String formatUrl(String origUrl, String variable) { + + if (variable != null) { + origUrl = String.format(origUrl, variable); + } + return origUrl; + } + + + public RestResponse terminateNssi(NssiTerminateRequest nssiTerminate, String nssiId) throws ApplicationException { + + assertObjectNotNull(nssiTerminate.getEsrInfo()); + assertObjectNotNull(nssiTerminate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiTerminate.getEsrInfo().getVendor()); + + TerminateNssi terminate = nssiTerminate.getTerminateNssi(); + + assertObjectNotNull(nssiId); + assertObjectNotNull(terminate.getNsiId()); + + logger.info("Terminate Nssi has begun"); + + String terminateUrl = formTnAndAnUrl(nssiTerminate.getEsrInfo(), TerminateNssi.URL, nssiId); + String terminateReq = marshal(terminate); + + RestResponse rsp = restUtil.sendRequest(terminateUrl, DELETE, terminateReq, nssiTerminate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse res = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(nssiId, res.getJobId(), terminate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, DEALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse activateNssi(NssiActDeActRequest nssiActivate, String snssai) throws ApplicationException { + + assertObjectNotNull(nssiActivate.getEsrInfo()); + assertObjectNotNull(nssiActivate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiActivate.getEsrInfo().getVendor()); + + ActDeActNssi activate = nssiActivate.getActDeActNssi(); + + assertObjectNotNull(snssai); + assertObjectNotNull(activate.getNssiId()); + assertObjectNotNull(activate.getNsiId()); + + logger.info("Activate Nssi has begun"); + + String activateUrl = formTnAndAnUrl(nssiActivate.getEsrInfo(), ACT_URL, snssai); + String activateReq = marshal(activate); + + RestResponse rsp = restUtil.sendRequest(activateUrl, PUT, activateReq, nssiActivate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse activateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = + new ResourceOperationStatus(activate.getNssiId(), activateRes.getJobId(), activate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ACTIVATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse deActivateNssi(NssiActDeActRequest nssiDeActivate, String snssai) throws ApplicationException { + + assertObjectNotNull(nssiDeActivate.getEsrInfo()); + assertObjectNotNull(nssiDeActivate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiDeActivate.getEsrInfo().getVendor()); + + logger.info("Deactivate Nssi has begun"); + + ActDeActNssi deActivate = nssiDeActivate.getActDeActNssi(); + + assertObjectNotNull(snssai); + assertObjectNotNull(deActivate.getNssiId()); + assertObjectNotNull(deActivate.getNsiId()); + + String deActivateUrl = formTnAndAnUrl(nssiDeActivate.getEsrInfo(), DE_ACT_URL, snssai); + String deActivateReq = marshal(deActivate); + + RestResponse rsp = restUtil.sendRequest(deActivateUrl, PUT, deActivateReq, nssiDeActivate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse deActivateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(deActivate.getNssiId(), + deActivateRes.getJobId(), deActivate.getNsiId()); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, DEACTIVATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse queryJobStatus(JobStatusRequest jobReq, String jobId) throws ApplicationException { + + assertObjectNotNull(jobReq.getEsrInfo()); + assertObjectNotNull(jobReq.getEsrInfo().getNetworkType()); + assertObjectNotNull(jobReq.getEsrInfo().getVendor()); + assertObjectNotNull(jobId); + assertObjectNotNull(jobReq.getNssiId()); + assertObjectNotNull(jobReq.getNsiId()); + + logger.info("Query job status has begun"); + + ResourceOperationStatus status = new ResourceOperationStatus(jobReq.getNssiId(), jobId, jobReq.getNsiId()); + status = rscOperStatusRepo.findOne(Example.of(status)) + .orElseThrow(() -> new ApplicationException(404, "Cannot Find Operation Status")); + + String statusUrl = formatUrl(JobStatusRequest.URL, jobId); + if (jobReq.getResponseId() != null) { + statusUrl = statusUrl + "?responseId=" + jobReq.getResponseId(); + } + + RestResponse rsp = restUtil.sendRequest(statusUrl, GET, "", jobReq.getEsrInfo()); + assertObjectNotNull(rsp); + + if (!valueOf(rsp.getStatus()).startsWith("2")) { + updateDbStatus(status, rsp.getStatus(), ERROR, QUERY_JOB_STATUS_FAILED); + throw new ApplicationException(500, QUERY_JOB_STATUS_FAILED); + } + + ResponseDescriptor rspDesc = + unMarshal(rsp.getResponseContent(), JobStatusResponse.class).getResponseDescriptor(); + logger.info("save segment and operaton info -> begin"); + updateRequestDbJobStatus(rspDesc, status, rsp); + logger.info("save segment and operaton info -> end"); + return rsp; + } + + + public RestResponse updateNssi(NssiUpdateRequest nssiUpdate, String sliceId) throws ApplicationException { + + assertObjectNotNull(nssiUpdate.getEsrInfo()); + assertObjectNotNull(nssiUpdate.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiUpdate.getEsrInfo().getVendor()); + assertObjectNotNull(sliceId); + + String nsiId = null; + String nssiId = null; + String updateReq = null; + String updateUrl = null; + logger.info("Update Nssi for " + nssiUpdate.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssiUpdate.getEsrInfo().getNetworkType()) { + case CORE: + UpdateCnNssi cn = nssiUpdate.getUpdateCnNssi(); + nsiId = cn.getNsiInfo().getNsiId(); + nssiId = cn.getNssiId(); + assertObjectNotNull(nsiId); + assertObjectNotNull(nssiId); + updateReq = marshal(cn); + updateUrl = formatUrl(UpdateCnNssi.URL, sliceId); + break; + + case ACCESS: + case TRANSPORT: + throw new ApplicationException(1, "Update Nssi doesn't " + "support the Network type:" + + nssiUpdate.getEsrInfo().getNetworkType()); + } + + RestResponse rsp = restUtil.sendRequest(updateUrl, PUT, updateReq, nssiUpdate.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(nssiId, allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse updateNssiById(NssiUpdateRequestById nssiUpdateById, String nssiId) + throws ApplicationException { + + assertObjectNotNull(nssiUpdateById.getEsrInfo()); + assertObjectNotNull(nssiUpdateById.getEsrInfo().getNetworkType()); + assertObjectNotNull(nssiUpdateById.getEsrInfo().getVendor()); + assertObjectNotNull(nssiId); + + String nsiId = null; + String updateReq = null; + String updateUrl = null; + logger.info("Update Nssi by ID for " + nssiUpdateById.getEsrInfo().getNetworkType() + " Network has begun"); + + switch (nssiUpdateById.getEsrInfo().getNetworkType()) { + case CORE: + UpdateCnNssiById cn = nssiUpdateById.getUpdateCnNssiById(); + nsiId = cn.getNsiInfo().getNsiId(); + assertObjectNotNull(nsiId); + updateReq = marshal(cn); + updateUrl = formatUrl(UpdateCnNssiById.URL, nssiId); + break; + + case ACCESS: + case TRANSPORT: + throw new ApplicationException(1, "Update Nssi doesn't " + "support the Network type:" + + nssiUpdateById.getEsrInfo().getNetworkType()); + } + + RestResponse rsp = restUtil.sendRequest(updateUrl, PUT, updateReq, nssiUpdateById.getEsrInfo()); + assertObjectNotNull(rsp); + + if (valueOf(rsp.getStatus()).startsWith("2")) { + NssiResponse allocateRes = unMarshal(rsp.getResponseContent(), NssiResponse.class); + + ResourceOperationStatus status = new ResourceOperationStatus(nssiId, allocateRes.getJobId(), nsiId); + logger.info("save segment and operaton info -> begin"); + updateDbStatus(status, rsp.getStatus(), STARTED, ALLOCATE_NSS_SUCCESS); + logger.info("save segment and operaton info -> end"); + } + return rsp; + } + + public RestResponse queryNssi(String vendor, String type, String sliceId) throws ApplicationException { + + logger.info("Query Nssi has begun"); + String getUrl = formatUrl(QUERY, sliceId); + EsrInfo esr = new EsrInfo(); + esr.setVendor(vendor); + esr.setNetworkType(NetworkType.valueOf(type)); + RestResponse rsp = restUtil.sendRequest(getUrl, GET, "", esr); + assertObjectNotNull(rsp); + return rsp; + } + + public RestResponse queryNssiById(String vendor, String type, String nssiId) throws ApplicationException { + + logger.info("Query Nssi by ID has begun"); + String getUrl = formatUrl(QUERY_BY_ID, nssiId); + EsrInfo esr = new EsrInfo(); + esr.setVendor(vendor); + esr.setNetworkType(NetworkType.valueOf(type)); + RestResponse rsp = restUtil.sendRequest(getUrl, GET, "", esr); + assertObjectNotNull(rsp); + return rsp; + } + + private void updateRequestDbJobStatus(ResponseDescriptor rspDesc, ResourceOperationStatus status, RestResponse rsp) + throws ApplicationException { + + switch (fromString(rspDesc.getStatus())) { + + case STARTED: + updateDbStatus(status, rsp.getStatus(), STARTED, QUERY_JOB_STATUS_SUCCESS); + break; + + case ERROR: + updateDbStatus(status, rsp.getStatus(), ERROR, QUERY_JOB_STATUS_FAILED); + throw new ApplicationException(500, QUERY_JOB_STATUS_FAILED); + + case FINISHED: + if (rspDesc.getProgress() == 100) { + updateDbStatus(status, rsp.getStatus(), FINISHED, QUERY_JOB_STATUS_SUCCESS); + } + break; + + case PROCESSING: + updateDbStatus(status, rsp.getStatus(), PROCESSING, QUERY_JOB_STATUS_SUCCESS); + break; + } + } + + private void updateDbStatus(ResourceOperationStatus status, int rspStatus, JobStatus jobStatus, + String description) { + status.setErrorCode(valueOf(rspStatus)); + status.setStatus(jobStatus.toString()); + status.setStatusDescription(description); + logger.info("Updating DB status"); + rscOperStatusRepo.save(status); + logger.info("Updating successful"); + } + + public void setRscOperStatusRepo(ResourceOperationStatusRepository rscOperStatusRepo) { + this.rscOperStatusRepo = rscOperStatusRepo; + } + + public void setRestUtil(RestUtil restUtil) { + this.restUtil = restUtil; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java new file mode 100644 index 0000000000..cc047e45c7 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestResponse.java @@ -0,0 +1,92 @@ +/*- + * ============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.rest; + +import java.util.Map; + +public class RestResponse { + + // the response content + private String responseContent; + + // the response status + private int status; + + // the response header + private Map<String, String> respHeaderMap; + + public RestResponse() { + this.status = -1; + + this.respHeaderMap = null; + } + + public int getStatus() { + return this.status; + } + + public void setStatus(int status) { + this.status = status; + } + + public Map<String, String> getRespHeaderMap() { + return this.respHeaderMap; + } + + public void setRespHeaderMap(Map<String, String> header) { + this.respHeaderMap = header; + } + + public int getRespHeaderInt(String key) { + if (this.respHeaderMap != null) { + String result = this.respHeaderMap.get(key); + if (result != null) { + return Integer.parseInt(result); + } + } + return -1; + } + + public long getRespHeaderLong(String key) { + if (this.respHeaderMap != null) { + String result = this.respHeaderMap.get(key); + if (result != null) { + return Long.parseLong(result); + } + } + return -1L; + } + + public String getRespHeaderStr(String key) { + if (this.respHeaderMap != null) { + return this.respHeaderMap.get(key); + } + return null; + } + + public String getResponseContent() { + return this.responseContent; + } + + public void setResponseContent(String responseString) { + this.responseContent = responseString; + } +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java new file mode 100644 index 0000000000..3592d4f6a3 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/RestUtil.java @@ -0,0 +1,307 @@ +/*- + * ============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.rest; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import javax.ws.rs.core.UriBuilder; +import java.net.SocketTimeoutException; +import java.net.URI; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.aai.domain.yang.EsrSystemInfoList; +import org.onap.aai.domain.yang.EsrThirdpartySdnc; +import org.onap.aai.domain.yang.EsrThirdpartySdncList; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.onap.so.adapters.nssmf.extclients.aai.AaiServiceProvider; +import org.onap.so.adapters.nssmf.model.TokenRequest; +import org.onap.so.adapters.nssmf.model.TokenResponse; +import org.onap.so.beans.nsmf.EsrInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import static org.apache.http.entity.ContentType.APPLICATION_JSON; +import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.BAD_REQUEST; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal; +import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal; +import static org.onap.so.logger.ErrorCode.AvailabilityError; +import static org.onap.so.logger.LoggingAnchor.FOUR; +import static org.onap.so.logger.MessageEnum.RA_NS_EXC; + +@Component +public class RestUtil { + + private static final Logger logger = LoggerFactory.getLogger(RestUtil.class); + + private static final int DEFAULT_TIME_OUT = 60000; + + private static final String NSSMI_ADAPTER = "NSSMI Adapter"; + + private static final String TOKEN_URL = "/api/rest/securityManagement/v1" + "/oauth/token"; + + @Autowired + private AaiServiceProvider aaiSvcProv; + + + public NssmfInfo getNssmfHost(EsrInfo esrInfo) throws ApplicationException { + EsrThirdpartySdncList sdncList = aaiSvcProv.invokeGetThirdPartySdncList(); + if (sdncList != null && sdncList.getEsrThirdpartySdnc() != null) { + for (EsrThirdpartySdnc sdncEsr : sdncList.getEsrThirdpartySdnc()) { + + EsrSystemInfoList sysInfoList = + aaiSvcProv.invokeGetThirdPartySdncEsrSystemInfo(sdncEsr.getThirdpartySdncId()); + + if (sysInfoList != null && sysInfoList.getEsrSystemInfo() != null) { + for (EsrSystemInfo esr : sysInfoList.getEsrSystemInfo()) { + if (esr != null && esr.getType().equals(esrInfo.getNetworkType().getNetworkType()) + && esr.getVendor().equals(esrInfo.getVendor())) { + logger.info("Found an entry with vendor name " + esrInfo.getVendor() + " and network type " + + esrInfo.getNetworkType() + " in ESR."); + NssmfInfo nssmfInfo = new NssmfInfo(); + nssmfInfo.setIpAddress(esr.getIpAddress()); + nssmfInfo.setPort(esr.getPort()); + nssmfInfo.setCacert(esr.getSslCacert()); + nssmfInfo.setUserName(esr.getUserName()); + nssmfInfo.setPassword(esr.getPassword()); + String endPoint = UriBuilder.fromPath("").host(esr.getIpAddress()) + .port(Integer.valueOf(esr.getPort())).scheme("https").build().toString(); + nssmfInfo.setUrl(endPoint); + return nssmfInfo; + } + } + } + + } + } + + throw new ApplicationException(BAD_REQUEST, "ESR information is improper"); + } + + public RestResponse sendRequest(String url, HttpMethod methodType, String content, EsrInfo esrInfo) + throws ApplicationException { + + NssmfInfo nssmfInfo = getNssmfHost(esrInfo); + + TokenRequest req = new TokenRequest(); + req.setGrantType("password"); + req.setUserName(nssmfInfo.getUserName()); + req.setValue(nssmfInfo.getPassword()); + + String tokenReq = marshal(req); + + logger.info("Sending token request to NSSMF: " + tokenReq); + RestResponse tokenRes = send(nssmfInfo.getUrl() + TOKEN_URL, POST, tokenReq, null); + + TokenResponse res = unMarshal(tokenRes.getResponseContent(), TokenResponse.class); + String token = res.getAccessToken(); + Header header = new BasicHeader("X-Auth-Token", token); + String nssmfUrl = nssmfInfo.getUrl() + url; + return send(nssmfUrl, methodType, content, header); + } + + private RestResponse send(String url, HttpMethod methodType, String content, Header header) { + + HttpRequestBase req = null; + HttpResponse res = null; + + logger.debug("Beginning to send message {}: {}", methodType, url); + + try { + int timeout = DEFAULT_TIME_OUT; + + RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout).build(); + logger.debug("Sending request to NSSMF: " + content); + req = getHttpReq(url, methodType, header, config, content); + res = getHttpsClient().execute(req); + + String resContent = null; + if (res.getEntity() != null) { + resContent = EntityUtils.toString(res.getEntity(), "UTF-8"); + } + + int statusCode = res.getStatusLine().getStatusCode(); + String statusMessage = res.getStatusLine().getReasonPhrase(); + logger.info("NSSMF Response: {} {}", statusCode, + statusMessage + (resContent == null ? "" : System.lineSeparator() + resContent)); + + if (res.getStatusLine().getStatusCode() >= 300) { + String errMsg = "{\n \"errorCode\": " + res.getStatusLine().getStatusCode() + + "\n \"errorDescription\": " + statusMessage + "\n}"; + logError(errMsg); + return createResponse(statusCode, errMsg); + } + if (null != req) { + req.reset(); + } else { + logger.debug("method is NULL:"); + } + req = null; + + return createResponse(statusCode, resContent); + + } catch (SocketTimeoutException | ConnectTimeoutException e) { + String errMsg = "Request to NSSMF timed out"; + logError(errMsg, e); + return createResponse(408, errMsg); + } catch (Exception e) { + String errMsg = "Error processing request to NSSMF"; + logError(errMsg, e); + return createResponse(500, errMsg); + } finally { + if (res != null) { + try { + EntityUtils.consume(res.getEntity()); + } catch (Exception e) { + logger.debug("Exception :", e); + } + } + if (req != null) { + try { + req.reset(); + } catch (Exception e) { + logger.debug("Exception :", e); + } + } + } + } + + private RestResponse createResponse(int statusCode, String errMsg) { + RestResponse restResponse = new RestResponse(); + restResponse.setStatus(statusCode); + restResponse.setResponseContent(errMsg); + return restResponse; + } + + private HttpRequestBase getHttpReq(String url, HttpMethod method, Header header, RequestConfig config, + String content) throws ApplicationException { + HttpRequestBase base = null; + switch (method) { + case POST: + HttpPost post = new HttpPost(url); + post.setEntity(new StringEntity(content, APPLICATION_JSON)); + base = post; + break; + + case GET: + base = new HttpGet(url); + break; + + case PUT: + HttpPut put = new HttpPut(url); + put.setEntity(new StringEntity(content, APPLICATION_JSON)); + base = put; + break; + + case PATCH: + break; + + case DELETE: + HttpDeleteWithBody delete = new HttpDeleteWithBody(url); + if (content != null) { + delete.setEntity(new StringEntity(content, APPLICATION_JSON)); + } + base = delete; + break; + + } + base.setConfig(config); + if (header != null) { + base.setHeader(header); + } + return base; + } + + class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { + public static final String METHOD_NAME = "DELETE"; + + public String getMethod() { + return METHOD_NAME; + } + + public HttpDeleteWithBody(final String uri) { + super(); + setURI(URI.create(uri)); + } + + public HttpDeleteWithBody(final URI uri) { + super(); + setURI(uri); + } + + public HttpDeleteWithBody() { + super(); + } + } + + + public HttpClient getHttpsClient() { + + TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {} + + public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {} + }}; + + // Install the all-trusting trust manager + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + + SSLConnectionSocketFactory sslsf = + new SSLConnectionSocketFactory(sc, new String[] {"TLSv1"}, null, new TrustAllHostNameVerifier()); + return HttpClients.custom().setSSLSocketFactory(sslsf).build(); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + private static void logError(String errMsg, Throwable t) { + logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.getValue(), errMsg, t); + } + + private static void logError(String errMsg) { + logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.toString(), errMsg); + } +} + diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.java new file mode 100644 index 0000000000..254186bda8 --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/rest/TrustAllHostNameVerifier.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.rest; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; + +public class TrustAllHostNameVerifier implements HostnameVerifier { + + public boolean verify(String hostname, SSLSession session) { + return true; + } + +} diff --git a/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java new file mode 100644 index 0000000000..b0b84d822b --- /dev/null +++ b/adapters/mso-nssmf-adapter/src/main/java/org/onap/so/adapters/nssmf/util/NssmfAdapterUtil.java @@ -0,0 +1,94 @@ +/*- + * ============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.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import org.onap.so.adapters.nssmf.exceptions.ApplicationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.so.logger.ErrorCode; +import static org.onap.so.logger.LoggingAnchor.THREE; +import static org.onap.so.logger.MessageEnum.RA_NS_EXC; + +public class NssmfAdapterUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(NssmfAdapterUtil.class); + + public static final int BAD_REQUEST = 400; + + private static final String UNMARSHAL_FAIL_MSG = "Failed to unmarshal json"; + + private static final String MARSHAL_FAIL_MSG = "Failed to marshal object"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + public static class StatusDesc { + + public static final String ALLOCATE_NSS_SUCCESS = "Allocating nss is " + "successful"; + + public static final String CREATE_NSS_SUCCESS = "Creating nss is " + "successful"; + + public static final String DEALLOCATE_NSS_SUCCESS = "Deallocate nss " + "is successful"; + + public static final String ACTIVATE_NSS_SUCCESS = "Activate nss " + "is successful"; + + public static final String DEACTIVATE_NSS_SUCCESS = "Deactivate nss " + "is successful"; + + public static final String QUERY_JOB_STATUS_FAILED = "Query job " + "status failed"; + + public static final String QUERY_JOB_STATUS_SUCCESS = "Query job " + "status is successful"; + + private StatusDesc() { + + } + } + + private NssmfAdapterUtil() { + + } + + public static void assertObjectNotNull(Object object) throws ApplicationException { + if (null == object) { + LOGGER.error("Object is null."); + throw new ApplicationException(BAD_REQUEST, "An object is null."); + } + } + + public static <T> T unMarshal(String jsonstr, Class<T> type) throws ApplicationException { + try { + return MAPPER.readValue(jsonstr, type); + } catch (IOException e) { + LOGGER.error(THREE, RA_NS_EXC.toString(), ErrorCode.BusinessProcessError.getValue(), UNMARSHAL_FAIL_MSG, e); + throw new ApplicationException(BAD_REQUEST, UNMARSHAL_FAIL_MSG); + } + } + + public static String marshal(Object srcObj) throws ApplicationException { + try { + return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(srcObj); + } catch (IOException e) { + LOGGER.error(THREE, RA_NS_EXC.toString(), ErrorCode.BusinessProcessError.getValue(), MARSHAL_FAIL_MSG, e); + throw new ApplicationException(BAD_REQUEST, MARSHAL_FAIL_MSG); + } + } + +} 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-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/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 8c042dcbaf..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_NAME varchar(45); -ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_NAME varchar(45); +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); 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-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 4472956eb7..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> 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..9b2a8c3d62 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 @@ -20,13 +20,18 @@ package org.onap.so.adapters.vevnfm.aai; +import java.util.Collections; +import java.util.LinkedList; import java.util.List; import java.util.Optional; +import org.apache.logging.log4j.util.Strings; import org.onap.aai.domain.yang.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,43 +45,59 @@ public class AaiConnection { private static final int FIRST_INDEX = 0; - public EsrSystemInfo receiveVnfm() { + private static void isValid(final List<EsrSystemInfo> infos) throws VeVnfmException { + if (infos == null || infos.isEmpty() || Strings.isBlank(infos.get(FIRST_INDEX).getServiceUrl())) { + throw new VeVnfmException("No 'url' field in VNFM info"); + } + } + + public List<EsrSystemInfo> receiveVnfm() throws VeVnfmException { + List<EsrSystemInfo> infos; + + try { + infos = receiveVnfmInternal(); + } catch (Exception e) { + throw new VeVnfmException(e); + } + + isValid(infos); + + return infos; + } + + private List<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(); logger.info("The VNFM replied with: {}", esrVnfmList); final List<EsrVnfm> esrVnfm = esrVnfmList.getEsrVnfm(); - if (esrVnfm.isEmpty()) { - return null; + final List<EsrSystemInfo> infos = new LinkedList<>(); + + for (final EsrVnfm vnfm : esrVnfm) { + final String vnfmId = vnfm.getVnfmId(); + infos.addAll(receiveVnfmServiceUrl(resourcesClient, vnfmId)); } - final String vnfmId = esrVnfm.get(FIRST_INDEX).getVnfmId(); - return receiveVnfmServiceUrl(resourcesClient, vnfmId); + return infos; } return null; } - private EsrSystemInfo receiveVnfmServiceUrl(final AAIResourcesClient resourcesClient, final String vnfmId) { + private List<EsrSystemInfo> receiveVnfmServiceUrl(final AAIResourcesClient resourcesClient, final String vnfmId) { final Optional<EsrVnfm> response = resourcesClient.get(EsrVnfm.class, AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId).depth(Depth.ONE)); if (response.isPresent()) { final EsrVnfm esrVnfm = response.get(); logger.info("The VNFM replied with: {}", esrVnfm); - final List<EsrSystemInfo> esrSystemInfo = esrVnfm.getEsrSystemInfoList().getEsrSystemInfo(); - - if (esrSystemInfo.isEmpty()) { - return null; - } - - return esrSystemInfo.get(FIRST_INDEX); + return esrVnfm.getEsrSystemInfoList().getEsrSystemInfo(); } - return null; + return Collections.emptyList(); } } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/EsrId.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/EsrId.java new file mode 100644 index 0000000000..13ff2b6397 --- /dev/null +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/aai/EsrId.java @@ -0,0 +1,45 @@ +/*- + * ============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.aai; + +import org.onap.aai.domain.yang.EsrSystemInfo; + +public class EsrId { + + private EsrSystemInfo info; + private String id; + + public EsrSystemInfo getInfo() { + return info; + } + + public void setInfo(final EsrSystemInfo info) { + this.info = info; + } + + public String getId() { + return id; + } + + public void setId(final String id) { + this.id = id; + } +} 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..c033fc3f96 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,10 @@ package org.onap.so.adapters.vevnfm.configuration; +import java.util.List; +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 +42,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 List<EsrSystemInfo> infos = startupService.receiveVnfm(); + subscriptionScheduler.setInfos(infos); } } } 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 251e0c426b..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,11 +20,16 @@ package org.onap.so.adapters.vevnfm.provider; +import org.apache.logging.log4j.util.Strings; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; public class AuthorizationHeadersProvider extends BasicHttpHeadersProvider { public void addAuthorization(final String authorization) { + if (Strings.isBlank(authorization)) { + return; + } + getHttpHeaders().set(AUTHORIZATION_HEADER, authorization); } diff --git a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/DmaapService.java b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/DmaapService.java index 59397cead3..36a4c3300d 100644 --- a/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/DmaapService.java +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/DmaapService.java @@ -25,12 +25,15 @@ public class DmaapService { private HttpRestServiceProvider restProvider; public void send(final VnfLcmOperationOccurrenceNotification notification) { - final ResponseEntity<String> response = restProvider.postHttpRequest(notification, getUrl(), String.class); - - final HttpStatus statusCode = response.getStatusCode(); - final String body = response.getBody(); - - logger.info("The DMaaP replied with the code {} and the body {}", statusCode, body); + try { + final ResponseEntity<String> response = restProvider.postHttpRequest(notification, getUrl(), String.class); + final HttpStatus statusCode = response.getStatusCode(); + final String body = response.getBody(); + + logger.info("The DMaaP replied with the code {} and the body {}", statusCode, body); + } catch (Exception e) { + logger.warn("An issue connecting to DMaaP", e); + } } private String getUrl() { 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..92906ef35c 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,44 @@ package org.onap.so.adapters.vevnfm.service; -import org.apache.logging.log4j.util.Strings; +import java.util.Collections; +import java.util.List; 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 = {Exception.class}, maxAttempts = 5, backoff = @Backoff(delay = 5000, multiplier = 2)) + public List<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); - - if (!done) { - throw new VeVnfmException("Could not subscribe to VNFM"); - } + @Recover + public List<EsrSystemInfo> recoverReceiveVnfm(final Throwable t) { + logger.warn("Connection to AAI failed"); + final EsrSystemInfo info = new EsrSystemInfo(); + info.setServiceUrl(vnfmDefaultEndpoint); + logger.warn("This EsrSystemInfo is used by default: {}", info); + return Collections.singletonList(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 eefd9ba93b..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,19 +55,40 @@ 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.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); + } + } + private LccnSubscriptionRequest createRequest() { final LccnSubscriptionRequest request = new LccnSubscriptionRequest(); request.callbackUri(getCallbackUri()); @@ -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..d9f3acc3df --- /dev/null +++ b/adapters/mso-ve-vnfm-adapter/src/main/java/org/onap/so/adapters/vevnfm/service/SubscriptionScheduler.java @@ -0,0 +1,98 @@ +/*- + * ============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 java.util.LinkedList; +import java.util.List; +import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vevnfm.aai.EsrId; +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 List<EsrId> esrIds; + + public void setInfos(final List<EsrSystemInfo> infos) { + esrIds = new LinkedList<>(); + + for (final EsrSystemInfo info : infos) { + final EsrId esrId = new EsrId(); + esrId.setInfo(info); + esrIds.add(esrId); + } + } + + List<EsrId> getEsrIds() { + return esrIds; + } + + @Scheduled(fixedRate = 5000, initialDelay = 2000) + void subscribeTask() throws VeVnfmException { + if (isEsrIdsValid()) { + for (final EsrId esrId : esrIds) { + singleSubscribe(esrId); + } + } + } + + @Scheduled(fixedRate = 20000) + void checkSubscribeTask() throws VeVnfmException { + if (isEsrIdsValid()) { + for (final EsrId esrId : esrIds) { + singleCheckSubscription(esrId); + } + } + } + + private boolean isEsrIdsValid() { + return esrIds != null && !esrIds.isEmpty(); + } + + private void singleSubscribe(final EsrId esrId) throws VeVnfmException { + if (esrId.getId() == null) { + logger.info("Single subscribe task"); + esrId.setId(subscriberService.subscribe(esrId.getInfo())); + } + } + + private void singleCheckSubscription(final EsrId esrId) throws VeVnfmException { + if (esrId.getId() != null) { + logger.info("Checking subscription: {}", esrId.getId()); + if (!subscriberService.checkSubscription(esrId.getInfo(), esrId.getId())) { + logger.info("Subscription {} not available", esrId.getId()); + esrId.setId(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 index 64503ddfc2..f9ae427086 100644 --- 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 @@ -28,6 +28,8 @@ 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(); @@ -44,4 +46,41 @@ public class AuthorizationHeadersProviderTest { 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..9b18cf96dc 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,11 @@ 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 java.util.Collections; +import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -30,62 +34,35 @@ 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); - } - - @Test - public void testFailureAai() throws Exception { - // given - final EsrSystemInfo info = new EsrSystemInfo(); - when(aaiConnection.receiveVnfm()).thenReturn(info); + info.setServiceUrl(URL); + final List<EsrSystemInfo> infos = Collections.singletonList(info); - thrown.expect(VeVnfmException.class); + when(aaiConnection.receiveVnfm()).thenReturn(infos); // when - startupService.run(); - } + final List<EsrSystemInfo> systemInfo = startupService.receiveVnfm(); - @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); - - thrown.expect(VeVnfmException.class); - - // when - startupService.run(); + // then + verify(aaiConnection).receiveVnfm(); + assertEquals(infos, 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-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscriptionSchedulerTest.java b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscriptionSchedulerTest.java new file mode 100644 index 0000000000..d3da7c86ec --- /dev/null +++ b/adapters/mso-ve-vnfm-adapter/src/test/java/org/onap/so/adapters/vevnfm/service/SubscriptionSchedulerTest.java @@ -0,0 +1,69 @@ +/*- + * ============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 static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.EsrSystemInfo; + +@RunWith(MockitoJUnitRunner.class) +public class SubscriptionSchedulerTest { + + private static final String URL = "url"; + private static final String ID = "id044"; + + @Mock + private SubscriberService subscriberService; + + @InjectMocks + private SubscriptionScheduler subscriptionScheduler; + + @Test + public void testFullScenario() throws Exception { + // given + final EsrSystemInfo info = new EsrSystemInfo(); + info.setServiceUrl(URL); + final List<EsrSystemInfo> infos = Collections.singletonList(info); + + when(subscriberService.subscribe(eq(info))).thenReturn(ID); + when(subscriberService.checkSubscription(eq(info), eq(ID))).thenReturn(false); + + // when + subscriptionScheduler.setInfos(infos); + subscriptionScheduler.subscribeTask(); + subscriptionScheduler.checkSubscribeTask(); + + // then + verify(subscriberService).subscribe(info); + verify(subscriberService).checkSubscription(info, ID); + + assertNull(subscriptionScheduler.getEsrIds().get(0).getId()); + } +} 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/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/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/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 d02bd9a345..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 @@ -41,12 +41,11 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model. 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.SubscriptionNotFoundException; -import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionRequestConversionException; +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; @@ -67,7 +66,6 @@ public class SubscriptionManager { private final String msoKeyString; private final String vnfmAdapterAuth; - @Autowired public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider, final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider, @@ -112,7 +110,6 @@ 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); } @@ -174,6 +171,10 @@ public class SubscriptionManager { 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()); @@ -186,9 +187,9 @@ public class SubscriptionManager { try { etsiCatalogManagerSubscriptionRequest = conversionService.convert(pkgmSubscriptionRequest, org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest.class); - } catch (final 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 (final Exception exception) { logger.error(exception.getMessage()); @@ -209,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/rest/EtsiSubscriptionNotificationController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationController.java index a2f44f9deb..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,27 +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) 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/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/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..5d382fd4dd 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> @@ -23,6 +23,7 @@ <module>mso-openstack-adapters</module> <module>mso-vnfm-adapter</module> <module>mso-ve-vnfm-adapter</module> + <module>mso-nssmf-adapter</module> <module>so-appc-orchestrator</module> </modules> 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> diff --git a/asdc-controller/pom.xml b/asdc-controller/pom.xml index 6ae05896df..1059e89da9 100644 --- a/asdc-controller/pom.xml +++ b/asdc-controller/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so</groupId> diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/ErrorCode.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/ErrorCode.java new file mode 100644 index 0000000000..1714e24a27 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/ErrorCode.java @@ -0,0 +1,50 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public enum ErrorCode { + + NORMAL("0"), PACKAGE_EXIST("1"), CATALOG_EXCEPTION("2"), SYSTEM_ERROR("3"), UNKNOWN("-1"); + + private String code; + + private ErrorCode(final String code) { + this.code = code; + } + + public String getCode() { + return code; + } + + public static ErrorCode getErrorCode(final String code) { + for (final ErrorCode errorCode : ErrorCode.values()) { + if (errorCode.getCode().equalsIgnoreCase(code)) { + return errorCode; + } + + } + return UNKNOWN; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboadingJobStatus.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboadingJobStatus.java new file mode 100644 index 0000000000..772f81a7fe --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboadingJobStatus.java @@ -0,0 +1,63 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlElement; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class EtsiCatalogPackageOnboadingJobStatus implements Serializable { + + private static final long serialVersionUID = 1L; + + @XmlElement(name = "jobId") + private String jobId; + + @XmlElement(name = "responseDescriptor") + private EtsiCatalogPackageOnboardingJobDescriptor responseDescriptor; + + public String getJobId() { + return jobId; + } + + public void setJobId(final String jobId) { + this.jobId = jobId; + } + + public EtsiCatalogPackageOnboardingJobDescriptor getResponseDescriptor() { + return responseDescriptor; + } + + public void setResponseDescriptor(final EtsiCatalogPackageOnboardingJobDescriptor responseDescriptor) { + this.responseDescriptor = responseDescriptor; + } + + @Override + public String toString() { + return "EtsiCatalogPackageOnboadingJobStatus [jobId=" + jobId + ", responseDescriptor=" + responseDescriptor + + "]"; + } + + + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingJob.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingJob.java new file mode 100644 index 0000000000..0c7bba6751 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingJob.java @@ -0,0 +1,49 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlElement; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class EtsiCatalogPackageOnboardingJob implements Serializable { + + private static final long serialVersionUID = 1L; + + @XmlElement(name = "jobId") + private String jobId; + + public String getJobId() { + return jobId; + } + + public void setJobId(final String jobId) { + this.jobId = jobId; + } + + @Override + public String toString() { + return "EtsiCatalogPackageOnboardingJob [jobId=" + jobId + "]"; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingJobDescriptor.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingJobDescriptor.java new file mode 100644 index 0000000000..b0c07d6f24 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingJobDescriptor.java @@ -0,0 +1,74 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlElement; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class EtsiCatalogPackageOnboardingJobDescriptor implements Serializable { + + private static final long serialVersionUID = 1L; + + @XmlElement(name = "status") + private String status; + + @XmlElement(name = "statusDescription") + private String statusDescription; + + @XmlElement(name = "errorCode") + private String errorCode; + + public String getStatus() { + return status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public String getStatusDescription() { + return statusDescription; + } + + public void setStatusDescription(final String statusDescription) { + this.statusDescription = statusDescription; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(final String errorCode) { + this.errorCode = errorCode; + } + + @Override + public String toString() { + return "EtsiCatalogPackageOnboardingJobDescriptor [status=" + status + ", statusDescription=" + + statusDescription + ", errorCode=" + errorCode + "]"; + } + + + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingRequest.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingRequest.java new file mode 100644 index 0000000000..79fd1398a0 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogPackageOnboardingRequest.java @@ -0,0 +1,54 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlElement; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class EtsiCatalogPackageOnboardingRequest implements Serializable { + + private static final long serialVersionUID = 1L; + + @XmlElement(name = "csarId") + private String csarId; + + public EtsiCatalogPackageOnboardingRequest csarId(final String csarId) { + this.csarId = csarId; + return this; + } + + public String getCsarId() { + return csarId; + } + + public void setCsarId(final String csarId) { + this.csarId = csarId; + } + + @Override + public String toString() { + return "EtsiCatalogPackageOnboardingRequest [csarId=" + csarId + "]"; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogServiceProvider.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogServiceProvider.java new file mode 100644 index 0000000000..f6a303291f --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiCatalogServiceProvider.java @@ -0,0 +1,112 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import static org.onap.so.asdc.etsi.pkg.processor.HttpRestServiceProviderConfiguration.ETSI_CATALOG_HTTP_REST_SERVICE_PROVIDER_BEAN; +import org.onap.so.asdc.etsi.pkg.processor.exceptions.EtsiCatalogManagerRequestFailureException; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class EtsiCatalogServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProvider.class); + + private final HttpRestServiceProvider httpServiceProvider; + + @Value("${etsi-catalog-manager.endpoint:http://modeling-etsicatalog.onap:8806/api/catalog/v1}") + private String etsiCatalogManagerEndpoint; + + @Autowired + public EtsiCatalogServiceProvider( + @Qualifier(ETSI_CATALOG_HTTP_REST_SERVICE_PROVIDER_BEAN) final HttpRestServiceProvider httpServiceProvider) { + this.httpServiceProvider = httpServiceProvider; + } + + public EtsiCatalogPackageOnboardingJob onBoardResource( + final EtsiCatalogPackageOnboardingRequest packageOnboardingRequest) { + try { + final String url = etsiCatalogManagerEndpoint + "/vnfpackages"; + final ResponseEntity<EtsiCatalogPackageOnboardingJob> responseEntity = httpServiceProvider.postHttpRequest( + packageOnboardingRequest, url, getHeaders(), EtsiCatalogPackageOnboardingJob.class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (responseEntity.hasBody()) { + return responseEntity.getBody(); + } + LOGGER.error("Received response without body"); + } + final String message = "Unexpected status code received " + responseEntity.getStatusCode(); + LOGGER.error(message); + throw new EtsiCatalogManagerRequestFailureException(message); + + } catch (final InvalidRestRequestException | RestProcessingException exception) { + final String message = "Unable to process onboarding request"; + LOGGER.error(message, exception); + throw new EtsiCatalogManagerRequestFailureException(message); + } + + } + + public EtsiCatalogPackageOnboadingJobStatus getJobStatus(final String jobId) { + try { + final String url = etsiCatalogManagerEndpoint + "/jobs/" + jobId; + + final ResponseEntity<EtsiCatalogPackageOnboadingJobStatus> responseEntity = + httpServiceProvider.getHttpResponse(url, getHeaders(), EtsiCatalogPackageOnboadingJobStatus.class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (responseEntity.hasBody()) { + return responseEntity.getBody(); + } + LOGGER.error("Received response without body"); + } + final String message = + "Unexpected status code received while getting job status " + responseEntity.getStatusCode(); + LOGGER.error(message); + throw new EtsiCatalogManagerRequestFailureException(message); + } catch (final InvalidRestRequestException | RestProcessingException exception) { + final String message = "Unable to get job status"; + LOGGER.error(message, exception); + throw new EtsiCatalogManagerRequestFailureException(message); + } + + } + + private HttpHeaders getHeaders() { + final HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + return headers; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiResourcePackageProcessor.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiResourcePackageProcessor.java new file mode 100644 index 0000000000..bb7197b7a4 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/EtsiResourcePackageProcessor.java @@ -0,0 +1,175 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import org.onap.so.asdc.etsi.pkg.processor.exceptions.SOL004ResourcePackageFailureException; +import org.onap.so.asdc.etsi.pkg.processor.exceptions.SOL004ResourcePackageProcessingException; +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.stereotype.Service; +import com.google.common.collect.ImmutableSet; + + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class EtsiResourcePackageProcessor { + + private final static Logger LOGGER = LoggerFactory.getLogger(EtsiResourcePackageProcessor.class); + private static final String ONBOARDED_PACKAGE_DIR_PATH = "Artifacts/Deployment/ONBOARDED_PACKAGE"; + private final SdcResourceProvider sdcResourceProvider; + private final EtsiCatalogServiceProvider catalogServiceProvider; + private static final int SLEEP_TIME_IN_SECONDS = 5; + + private static final ImmutableSet<JobStatus> JOB_FINISHED_STATES = + ImmutableSet.of(JobStatus.FINISHED, JobStatus.ERROR, JobStatus.TIMEOUT); + + @Value("${etsi-catalog-manager.rest.timeoutInSeconds:300}") + private int timeOutInSeconds; + + @Autowired + public EtsiResourcePackageProcessor(final SdcResourceProvider sdcResourceProvider, + final EtsiCatalogServiceProvider catalogServiceProvider) { + this.sdcResourceProvider = sdcResourceProvider; + this.catalogServiceProvider = catalogServiceProvider; + } + + public void processPackageIfExists(final String vnfUuid) { + LOGGER.debug("Processing vnf with UUID: {} ", vnfUuid); + try { + final Optional<byte[]> optional = sdcResourceProvider.getVnfResource(vnfUuid); + if (optional.isPresent()) { + final byte[] resourceContent = optional.get(); + + if (containsOnBoardedSol004Package(resourceContent)) { + final EtsiCatalogPackageOnboardingJob onboardingJob = catalogServiceProvider + .onBoardResource(new EtsiCatalogPackageOnboardingRequest().csarId(vnfUuid)); + LOGGER.debug("Successfully created job with id: {} to onboard vnf with UUID: {}", + onboardingJob.getJobId(), vnfUuid); + + if (onboardingJob.getJobId() == null) { + throw new SOL004ResourcePackageFailureException( + "Received invalid jobId " + onboardingJob.getJobId()); + } + + final Optional<EtsiCatalogPackageOnboadingJobStatus> jobStatusOptional = + waitForJobToFinish(onboardingJob); + + if (!jobStatusOptional.isPresent()) { + final String message = "Job status timeout reached failed to onboard vnf with UUID: " + vnfUuid; + LOGGER.debug(message, vnfUuid); + throw new SOL004ResourcePackageFailureException(message); + } + + final EtsiCatalogPackageOnboadingJobStatus onboadingJobStatus = jobStatusOptional.get(); + final JobStatus jobStatus = getJobStatus(onboadingJobStatus); + final ErrorCode errorCode = getErrorCode(onboadingJobStatus); + + LOGGER.debug("Final job status: {}, error code: {}", jobStatus, errorCode); + if (!JobStatus.FINISHED.equals(jobStatus) && !ErrorCode.PACKAGE_EXIST.equals(errorCode)) { + final String message = "Failed to onboard vnf with UUID: " + vnfUuid + " job status: " + + jobStatus + " errorCode: " + errorCode; + LOGGER.debug(message, vnfUuid); + throw new SOL004ResourcePackageFailureException(message); + } + LOGGER.debug("Successfully onboarded package in ETSI catalog .. "); + } + + } + } catch (final Exception exception) { + final String message = "Unable to process resource received from SDC"; + LOGGER.error(message, exception); + throw new SOL004ResourcePackageProcessingException(message, exception); + } + + } + + private Optional<EtsiCatalogPackageOnboadingJobStatus> waitForJobToFinish( + final EtsiCatalogPackageOnboardingJob onboardingJob) throws InterruptedException { + JobStatus currentJobStatus = null; + final long startTimeInMillis = System.currentTimeMillis(); + final long timeOutTime = startTimeInMillis + TimeUnit.SECONDS.toMillis(timeOutInSeconds); + + LOGGER.debug("Will wait till {} for {} job to finish", Instant.ofEpochMilli(timeOutTime).toString(), + onboardingJob.getJobId()); + + while (timeOutTime > System.currentTimeMillis()) { + + final EtsiCatalogPackageOnboadingJobStatus onboadingJobStatus = + catalogServiceProvider.getJobStatus(onboardingJob.getJobId()); + LOGGER.debug("Current job status {} ", onboadingJobStatus); + + currentJobStatus = getJobStatus(onboadingJobStatus); + if (JOB_FINISHED_STATES.contains(currentJobStatus)) { + return Optional.of(onboadingJobStatus); + } + + LOGGER.debug("Onboarding not finished yet, will try again in {} seconds", SLEEP_TIME_IN_SECONDS); + TimeUnit.SECONDS.sleep(SLEEP_TIME_IN_SECONDS); + + } + LOGGER.warn("Timeout current job status: {}", currentJobStatus); + return Optional.empty(); + } + + private boolean containsOnBoardedSol004Package(final byte[] resourceContent) throws IOException { + try (final ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(resourceContent))) { + ZipEntry entry; + while ((entry = zipStream.getNextEntry()) != null) { + if (entry.getName() != null && entry.getName().contains(ONBOARDED_PACKAGE_DIR_PATH)) { + LOGGER.debug("Found entry: {} that contains {} in name", entry.getName(), + ONBOARDED_PACKAGE_DIR_PATH); + return true; + } + } + + } + LOGGER.debug("Unable to find {} dir in downloaded package", ONBOARDED_PACKAGE_DIR_PATH); + return false; + } + + private JobStatus getJobStatus(final EtsiCatalogPackageOnboadingJobStatus onboadingJobStatus) { + if (onboadingJobStatus.getResponseDescriptor() != null) { + return JobStatus.getJobStatus(onboadingJobStatus.getResponseDescriptor().getStatus()); + } + LOGGER.warn("Found null ResponseDescriptor {}", onboadingJobStatus); + return JobStatus.UNKNOWN; + } + + private ErrorCode getErrorCode(final EtsiCatalogPackageOnboadingJobStatus onboadingJobStatus) { + if (onboadingJobStatus.getResponseDescriptor() != null) { + return ErrorCode.getErrorCode(onboadingJobStatus.getResponseDescriptor().getErrorCode()); + } + LOGGER.warn("Found null ResponseDescriptor {}", onboadingJobStatus); + return ErrorCode.UNKNOWN; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/HttpRestServiceProviderConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/HttpRestServiceProviderConfiguration.java new file mode 100644 index 0000000000..1afda0d29f --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/HttpRestServiceProviderConfiguration.java @@ -0,0 +1,55 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import static org.onap.so.asdc.etsi.pkg.processor.SslBasedHttpClientConfiguration.SSL_BASED_CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class HttpRestServiceProviderConfiguration { + + public static final String ETSI_CATALOG_HTTP_REST_SERVICE_PROVIDER_BEAN = "etsiCatalogHttpRestServiceProviderBean"; + public static final String SDC_HTTP_REST_SERVICE_PROVIDER_BEAN = "sdcHttpRestServiceProviderBean"; + + @Bean + @Qualifier(ETSI_CATALOG_HTTP_REST_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider etsiCataloghttpRestServiceProvider( + @Qualifier(CONFIGURABLE_REST_TEMPLATE) final RestTemplate restTemplate) { + return new HttpRestServiceProviderImpl(restTemplate); + } + + @Bean + @Qualifier(SDC_HTTP_REST_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider sdchttpRestServiceProvider( + @Qualifier(SSL_BASED_CONFIGURABLE_REST_TEMPLATE) final RestTemplate restTemplate) { + return new HttpRestServiceProviderImpl(restTemplate); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/JobStatus.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/JobStatus.java new file mode 100644 index 0000000000..cf09b15539 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/JobStatus.java @@ -0,0 +1,60 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public enum JobStatus { + + STARTED("started"), + TIMEOUT("timeout"), + FINISHED("finished"), + PARTLY_FINISHED("partly_finished"), + PROCESSING("processing"), + ERROR("error"), + UNKNOWN("unknown"); + + private String value; + + private JobStatus(final String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return this.value; + } + + public static JobStatus getJobStatus(final String jobStatus) { + for (final JobStatus status : JobStatus.values()) { + if (status.getValue().equalsIgnoreCase(jobStatus)) { + return status; + } + } + return JobStatus.UNKNOWN; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SdcBasicHttpConfigurationProvider.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SdcBasicHttpConfigurationProvider.java new file mode 100644 index 0000000000..19375e265f --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SdcBasicHttpConfigurationProvider.java @@ -0,0 +1,60 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import org.apache.commons.codec.binary.Base64; +import org.onap.so.utils.CryptoUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class SdcBasicHttpConfigurationProvider { + + @Value("${sdc.endpoint:https://sdc-be.onap:8443}") + private String endPoint; + + @Value("${sdc.username:mso}") + private String username; + + @Value(value = "${sdc.password:76966BDD3C7414A03F7037264FF2E6C8EEC6C28F2B67F2840A1ED857C0260FEE731D73F47F828E5527125D29FD25D3E0DE39EE44C058906BF1657DE77BF897EECA93BDC07FA64F}") + private String password; + + @Value(value = "${sdc.key:566B754875657232314F5548556D3665}") + private String key; + + + public String getBasicAuthorization() throws GeneralSecurityException { + final String auth = username + ":" + CryptoUtils.decrypt(password, key); + final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); + return "Basic " + new String(encodedAuth); + } + + public String getEndPoint() { + return endPoint; + } + + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SdcResourceProvider.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SdcResourceProvider.java new file mode 100644 index 0000000000..0cd0aba9c3 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SdcResourceProvider.java @@ -0,0 +1,96 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import static org.onap.so.asdc.etsi.pkg.processor.HttpRestServiceProviderConfiguration.SDC_HTTP_REST_SERVICE_PROVIDER_BEAN; +import static org.springframework.http.HttpHeaders.ACCEPT; +import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; +import java.security.GeneralSecurityException; +import java.util.Optional; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Service +public class SdcResourceProvider { + private final static Logger LOGGER = LoggerFactory.getLogger(SdcResourceProvider.class); + + private static final String SERVICE_NAME = "SO-SDC-CONTROLLER"; + + private final HttpRestServiceProvider httpRestServiceProvider; + + private final SdcBasicHttpConfigurationProvider sdcBasicHttpConfigurationProvider; + + @Autowired + public SdcResourceProvider( + @Qualifier(SDC_HTTP_REST_SERVICE_PROVIDER_BEAN) final HttpRestServiceProvider httpRestServiceProvider, + final SdcBasicHttpConfigurationProvider sdcBasicHttpConfigurationProvider) { + this.httpRestServiceProvider = httpRestServiceProvider; + this.sdcBasicHttpConfigurationProvider = sdcBasicHttpConfigurationProvider; + } + + public Optional<byte[]> getVnfResource(final String resourceId) { + LOGGER.debug("Will get resource from SDC using resource id: {}", resourceId); + try { + final HttpHeaders headers = getHttpHeaders(); + headers.add(ACCEPT, APPLICATION_OCTET_STREAM_VALUE); + final String url = getSdcResourceEndPoint(resourceId); + LOGGER.debug("will invoke url: {} to get resource ", url); + final ResponseEntity<byte[]> responseEntity = + httpRestServiceProvider.getHttpResponse(url, headers, byte[].class); + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + if (responseEntity.hasBody()) { + return Optional.of(responseEntity.getBody()); + } + LOGGER.error("Received response without body"); + } + LOGGER.error("Unexpected Status code received : {}", responseEntity.getStatusCode()); + return Optional.empty(); + } catch (final Exception exception) { + LOGGER.error("Unable to get {} resource from SDC", resourceId, exception); + return Optional.empty(); + } + } + + private String getSdcResourceEndPoint(final String resourceId) { + return sdcBasicHttpConfigurationProvider.getEndPoint() + "/sdc/v1/catalog/resources/" + resourceId + + "/toscaModel"; + } + + + private HttpHeaders getHttpHeaders() throws GeneralSecurityException { + final HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.AUTHORIZATION, sdcBasicHttpConfigurationProvider.getBasicAuthorization()); + headers.add("X-ECOMP-InstanceID", SERVICE_NAME); + headers.add("X-FromAppId", SERVICE_NAME); + return headers; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SslBasedHttpClientConfiguration.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SslBasedHttpClientConfiguration.java new file mode 100644 index 0000000000..88c21524e9 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/SslBasedHttpClientConfiguration.java @@ -0,0 +1,93 @@ +/*- + * ============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.asdc.etsi.pkg.processor; + +import java.security.NoSuchAlgorithmException; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLContext; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; +import org.onap.so.configuration.rest.HttpClientConnectionConfiguration; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class SslBasedHttpClientConfiguration { + private final static Logger LOGGER = LoggerFactory.getLogger(EtsiResourcePackageProcessor.class); + + + public static final String SSL_BASED_CONFIGURABLE_REST_TEMPLATE = "sslBasedConfigurableRestTemplate"; + private final HttpClientConnectionConfiguration clientConnectionConfiguration; + + @Autowired + public SslBasedHttpClientConfiguration(final HttpClientConnectionConfiguration clientConnectionConfiguration) { + this.clientConnectionConfiguration = clientConnectionConfiguration; + } + + @Bean + @Qualifier(SSL_BASED_CONFIGURABLE_REST_TEMPLATE) + public RestTemplate sslBasedConfigurableRestTemplate() { + final RestTemplate restTemplate = + new RestTemplate(new BufferingClientHttpRequestFactory(httpComponentsClientHttpRequestFactory())); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; + } + + private HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory() { + try { + LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with default SSL Context"); + return new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create() + .setConnectionManager(getConnectionManager()) + .setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute()) + .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections()) + .setDefaultRequestConfig(getRequestConfig()).setSSLContext(SSLContext.getDefault()).build()); + + } catch (final NoSuchAlgorithmException exception) { + LOGGER.error("Failed to create HttpComponentsClientHttpRequestFactory with default SSL Context", exception); + throw new RuntimeException(exception); + } + } + + private PoolingHttpClientConnectionManager getConnectionManager() { + return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(), + TimeUnit.MINUTES); + } + + private RequestConfig getRequestConfig() { + return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds()) + .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build(); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/EtsiCatalogManagerRequestFailureException.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/EtsiCatalogManagerRequestFailureException.java new file mode 100644 index 0000000000..4f2e5039d7 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/EtsiCatalogManagerRequestFailureException.java @@ -0,0 +1,40 @@ +/*- + * ============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.asdc.etsi.pkg.processor.exceptions; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class EtsiCatalogManagerRequestFailureException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public EtsiCatalogManagerRequestFailureException(final String message) { + super(message); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/SOL004ResourcePackageFailureException.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/SOL004ResourcePackageFailureException.java new file mode 100644 index 0000000000..8e05a50f32 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/SOL004ResourcePackageFailureException.java @@ -0,0 +1,40 @@ +/*- + * ============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.asdc.etsi.pkg.processor.exceptions; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class SOL004ResourcePackageFailureException extends RuntimeException { + + private static final long serialVersionUID = 5834657185124807797L; + + public SOL004ResourcePackageFailureException(final String message) { + super(message); + + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/SOL004ResourcePackageProcessingException.java b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/SOL004ResourcePackageProcessingException.java new file mode 100644 index 0000000000..0e9f1ea9dc --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/etsi/pkg/processor/exceptions/SOL004ResourcePackageProcessingException.java @@ -0,0 +1,34 @@ +/*- + * ============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.asdc.etsi.pkg.processor.exceptions; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class SOL004ResourcePackageProcessingException extends RuntimeException { + + private static final long serialVersionUID = 4860501744379116092L; + + public SOL004ResourcePackageProcessingException(final String message, final Throwable cause) { + super(message, cause); + + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java index 240bb83862..263118d1b3 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java @@ -39,7 +39,6 @@ import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import org.onap.so.logger.LoggingAnchor; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.LockAcquisitionException; import org.onap.sdc.api.notification.IArtifactInfo; @@ -63,6 +62,7 @@ import org.onap.sdc.toscaparser.api.parameters.Input; import org.onap.sdc.utils.DistributionStatusEnum; import org.onap.so.asdc.client.ASDCConfiguration; import org.onap.so.asdc.client.exceptions.ArtifactInstallerException; +import org.onap.so.asdc.etsi.pkg.processor.EtsiResourcePackageProcessor; import org.onap.so.asdc.installer.ASDCElementInfo; import org.onap.so.asdc.installer.BigDecimalVersion; import org.onap.so.asdc.installer.IVfModuleData; @@ -113,7 +113,6 @@ import org.onap.so.db.catalog.data.repository.CollectionResourceCustomizationRep import org.onap.so.db.catalog.data.repository.CollectionResourceRepository; import org.onap.so.db.catalog.data.repository.ConfigurationResourceCustomizationRepository; import org.onap.so.db.catalog.data.repository.ConfigurationResourceRepository; -import org.onap.so.db.catalog.data.repository.CvnfcConfigurationCustomizationRepository; import org.onap.so.db.catalog.data.repository.CvnfcCustomizationRepository; import org.onap.so.db.catalog.data.repository.ExternalServiceToInternalServiceRepository; import org.onap.so.db.catalog.data.repository.HeatEnvironmentRepository; @@ -140,6 +139,7 @@ import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatu import org.onap.so.db.request.data.repository.WatchdogDistributionStatusRepository; import org.onap.so.db.request.data.repository.WatchdogServiceModVerIdLookupRepository; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -147,9 +147,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.util.CollectionUtils; @Component public class ToscaResourceInstaller { @@ -273,6 +273,9 @@ public class ToscaResourceInstaller { @Autowired protected WorkflowResource workflowResource; + @Autowired + protected EtsiResourcePackageProcessor etsiResourcePackageProcessor; + protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class); public boolean isCsarAlreadyDeployed(ToscaResourceStructure toscaResourceStructure) @@ -456,6 +459,8 @@ public class ToscaResourceInstaller { if (ALLOTTED_RESOURCE.equalsIgnoreCase(category)) { arEntityDetails.add(vfEntityDetails); } + final String vnfUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID); + etsiResourcePackageProcessor.processPackageIfExists(vnfUuid); processVfModules(vfEntityDetails, toscaResourceStruct, vfResourceStructure, service, metadata); } diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java b/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java index e25de9c3d4..1a2e385121 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/TestApplication.java @@ -31,12 +31,14 @@ import org.springframework.context.annotation.Profile; @SpringBootApplication @Profile("test") -@ComponentScan(basePackages = {"org.onap.so.asdc", "org.onap.so.security"}, +@ComponentScan( + basePackages = {"org.onap.so.asdc", "org.onap.so.security", "org.onap.so.rest.service", + "org.onap.so.configuration.rest", "org.onap.so.client"}, excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class), @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = RequestsDBHelper.class), @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = InfraActiveRequestsRepositoryImpl.class)}) public class TestApplication { - public static void main(String... args) { + public static void main(final String... args) { SpringApplication.run(TestApplication.class, args); System.getProperties().setProperty("mso.db", "MARIADB"); System.getProperties().setProperty("server.name", "Springboot"); diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/SdcNotificationWithSol004PackageTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/SdcNotificationWithSol004PackageTest.java new file mode 100644 index 0000000000..cb5bd0f51a --- /dev/null +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/SdcNotificationWithSol004PackageTest.java @@ -0,0 +1,358 @@ +/*- + * ============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.asdc.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.ok; +import static com.github.tomakehurst.wiremock.client.WireMock.okJson; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_ERROR; +import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_OK; +import static org.springframework.http.HttpHeaders.ACCEPT; +import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.so.asdc.BaseTest; +import org.onap.so.asdc.client.exceptions.ASDCControllerException; +import org.onap.so.asdc.client.test.emulators.DistributionClientEmulator; +import org.onap.so.asdc.client.test.emulators.NotificationDataImpl; +import org.onap.so.db.catalog.data.repository.ServiceRepository; +import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; +import org.onap.so.db.request.beans.WatchdogComponentDistributionStatusId; +import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import com.google.gson.GsonBuilder; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public class SdcNotificationWithSol004PackageTest extends BaseTest { + + private final static Logger LOGGER = LoggerFactory.getLogger(SdcNotificationWithSol004PackageTest.class); + private static final String ETSI_CATALOG_PACKAGE_ONBOARDING_URL = "/api/catalog/v1/vnfpackages"; + private static final String COMPONENT_NAME = "SO"; + private static final String CSAR_ID = "8f0b72e1-b6d6-42b6-a808-c60b17f04d7a"; + private static final String SDC_GET_RESOURCE_URL = "/sdc/v1/catalog/resources/" + CSAR_ID + "/toscaModel"; + private static final String ETSI_CATALOG_PACKAGE_ONBOARDING_REQUEST = "{\"csarId\": \"" + CSAR_ID + "\"}"; + private static final String DISTRIBUTION_ID = "35f20eb9-238a-4cc2-96dc-0a08f71bc209"; + private static final String VGW_RESOURCE_PATH = "src/test/resources/resource-examples/vgw"; + private static final String SERVICE_UUID = "e051ff77-fb79-451c-8457-1cbf94e4db8f"; + private static final String SERVICE_INVARIANT_UUID = "c2ce924f-0aa1-4777-9b42-c0fec006a883"; + private static final String JOB_ID = "57c13120-0a03-4d2e-837a-7c41d61e4a30"; + private static final String ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL = "/api/catalog/v1/jobs/" + JOB_ID; + private static final String ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_RESPONSE = "{\"jobId\": \"" + JOB_ID + "\"}"; + + @Autowired + private ASDCController asdcController; + + private DistributionClientEmulator distributionClient; + + @Autowired + private WatchdogComponentDistributionStatusRepository watchdogComponentDistributionStatusRepository; + + @Autowired + protected ServiceRepository serviceRepository; + + @Before + public void setUp() { + distributionClient = new DistributionClientEmulator(); + distributionClient.setResourcePath(getAbsolutePath(VGW_RESOURCE_PATH)); + asdcController.setDistributionClient(distributionClient); + try { + asdcController.initASDC(); + } catch (final ASDCControllerException controllerException) { + LOGGER.error(controllerException.getMessage(), controllerException); + fail(controllerException.getMessage()); + } + } + + @After + public void shutDown() { + try { + if (serviceRepository.existsById(SERVICE_UUID)) { + LOGGER.debug("Deleting existing service using {} ", SERVICE_UUID); + serviceRepository.deleteById(SERVICE_UUID); + } + + final WatchdogComponentDistributionStatusId distributionId = new WatchdogComponentDistributionStatusId(); + distributionId.setDistributionId(DISTRIBUTION_ID); + distributionId.setComponentName(COMPONENT_NAME); + if (watchdogComponentDistributionStatusRepository.existsById(distributionId)) { + LOGGER.debug("Deleting existing WatchdogComponentDistributionStatus using {} ", distributionId); + watchdogComponentDistributionStatusRepository.deleteById(distributionId); + } + asdcController.closeASDC(); + } catch (final ASDCControllerException asdcControllerException) { + LOGGER.error(asdcControllerException.getMessage(), asdcControllerException); + fail(asdcControllerException.getMessage()); + } + } + + @Test + public void testTreatNotification_vgwServiceContainingSol004Package_successfullyOnboard() throws IOException { + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer.stubFor(get(SDC_GET_RESOURCE_URL) + .willReturn(aResponse().withBody(getFileContent( + Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "SDC_RESOURCE_CSAR", "vgw_sdc_resource.csar")))) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + wireMockServer.stubFor(post(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .willReturn(okJson(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_RESPONSE))); + + wireMockServer.stubFor(get(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL)) + .willReturn(okJson(new String(getFileContent(Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), + "etsi-catalog-package-onboading-job-status-successful.json")))))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_OK.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + + verify(postRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .withRequestBody(equalToJson(ETSI_CATALOG_PACKAGE_ONBOARDING_REQUEST))); + + verify(getRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL))); + } + + @Test + public void testTreatNotification_vgwServiceUnableToGeSdcResource_successfullyOnboard() throws IOException { + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer + .stubFor(get(SDC_GET_RESOURCE_URL).willReturn(aResponse().withStatus(HttpStatus.NOT_FOUND.value())) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_OK.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + } + + @Test + public void testTreatNotification_vgwServiceContainingNonEtsiSdcResource_successfullyOnboard() throws IOException { + + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer.stubFor(get(SDC_GET_RESOURCE_URL) + .willReturn(aResponse().withBody(getFileContent( + Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "service-Vgwservicev1-csar.csar")))) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_OK.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + + } + + @Test + public void testTreatNotification_vgwServiceContainingSol004Package_onnboardRequestToEtsiCatalogReturnsBadGatway_distributionStatusError() + throws IOException { + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer.stubFor(get(SDC_GET_RESOURCE_URL) + .willReturn(aResponse().withBody(getFileContent( + Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "SDC_RESOURCE_CSAR", "vgw_sdc_resource.csar")))) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + wireMockServer.stubFor(post(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .willReturn(aResponse().withStatus(HttpStatus.BAD_GATEWAY.value()))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_ERROR.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + + verify(postRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .withRequestBody(equalToJson(ETSI_CATALOG_PACKAGE_ONBOARDING_REQUEST))); + + } + + @Test + public void testTreatNotification_vgwServiceContainingSol004Package_getJobStatusReturnsBadGatway_distributionStatusError() + throws IOException { + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer.stubFor(get(SDC_GET_RESOURCE_URL) + .willReturn(aResponse().withBody(getFileContent( + Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "SDC_RESOURCE_CSAR", "vgw_sdc_resource.csar")))) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + wireMockServer.stubFor(post(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .willReturn(okJson(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_RESPONSE))); + + wireMockServer.stubFor(get(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL)) + .willReturn(aResponse().withStatus(HttpStatus.BAD_GATEWAY.value()))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_ERROR.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + + verify(postRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .withRequestBody(equalToJson(ETSI_CATALOG_PACKAGE_ONBOARDING_REQUEST))); + + verify(getRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL))); + + } + + @Test + public void testTreatNotification_vgwServiceContainingSol004Package_getJobStatusBodyWithStatusError_distributionStatusError() + throws IOException { + + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer.stubFor(get(SDC_GET_RESOURCE_URL) + .willReturn(aResponse().withBody(getFileContent( + Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "SDC_RESOURCE_CSAR", "vgw_sdc_resource.csar")))) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + wireMockServer.stubFor(post(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .willReturn(okJson(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_RESPONSE))); + + wireMockServer.stubFor(get(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL)) + .willReturn(okJson(new String(getFileContent(Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), + "etsi-catalog-package-onboading-job-status-error.json")))))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_ERROR.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + + verify(postRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .withRequestBody(equalToJson(ETSI_CATALOG_PACKAGE_ONBOARDING_REQUEST))); + + verify(getRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL))); + + + } + + @Test + public void testTreatNotification_vgwServiceContainingSol004PackageAndPackageAlreadyExistsInEtsiCatalog_successfullyOnboard() + throws IOException { + initMockAaiServer(SERVICE_UUID, SERVICE_INVARIANT_UUID); + + wireMockServer.stubFor(get(SDC_GET_RESOURCE_URL) + .willReturn(aResponse().withBody(getFileContent( + Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "SDC_RESOURCE_CSAR", "vgw_sdc_resource.csar")))) + .withHeader(ACCEPT, equalTo(APPLICATION_OCTET_STREAM_VALUE))); + + wireMockServer.stubFor(post(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .willReturn(okJson(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_RESPONSE))); + + wireMockServer.stubFor(get(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL)) + .willReturn(okJson(new String(getFileContent(Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), + "etsi-catalog-package-onboading-job-status-error-package-exists.json")))))); + + asdcController.treatNotification(getNotificationDataImplObject()); + + final List<WatchdogComponentDistributionStatus> distributionList = + watchdogComponentDistributionStatusRepository.findByDistributionId(DISTRIBUTION_ID); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + final WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals(COMPONENT_DONE_OK.toString(), distributionStatus.getComponentDistributionStatus()); + assertEquals(COMPONENT_NAME, distributionStatus.getComponentName()); + + verify(postRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_URL)) + .withRequestBody(equalToJson(ETSI_CATALOG_PACKAGE_ONBOARDING_REQUEST))); + + verify(getRequestedFor(urlEqualTo(ETSI_CATALOG_PACKAGE_ONBOARDING_JOB_STATUS_URL))); + } + + + private byte[] getFileContent(final Path path) throws IOException { + return Files.readAllBytes(path); + } + + private NotificationDataImpl getNotificationDataImplObject() throws IOException { + final Path filePath = Paths.get(getAbsolutePath(VGW_RESOURCE_PATH), "dmaap-notification-message.json"); + final byte[] bytes = Files.readAllBytes(filePath); + + return new GsonBuilder().setPrettyPrinting().create().fromJson(new String(bytes), NotificationDataImpl.class); + } + + /** + * Mock the AAI using wireshark. + */ + private void initMockAaiServer(final String serviceUuid, final String serviceInvariantUuid) { + final String modelEndpoint = "/aai/v19/service-design-and-creation/models/model/" + serviceInvariantUuid + + "/model-vers/model-ver/" + serviceUuid + "?depth=0"; + + wireMockServer.stubFor(post(urlEqualTo(modelEndpoint)).willReturn(ok())); + } + + private String getAbsolutePath(final String path) { + final File file = new File(path); + return file.getAbsolutePath(); + } +} diff --git a/asdc-controller/src/test/resources/application-test.yaml b/asdc-controller/src/test/resources/application-test.yaml index 9fa20550db..60cd2d9f2a 100644 --- a/asdc-controller/src/test/resources/application-test.yaml +++ b/asdc-controller/src/test/resources/application-test.yaml @@ -102,3 +102,11 @@ mso: endpoint: http://localhost:${wiremock.server.port} config: defaultpath: src/test/resources + +sdc: + endpoint: http://localhost:${wiremock.server.port} + +etsi-catalog-manager: + endpoint: http://localhost:${wiremock.server.port}/api/catalog/v1 + rest: + timeoutInSeconds: 5 diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/VENDOR_LICENSE/vendor-license-model.xml b/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/VENDOR_LICENSE/vendor-license-model.xml new file mode 100644 index 0000000000..6499a58fab --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/VENDOR_LICENSE/vendor-license-model.xml @@ -0,0 +1 @@ +<vendor-license-model xmlns="http://xmlns.openecomp.org/asdc/license-model/1.0"><vendor-name>VLM</vendor-name><entitlement-pool-list><entitlement-pool><entitlement-pool-invariant-uuid>d6dea4a3db6b415ba50f17cb3311d046</entitlement-pool-invariant-uuid><entitlement-pool-uuid>04B01ABDE6CA4A9FBA75ACC023C6FEDA</entitlement-pool-uuid><version>1.0</version><name>EP</name><description/><increments/><manufacturer-reference-number>2345</manufacturer-reference-number><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit/><value/></threshold-value><sp-limits/><vendor-limits/></entitlement-pool></entitlement-pool-list><license-key-group-list><license-key-group><version>1.0</version><name>LKG</name><description/><type>Unique</type><increments/><manufacturerReferenceNumber/><license-key-group-invariant-uuid>55ddeb1a87be4fbb95a9bd74b4d745ca</license-key-group-invariant-uuid><license-key-group-uuid>81117C9B092C4C70AFF76833373CE7F4</license-key-group-uuid><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit>Absolute</unit><value>23456789</value></threshold-value><sp-limits/><vendor-limits/></license-key-group></license-key-group-list></vendor-license-model>
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/VF_LICENSE/vf-license-model.xml b/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/VF_LICENSE/vf-license-model.xml new file mode 100644 index 0000000000..581a3acb7f --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/VF_LICENSE/vf-license-model.xml @@ -0,0 +1 @@ +<vf-license-model xmlns="http://xmlns.openecomp.org/asdc/license-model/1.0"><vendor-name>VLM</vendor-name><vf-id>fa87b9536b704787981357393f36b3fc</vf-id><feature-group-list><feature-group><entitlement-pool-list><entitlement-pool><name>EP</name><description/><increments/><entitlement-pool-invariant-uuid>d6dea4a3db6b415ba50f17cb3311d046</entitlement-pool-invariant-uuid><entitlement-pool-uuid>04B01ABDE6CA4A9FBA75ACC023C6FEDA</entitlement-pool-uuid><manufacturer-reference-number>2345</manufacturer-reference-number><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit/><value/></threshold-value><version>1.0</version><sp-limits/><vendor-limits/></entitlement-pool></entitlement-pool-list><license-key-group-list><license-key-group><name>LKG</name><description/><type>Unique</type><increments/><license-key-group-invariant-uuid>55ddeb1a87be4fbb95a9bd74b4d745ca</license-key-group-invariant-uuid><license-key-group-uuid>81117C9B092C4C70AFF76833373CE7F4</license-key-group-uuid><manufacturer-reference-number/><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit>Absolute</unit><value>23456789</value></threshold-value><version>1.0</version><sp-limits/><vendor-limits/></license-key-group></license-key-group-list><name>FG</name><feature-group-uuid>2218d90f94944a94952be83354847631</feature-group-uuid><description/><part-number>234594</part-number></feature-group></feature-group-list></vf-license-model>
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/vgw6.csar b/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/vgw6.csar Binary files differnew file mode 100644 index 0000000000..56dbb2bce0 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/ONBOARDED_PACKAGE/vgw6.csar diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/SDC_RESOURCE_CSAR/vgw_sdc_resource.csar b/asdc-controller/src/test/resources/resource-examples/vgw/SDC_RESOURCE_CSAR/vgw_sdc_resource.csar Binary files differnew file mode 100644 index 0000000000..7ddfb6ef51 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/SDC_RESOURCE_CSAR/vgw_sdc_resource.csar diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/VENDOR_LICENSE/vendor-license-model.xml b/asdc-controller/src/test/resources/resource-examples/vgw/VENDOR_LICENSE/vendor-license-model.xml new file mode 100644 index 0000000000..6499a58fab --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/VENDOR_LICENSE/vendor-license-model.xml @@ -0,0 +1 @@ +<vendor-license-model xmlns="http://xmlns.openecomp.org/asdc/license-model/1.0"><vendor-name>VLM</vendor-name><entitlement-pool-list><entitlement-pool><entitlement-pool-invariant-uuid>d6dea4a3db6b415ba50f17cb3311d046</entitlement-pool-invariant-uuid><entitlement-pool-uuid>04B01ABDE6CA4A9FBA75ACC023C6FEDA</entitlement-pool-uuid><version>1.0</version><name>EP</name><description/><increments/><manufacturer-reference-number>2345</manufacturer-reference-number><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit/><value/></threshold-value><sp-limits/><vendor-limits/></entitlement-pool></entitlement-pool-list><license-key-group-list><license-key-group><version>1.0</version><name>LKG</name><description/><type>Unique</type><increments/><manufacturerReferenceNumber/><license-key-group-invariant-uuid>55ddeb1a87be4fbb95a9bd74b4d745ca</license-key-group-invariant-uuid><license-key-group-uuid>81117C9B092C4C70AFF76833373CE7F4</license-key-group-uuid><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit>Absolute</unit><value>23456789</value></threshold-value><sp-limits/><vendor-limits/></license-key-group></license-key-group-list></vendor-license-model>
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/VF_LICENSE/vf-license-model.xml b/asdc-controller/src/test/resources/resource-examples/vgw/VF_LICENSE/vf-license-model.xml new file mode 100644 index 0000000000..581a3acb7f --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/VF_LICENSE/vf-license-model.xml @@ -0,0 +1 @@ +<vf-license-model xmlns="http://xmlns.openecomp.org/asdc/license-model/1.0"><vendor-name>VLM</vendor-name><vf-id>fa87b9536b704787981357393f36b3fc</vf-id><feature-group-list><feature-group><entitlement-pool-list><entitlement-pool><name>EP</name><description/><increments/><entitlement-pool-invariant-uuid>d6dea4a3db6b415ba50f17cb3311d046</entitlement-pool-invariant-uuid><entitlement-pool-uuid>04B01ABDE6CA4A9FBA75ACC023C6FEDA</entitlement-pool-uuid><manufacturer-reference-number>2345</manufacturer-reference-number><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit/><value/></threshold-value><version>1.0</version><sp-limits/><vendor-limits/></entitlement-pool></entitlement-pool-list><license-key-group-list><license-key-group><name>LKG</name><description/><type>Unique</type><increments/><license-key-group-invariant-uuid>55ddeb1a87be4fbb95a9bd74b4d745ca</license-key-group-invariant-uuid><license-key-group-uuid>81117C9B092C4C70AFF76833373CE7F4</license-key-group-uuid><manufacturer-reference-number/><operational-scope><value/></operational-scope><start-date/><expiry-date/><threshold-value><unit>Absolute</unit><value>23456789</value></threshold-value><version>1.0</version><sp-limits/><vendor-limits/></license-key-group></license-key-group-list><name>FG</name><feature-group-uuid>2218d90f94944a94952be83354847631</feature-group-uuid><description/><part-number>234594</part-number></feature-group></feature-group-list></vf-license-model>
\ No newline at end of file diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/dmaap-notification-message.json b/asdc-controller/src/test/resources/resource-examples/vgw/dmaap-notification-message.json new file mode 100644 index 0000000000..d936cd1144 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/dmaap-notification-message.json @@ -0,0 +1,66 @@ +{ + "distributionID": "35f20eb9-238a-4cc2-96dc-0a08f71bc209", + "serviceName": "VgwServiceV1", + "serviceVersion": "1.0", + "serviceUUID": "e051ff77-fb79-451c-8457-1cbf94e4db8f", + "serviceDescription": "Test VGW Service", + "serviceInvariantUUID": "c2ce924f-0aa1-4777-9b42-c0fec006a883", + "resources": [ + { + "resourceInstanceName": "VgwVspV1 0", + "resourceName": "VgwVspV1", + "resourceVersion": "1.0", + "resourceType": "VF", + "resourceUUID": "655aa939-d589-4333-8cc6-8fcb15db858a", + "resourceInvariantUUID": "c53a0c91-35f6-40ff-bcda-f75030cfaf2d", + "resourceCustomizationUUID": "db1673e1-351a-4d04-8e2f-84b2b4c52cc7", + "category": "Generic", + "subcategory": "Network Service", + "artifacts": [ + { + "artifactName": "vf-license-model.xml", + "artifactType": "VF_LICENSE", + "artifactURL": "/VF_LICENSE/vf-license-model.xml", + "artifactChecksum": "NjMwZDc0YzhiNDRlZDAyYjIxMmFlM2M0MWRkZjFmNDA\u003d", + "artifactDescription": "VF license file", + "artifactTimeout": 120, + "artifactUUID": "8dda263d-90bb-4b3d-b8e0-0048222dc658", + "artifactVersion": "1" + }, + { + "artifactName": "vgw6.csar", + "artifactType": "ONBOARDED_PACKAGE", + "artifactURL": "/ONBOARDED_PACKAGE/vgw6.csar", + "artifactChecksum": "NjdmNGU3ZDlkODQ0YTUzMTU5NjZmOThiYjMxNTJiNGI\u003d", + "artifactDescription": "Artifact created from csar", + "artifactTimeout": 120, + "artifactUUID": "9e9930b8-898e-4b8b-999e-66c43e1611f4", + "artifactVersion": "1" + }, + { + "artifactName": "vendor-license-model.xml", + "artifactType": "VENDOR_LICENSE", + "artifactURL": "/VENDOR_LICENSE/vendor-license-model.xml", + "artifactChecksum": "NGNmNzU4MDhjN2FjMTJkNWIxMjNkZDZhOWQyYzU0ZjA\u003d", + "artifactDescription": " Vendor license file", + "artifactTimeout": 120, + "artifactUUID": "b3f7a4cf-6a35-4f66-b800-cd4a9a0e9719", + "artifactVersion": "1" + } + ] + } + ], + "serviceArtifacts": [ + { + "artifactName": "service-Vgwservicev1-csar.csar", + "artifactType": "TOSCA_CSAR", + "artifactURL": "/service-Vgwservicev1-csar.csar", + "artifactChecksum": "MzcxNTMwMDhmNGY0MjRkMjFkNzk1MDNjOTVhNjQzMmE\u003d", + "artifactDescription": "TOSCA definition package of the asset", + "artifactTimeout": 0, + "artifactUUID": "0cc70c6e-6ddc-4ecc-8052-d9f1433c14b8", + "artifactVersion": "1" + } + ], + "workloadContext": "Production" +} diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-error-package-exists.json b/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-error-package-exists.json new file mode 100644 index 0000000000..8dc07b9613 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-error-package-exists.json @@ -0,0 +1,20 @@ +{ + "jobId": "57c13120-0a03-4d2e-837a-7c41d61e4a30", + "responseDescriptor": + { + "status": "error", + "progress": "255", + "statusDescription": "VNF package() already exists.", + "errorCode": "1", + "responseId": "2", + "responseHistoryList": [ + { + "status": "processing", + "progress": "5", + "statusDescription": "Start CSAR(8f0b72e1-b6d6-42b6-a808-c60b17f04d7a) distribute.", + "errorCode": "0", + "responseId": "1" + } + ] + } +} diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-error.json b/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-error.json new file mode 100644 index 0000000000..13f346fb7a --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-error.json @@ -0,0 +1,20 @@ +{ + "jobId": "57c13120-0a03-4d2e-837a-7c41d61e4a30", + "responseDescriptor": + { + "status": "error", + "progress": "255", + "statusDescription": "Failed to query artifacts(resources) from sdc.", + "errorCode": "0", + "responseId": "2", + "responseHistoryList": [ + { + "status": "processing", + "progress": "5", + "statusDescription": "Start CSAR(8f0b72e1-b6d6-42b6-a808-c60b17f04d7a) distribute.", + "errorCode": "0", + "responseId": "1" + } + ] + } +} diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-successful.json b/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-successful.json new file mode 100644 index 0000000000..b5dc1fe4f2 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/etsi-catalog-package-onboading-job-status-successful.json @@ -0,0 +1,27 @@ +{ + "jobId": "57c13120-0a03-4d2e-837a-7c41d61e4a30", + "responseDescriptor": + { + "status": "finished", + "progress": "100", + "statusDescription": "CSAR(8f0b72e1-b6d6-42b6-a808-c60b17f04d7a) distribute successfully.", + "errorCode": "0", + "responseId": "3", + "responseHistoryList": [ + { + "status": "processing", + "progress": "30", + "statusDescription": "Save CSAR(8f0b72e1-b6d6-42b6-a808-c60b17f04d7a) to database.", + "errorCode": "0", + "responseId": "2" + }, + { + "status": "processing", + "progress": "5", + "statusDescription": "Start CSAR(8f0b72e1-b6d6-42b6-a808-c60b17f04d7a) distribute.", + "errorCode": "0", + "responseId": "1" + } + ] + } +} diff --git a/asdc-controller/src/test/resources/resource-examples/vgw/service-Vgwservicev1-csar.csar b/asdc-controller/src/test/resources/resource-examples/vgw/service-Vgwservicev1-csar.csar Binary files differnew file mode 100644 index 0000000000..51a9e19466 --- /dev/null +++ b/asdc-controller/src/test/resources/resource-examples/vgw/service-Vgwservicev1-csar.csar diff --git a/bpmn/MSOCommonBPMN/pom.xml b/bpmn/MSOCommonBPMN/pom.xml index e233e6a7c6..c817874fb6 100644 --- a/bpmn/MSOCommonBPMN/pom.xml +++ b/bpmn/MSOCommonBPMN/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>MSOCommonBPMN</artifactId> <name>MSOCommonBPMN</name> diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RequestDBUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RequestDBUtil.groovy new file mode 100644 index 0000000000..ce474fa713 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/RequestDBUtil.groovy @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2019, CMCC Technologies Co., Ltd. + # + # Licensed under the Apache License, Version 2.0 (the "License") + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.common.scripts + +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.db.request.beans.OperationStatus +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import org.springframework.web.util.UriUtils + +class RequestDBUtil { + private static final Logger logger = LoggerFactory.getLogger( RequestDBUtil.class); + private ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * update operation status in requestDB + * @param execution + * @param operationStatus + */ + void prepareUpdateOperationStatus(DelegateExecution execution, final OperationStatus operationStatus){ + logger.debug("start prepareUpdateOperationStatus") + try{ + def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution) + execution.setVariable("dbAdapterEndpoint", dbAdapterEndpoint) + logger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + String serviceId = operationStatus.getServiceId() + serviceId = UriUtils.encode(serviceId,"UTF-8") + String operationId = operationStatus.getOperationId() + String userId = operationStatus.getUserId() + String operationType = operationStatus.getOperation() + String result = operationStatus.getResult() + String progress = operationStatus.getProgress() + String operationContent = operationStatus.getOperationContent() + String reason = operationStatus.getReason() + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope> + """ + execution.setVariable("updateOperationStatus", payload) + + }catch(any){ + String exceptionMessage = "Prepare update ServiceOperationStatus failed. cause - " + any.getMessage() + logger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + logger.trace("finished update OperationStatus") + } + + + /** + * get operation status from requestDB by serviceId and operationId + * @param execution + * @param serviceId + * @param operationId + */ + void getOperationStatus(DelegateExecution execution, String serviceId, String operationId) { + logger.trace("start getOperationStatus") + try { + def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution) + execution.setVariable("dbAdapterEndpoint", dbAdapterEndpoint) + logger.trace("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + serviceId = UriUtils.encode(serviceId,"UTF-8") + operationId = UriUtils.encode(operationId,"UTF-8") + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:getServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + </ns:getServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope> + """ + execution.setVariable("getOperationStatus", payload) + + } catch(any){ + String exceptionMessage = "Get ServiceOperationStatus failed. cause - " + any.getMessage() + logger.error(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java index ec7b613727..e004e10cf0 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java @@ -24,6 +24,7 @@ package org.onap.so.bpmn.servicedecomposition.tasks; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; @@ -398,68 +399,37 @@ public class BBInputSetupUtils { } public Configuration getAAIConfiguration(String configurationId) { - return this.injectionHelper.getAaiClient() - .get(Configuration.class, - AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configurationId).depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("No Configuration matched by id"); - return null; - }); + return this.getConcreteAAIResource(Configuration.class, AAIObjectType.CONFIGURATION, configurationId); } public GenericVnf getAAIGenericVnf(String vnfId) { - - return this.injectionHelper.getAaiClient() - .get(GenericVnf.class, - AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("No Generic Vnf matched by id"); - return null; - }); + return getConcreteAAIResource(GenericVnf.class, AAIObjectType.GENERIC_VNF, vnfId); } public VpnBinding getAAIVpnBinding(String vpnBindingId) { - - return this.injectionHelper.getAaiClient() - .get(VpnBinding.class, - AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId).depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("No VpnBinding matched by id"); - return null; - }); + return getConcreteAAIResource(VpnBinding.class, AAIObjectType.VPN_BINDING, vpnBindingId); } public VolumeGroup getAAIVolumeGroup(String cloudOwnerId, String cloudRegionId, String volumeGroupId) { - return this.injectionHelper.getAaiClient() - .get(VolumeGroup.class, AAIUriFactory - .createResourceUri(AAIObjectType.VOLUME_GROUP, cloudOwnerId, cloudRegionId, volumeGroupId) - .depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("No Generic Vnf matched by id"); - return null; - }); + return getConcreteAAIResource(VolumeGroup.class, AAIObjectType.VOLUME_GROUP, cloudOwnerId, cloudRegionId, + volumeGroupId); } public VfModule getAAIVfModule(String vnfId, String vfModuleId) { - return this.injectionHelper.getAaiClient() - .get(VfModule.class, - AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId).depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("No Generic Vnf matched by id"); - return null; - }); + return getConcreteAAIResource(VfModule.class, AAIObjectType.VF_MODULE, vnfId, vfModuleId); } public L3Network getAAIL3Network(String networkId) { + return getConcreteAAIResource(L3Network.class, AAIObjectType.L3_NETWORK, networkId); + } - return this.injectionHelper.getAaiClient() - .get(L3Network.class, - AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE)) - .orElseGet(() -> { - logger.debug("No Generic Vnf matched by id"); + private <T> T getConcreteAAIResource(Class<T> clazz, AAIObjectType objectType, Object... ids) { + return injectionHelper.getAaiClient() + .get(clazz, AAIUriFactory.createResourceUri(objectType, ids).depth(Depth.ONE)).orElseGet(() -> { + logger.debug("No resource of type: {} matched by ids: {}", objectType.typeName(), + Arrays.toString(ids)); return null; }); - } public Optional<ServiceInstance> getRelatedServiceInstanceFromInstanceGroup(String instanceGroupId) diff --git a/bpmn/MSOCoreBPMN/pom.xml b/bpmn/MSOCoreBPMN/pom.xml index fd239562e2..47254e75f2 100644 --- a/bpmn/MSOCoreBPMN/pom.xml +++ b/bpmn/MSOCoreBPMN/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>MSOCoreBPMN</artifactId> diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceArtifact.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceArtifact.java new file mode 100644 index 0000000000..aefd70ff89 --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/domain/ServiceArtifact.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2019, CMCC Technologies Co., Ltd. + # + # Licensed under the Apache License, Version 2.0 (the "License") + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.core.domain; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonRootName; +import java.io.Serializable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"artifactUUID", "name", "version", "checksum", "type", "content", "description"}) +@JsonRootName("serviceArtifact") +public class ServiceArtifact extends JsonWrapper implements Serializable { + + private static final long serialVersionUID = 1L; + @JsonProperty("artifactUUID") + private String artifactUUID; + @JsonProperty("name") + private String name; + @JsonProperty("version") + private String version; + @JsonProperty("checksum") + private String checksum; + @JsonProperty("type") + private String type; + @JsonProperty("content") + private String content; + @JsonProperty("description") + private String description; + + @JsonProperty("artifactUUID") + public String getArtifactUUID() { + return artifactUUID; + } + + @JsonProperty("artifactUUID") + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + @JsonProperty("name") + public String getName() { + return name; + } + + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + @JsonProperty("version") + public String getVersion() { + return version; + } + + @JsonProperty("version") + public void setVersion(String version) { + this.version = version; + } + + @JsonProperty("checksum") + public String getChecksum() { + return checksum; + } + + @JsonProperty("checksum") + public void setChecksum(String checksum) { + this.checksum = checksum; + } + + @JsonProperty("type") + public String getType() { + return type; + } + + @JsonProperty("type") + public void setType(String type) { + this.type = type; + } + + @JsonProperty("content") + public String getContent() { + return content; + } + + @JsonProperty("content") + public void setContent(String content) { + this.content = content; + } + + @JsonProperty("description") + public String getDescription() { + return description; + } + + @JsonProperty("description") + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/bpmn/mso-infrastructure-bpmn/pom.xml b/bpmn/mso-infrastructure-bpmn/pom.xml index c3c26ef5e7..04a291af8c 100644 --- a/bpmn/mso-infrastructure-bpmn/pom.xml +++ b/bpmn/mso-infrastructure-bpmn/pom.xml @@ -3,7 +3,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mso-infrastructure-bpmn</artifactId> diff --git a/bpmn/pom.xml b/bpmn/pom.xml index 65af2fd8d5..6b81bab4df 100644 --- a/bpmn/pom.xml +++ b/bpmn/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>bpmn</artifactId> diff --git a/bpmn/so-bpmn-building-blocks/pom.xml b/bpmn/so-bpmn-building-blocks/pom.xml index a867613890..52c5502b32 100644 --- a/bpmn/so-bpmn-building-blocks/pom.xml +++ b/bpmn/so-bpmn-building-blocks/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>so-bpmn-building-blocks</artifactId> diff --git a/bpmn/so-bpmn-infrastructure-common/pom.xml b/bpmn/so-bpmn-infrastructure-common/pom.xml index 74df3a2c2e..0df3fbe704 100644 --- a/bpmn/so-bpmn-infrastructure-common/pom.xml +++ b/bpmn/so-bpmn-infrastructure-common/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>so-bpmn-infrastructure-common</artifactId> diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy new file mode 100644 index 0000000000..dc33bc930a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateCommunicationService.groovy @@ -0,0 +1,435 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2019, CMCC Technologies Co., Ltd. + # + # Licensed under the Apache License, Version 2.0 (the "License") + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.Relationship +import org.onap.aai.domain.yang.RelationshipData +import org.onap.aai.domain.yang.RelationshipList +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.RequestDBUtil +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.db.request.beans.OperationStatus +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +import javax.ws.rs.NotFoundException + +import static org.apache.commons.lang3.StringUtils.isBlank + +class ActivateCommunicationService extends AbstractServiceTaskProcessor { + + String Prefix="ACS_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + RequestDBUtil requestDBUtil = new RequestDBUtil() + + JsonUtils jsonUtil = new JsonUtils() + + AAIResourcesClient client = getAAIClient() + + private static final Logger logger = LoggerFactory.getLogger(ActivateCommunicationService.class) + + @Override + void preProcessRequest(DelegateExecution execution) { + logger.debug(Prefix + "preProcessRequest Start") + execution.setVariable("prefix", Prefix) + String msg + + try { + // check for incoming json message/input + String siRequest = execution.getVariable("bpmnRequest") + logger.debug(siRequest) + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + logger.info("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + logger.info(msg) + execution.setVariable("globalSubscriberId", "5GCustomer") + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + logger.debug(msg) + execution.setVariable("subscriptionServiceType", "5G") + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + String operationId = jsonUtil.getJsonValue(siRequest, "operationId") + execution.setVariable("operationId", operationId) + + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + msg = "Exception in preProcessRequest " + ex.getMessage() + logger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + logger.debug(Prefix + "preProcessRequest Exit") + } + + + def checkAAIOrchStatus = { DelegateExecution execution -> + + logger.debug(Prefix + "checkAAIOrchStatus Start") + + String msg + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + String operationType = execution.getVariable("operationType") + + logger.debug("serviceInstanceId: " + serviceInstanceId) + + //check the cms status + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, + globalSubscriberId, subscriptionServiceType, serviceInstanceId) + + if (!client.exists(uri)) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai") + } + + AAIResultWrapper wrapper = client.get(uri, NotFoundException.class) + Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class) + if(si.isPresent()) { + + if (si.get().getOrchestrationStatus().toLowerCase() == "activated" && + operationType == "deactivation") { + logger.info("Service is in active state") + execution.setVariable("serviceExpectStatus", "deactivated") + execution.setVariable("isContinue", "true") + execution.setVariable("requestParam", "deactivate") + + } else if (si.get().getOrchestrationStatus().toLowerCase() == "deactivated" && + operationType == "activation"){ + logger.info("Service is in de-activated state") + execution.setVariable("serviceExpectStatus", "activated") + execution.setVariable("isContinue", "true") + execution.setVariable("requestParam", "activate") + + } else { + execution.setVariable("isContinue", "false") + } + + RelationshipList relationshipList = si.get().getRelationshipList() + List<Relationship> relationship + if (relationshipList != null && (relationship = relationshipList.getRelationship()) != null + && relationship.size() > 0) { + List<RelationshipData> relationshipDatas = relationship.get(0).getRelationshipData() + + for (RelationshipData relationshipData : relationshipDatas) { + execution.setVariable("e2e_" + relationshipData.getRelationshipKey(), + relationshipData.getRelationshipValue()) + } + } else { + msg = "the communication service has no e2e service" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + } + + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + msg = "Exception in " + Prefix + "checkAAIOrchStatus: " + ex.getMessage() + logger.info( msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + logger.debug(Prefix + "checkAAIOrchStatus Exit") + } + + + def prepareInitOperationStatus = { DelegateExecution execution -> + logger.debug(Prefix + "prepareInitOperationStatus Start") + + String serviceId = execution.getVariable("serviceInstanceId") + + // 生成 operationId + String operationId = execution.getVariable("operationId") + + String operationType = execution.getVariable("operationType") + + OperationStatus initStatus = new OperationStatus() + initStatus.setServiceId(serviceId) + initStatus.setOperationId(operationId) + initStatus.setOperation(operationType) + initStatus.setUserId(execution.getVariable("globalSubscriberId") as String) + initStatus.setResult("processing") + initStatus.setProgress("0") + initStatus.setReason("") + initStatus.setOperationContent("communication service active operation start") + + requestDBUtil.prepareUpdateOperationStatus(execution, initStatus) + + logger.debug(Prefix + "prepareInitOperationStatus Exit") + } + + + def sendSyncResponse = { DelegateExecution execution -> + logger.debug(Prefix + "sendSyncResponse Start") + try { + String operationId = execution.getVariable("operationId") + + String restRequest = """{"operationId":"${operationId}"}""".trim() + logger.debug(" sendSyncResponse to APIH:" + "\n" + restRequest) + + sendWorkflowResponse(execution, 202, restRequest) + execution.setVariable("sentSyncResponse", true) + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + logger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + logger.debug(Prefix + "sendSyncResponse Exit") + } + + + def preRequestSend2NSMF = { DelegateExecution execution -> + logger.debug(Prefix + "preRequestSend2NSMF Start") + try { + + String e2eServiceInstanceId = execution.getVariable("e2e_service-instance.service-instance-id") + execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId) + + String requestParam = execution.getVariable("requestParam") + //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3" + def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) + def url = NSMF_endpoint + "/e2eServiceInstances/v3/${e2eServiceInstanceId}/${requestParam}" + execution.setVariable("NSMF_endpoint", url) + + //get from model catalog inputs + String payload = """ + { + "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}", + "serviceType": "${execution.getVariable("subscriptionServiceType")}" + } + """ + execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", "")) + + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + String msg = "Exception in " + Prefix + "preRequestSend2NSMF. " + ex.getMessage() + logger.error(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + logger.debug(Prefix + "preRequestSend2NSMF Exit") + } + + + def processNSMFResponse = { DelegateExecution execution -> + logger.debug(Prefix + "processNSMFResponse Start") + //oof + try { + def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer + if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) { + def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String + def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "operationId") + + execution.setVariable("e2eOperationId", e2eOperationId) + execution.setVariable("ProcessNsmfSuccess", "OK") + } else { + execution.setVariable("ProcessNsmfSuccess", "ERROR") + execution.setVariable("operationStatus", "error") + execution.setVariable("operationContent", + "communication service " + execution.getVariable("operationType") + + " operation error: nsmf response fail") + execution.setVariable("orchestrationStatus", "error") + } + + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage() + logger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + logger.debug(Prefix + "processNSMFResponse Exit") + } + + + def prepareUpdateOperationStatus = { DelegateExecution execution -> + logger.debug(Prefix + "prepareUpdateOperationStatus Start") + // update status creating + OperationStatus status = new OperationStatus() + status.setServiceId(execution.getVariable("serviceInstanceId") as String) + status.setOperationId(execution.getVariable("operationId") as String) + status.setOperation(execution.getVariable("operationType") as String) + status.setResult("processing") + status.setProgress("20") + status.setOperationContent("communication service "+ execution.getVariable("operationType") + + " operation processing: waiting nsmf service create finished") + status.setUserId(execution.getVariable("globalSubscriberId") as String) + + requestDBUtil.prepareUpdateOperationStatus(execution, status) + logger.debug(Prefix + "prepareUpdateOperationStatus Exit") + } + + + //todo + def prepareCallCheckProcessStatus = { DelegateExecution execution -> + logger.debug(Prefix + "prepareCallCheckProcessStatus Start") + + def successConditions = new ArrayList<>() + successConditions.add("finished") + execution.setVariable("successConditions", successConditions) + + def errorConditions = new ArrayList<>() + errorConditions.add("error") + execution.setVariable("errorConditions", errorConditions) + + execution.setVariable("processServiceType", "communication service") + + execution.setVariable("timeOut", 3 * 60 * 60 * 1000) + + def successParamMap = new HashMap<String, Object>() + successParamMap.put("orchestrationStatus", execution.getVariable("serviceExpectStatus")) + + execution.setVariable("successParamMap", successParamMap) + + def errorParamMap = new HashMap<String, Object>() + errorParamMap.put("orchestrationStatus", "error") + + execution.setVariable("errorParamMap", errorParamMap) + + def timeOutParamMap = new HashMap<String, Object>() + timeOutParamMap.put("orchestrationStatus", "error") + + execution.setVariable("timeOutParamMap", timeOutParamMap) + + execution.setVariable("initProgress", 20) + execution.setVariable("endProgress", 90) + + logger.debug(Prefix + "prepareCallCheckProcessStatus Exit") + } + + + /** + * prepare update operation status to complete after NSMF process success + * @param execution + */ + def prepareCompleteStatus = { DelegateExecution execution -> + + logger.debug(Prefix + "prepareCompleteStatus Start") + String operationType = execution.getVariable("operationType") + OperationStatus status = new OperationStatus() + status.setServiceId(execution.getVariable("serviceInstanceId") as String) + status.setOperationId(execution.getVariable("operationId") as String) + status.setOperation(operationType) + status.setResult(execution.getVariable("operationStatus") as String) + status.setProgress("100") + status.setOperationContent(execution.getVariable("operationContent") as String) + status.setUserId(execution.getVariable("globalSubscriberId") as String) + + requestDBUtil.prepareUpdateOperationStatus(execution, status) + logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId") + + ", operationId: " + execution.getVariable("operationId")) + + logger.debug(Prefix + "prepareCompleteStatus Exit") + } + + + /** + * update NSMF complete status to AAI when the NSMF process finished + * @param execution + */ + def updateFinishStatusInAAI = { DelegateExecution execution -> + logger.debug(Prefix + "updateFinishStatusInAAI Start") + String msg + try { + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String orchestrationStatus = execution.getVariable("orchestrationStatus") + // create service + ServiceInstance csi = new ServiceInstance() + csi.setOrchestrationStatus(orchestrationStatus) + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, + globalSubscriberId, subscriptionServiceType, serviceInstanceId) + client.update(uri, csi) + + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + msg = "Exception in complete communication service " + ex.getMessage() + logger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + logger.debug(Prefix + "updateFinishStatusInAAI Exit") + } + + + public sendSyncError = { DelegateExecution execution -> + logger.debug("sendSyncError Start") + try { + String errorMessage + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildWorkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + logger.debug(buildWorkflowException) + sendWorkflowResponse(execution, 500, buildWorkflowException) + + } catch (Exception ex) { + logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + logger.debug(Prefix + "sendSyncError Exit") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy new file mode 100644 index 0000000000..3233bfff61 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatus.groovy @@ -0,0 +1,333 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2019, CMCC Technologies Co., Ltd. + # + # Licensed under the Apache License, Version 2.0 (the "License") + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.RequestDBUtil +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.db.request.beans.OperationStatus +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +import java.util.concurrent.TimeUnit + +import static org.apache.commons.lang3.StringUtils.isBlank + +class CheckServiceProcessStatus extends AbstractServiceTaskProcessor { + + + String Prefix="CSPS_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + RequestDBUtil requestDBUtil = new RequestDBUtil() + + JsonUtils jsonUtil = new JsonUtils() + + AAIResourcesClient client = getAAIClient() + + private static final Logger logger = LoggerFactory.getLogger(CheckServiceProcessStatus.class) + + @Override + void preProcessRequest(DelegateExecution execution) { + logger.debug(Prefix + "CheckServiceProcessStatus preProcessRequest Start") + execution.setVariable("prefix", Prefix) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId") + String parentOperationId = execution.getVariable("parentOperationId") + + if (isBlank(serviceInstanceId) || isBlank(operationId)) { + String msg = "Exception in" + Prefix + "preProcessRequest: Input serviceInstanceId or operationId is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (isBlank(parentServiceInstanceId) || isBlank(parentOperationId)) { + execution.setVariable("isNeedUpdateParentStatus", false) + } + + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if (isBlank(globalSubscriberId)) { + execution.setVariable("globalSubscriberId", "5GCustomer") + } + + // serviceType: type of service + String serviceType = execution.getVariable("processServiceType") + if (isBlank(serviceType)) { + execution.setVariable("processServiceType", "service") + } + + // operationType: type of service + String operationType = execution.getVariable("operationType") + if (isBlank(operationType)) { + execution.setVariable("operationType", "CREATE") + } + + //successConditions: processing end success conditions + List<String> successConditions = execution.getVariable("successConditions") as List + + //errorConditions: processing end error conditions + List<String> errorConditions = execution.getVariable("errorConditions") as List + + if ((successConditions == null || successConditions.size() < 1) + && (errorConditions == null || errorConditions.size() < 1)) { + String msg = "Exception in" + Prefix + "preProcessRequest: conditions is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + for (int i = 0; i < successConditions.size(); i++) { + String condition = successConditions.get(i) + successConditions.set(i, condition.toLowerCase()) + } + for (int i = 0; i < errorConditions.size(); i++) { + String condition = errorConditions.get(i) + errorConditions.set(i, condition.toLowerCase()) + } + } + + execution.setVariable("startTime", System.currentTimeMillis()) + + String initProgress = execution.getVariable("initProgress") + + if (isBlank(initProgress)) { + execution.setVariable("initProgress", 0) + } + + String endProgress = execution.getVariable("endProgress") + + if (isBlank(endProgress)) { + execution.setVariable("endProgress", 100) + } + + execution.setVariable("progress", 0) + logger.debug(Prefix + "preProcessRequest Exit") + } + + + /** + * check service status through request operation id, update operation status + */ + def preCheckServiceStatusReq = { DelegateExecution execution -> + logger.trace(Prefix + "preCheckServiceStatusReq Start") + String serviceInstanceId = execution.getVariable("serviceInstanceId") as String + String operationId = execution.getVariable("operationId") as String + requestDBUtil.getOperationStatus(execution, serviceInstanceId, operationId) + logger.trace(Prefix + "preCheckServiceStatusReq Exit") + } + + + /** + * handle service status, if service status is finished or error, set the service status + * @param execution + */ + def handlerServiceStatusResp = { DelegateExecution execution -> + logger.trace(Prefix + "handlerServiceStatusResp Start") + String msg + try { + def dbResponseCode = execution.getVariable("dbResponseCode") as Integer + if (dbResponseCode >= 200 && dbResponseCode < 400) { + String dbResponse = execution.getVariable("dbResponse") + def dbResponseJson = jsonUtil.xml2json(dbResponse) as String + + String result = jsonUtil.getJsonValue(dbResponseJson, + "Envelope.Body.getServiceOperationStatusResponse.return.result") + + if (isSuccessCompleted(execution, result)) { + + handlerSuccess(execution, result) + execution.setVariable("isAllFinished", "true") + + logger.debug(Prefix + "handlerServiceStatusResp: service success finished, dbResponse_result: " + + result) + + } else if (isErrorCompleted(execution, result)) { + + handlerError(execution, result) + execution.setVariable("isAllFinished", "true") + + logger.debug(Prefix + "handlerServiceStatusResp: service error finished, dbResponse_result: " + + result) + + } else { + String progress = jsonUtil.getJsonValue(dbResponseJson, + "Envelope.Body.getServiceOperationStatusResponse.return.progress") + + String oldProgress = execution.getVariable("progress") + + if (progress == oldProgress) { + execution.setVariable("isNeedUpdateDB", false) + } else { + execution.setVariable("progress", progress) + execution.setVariable("isNeedUpdateDB", true) + } + execution.setVariable("isAllFinished", "false") + TimeUnit.SECONDS.sleep(10) + } + } else { + execution.setVariable("isAllFinished", "false") + //todo: retry + TimeUnit.MILLISECONDS.sleep(10) + } + + } catch (BpmnError e) { + throw e + } catch (Exception ex) { + msg = "Exception in " + Prefix + "handlerServiceStatusResp: " + ex.getMessage() + logger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + logger.trace(Prefix + "handlerServiceStatusResp Exit") + } + + + def timeWaitDelay = { DelegateExecution execution -> + + Long startTime = execution.getVariable("startTime") as Long + Long timeOut = execution.getVariable("timeOut") as Long + + timeOut = timeOut == null ? 3 * 60 * 60 * 1000 : timeOut + + if (System.currentTimeMillis() - startTime > timeOut) { + + handlerTimeOut(execution) + execution.setVariable("isTimeOut", "YES") + + } else { + execution.setVariable("isTimeOut", "NO") + } + } + + + private handlerTimeOut = { DelegateExecution execution -> + + Map<String, Object> paramMap = execution.getVariable("timeOutParamMap") as Map + + handlerProcess(execution, "error", paramMap, "error", "with timeout") + } + + + private handlerSuccess = { DelegateExecution execution, String result -> + + Map<String, Object> paramMap = execution.getVariable("successParamMap") as Map + + handlerProcess(execution, result, paramMap, "deactivated", "success") + } + + + private handlerError = { DelegateExecution execution, String result -> + + Map<String, Object> paramMap = execution.getVariable("errorParamMap") as Map + + handlerProcess(execution, result, paramMap, "error", "with error") + } + + + private handlerProcess = { DelegateExecution execution, String result, def paramMap, def status, def msg -> + + if (paramMap != null) { + for (Map.Entry<String, Object> entry : paramMap.entrySet()) { + execution.setVariable(entry.getKey(), entry.getValue()) + } + } + + + if (isBlank(execution.getVariable("operationStatus") as String)) { + execution.setVariable("operationStatus", result) + } + + + if (isBlank(execution.getVariable("operationContent") as String)) { + String operationContent = execution.getVariable("processServiceType") + " " + + execution.getVariable("operationType") + " operation finished " + msg + execution.setVariable("operationContent", operationContent) + } + + if (isBlank(execution.getVariable("orchestrationStatus") as String)) { + execution.setVariable("orchestrationStatus", status) + } + + } + + + /** + * judge if the service processing success finished + */ + private isSuccessCompleted = { DelegateExecution execution, String result -> + + //successConditions: processing end success conditions + List<String> successConditions = execution.getVariable("successConditions") as List + + result = result.toLowerCase() + if (successConditions.contains(result)) { + return true + } + return false + } + + + /** + * judge if the service processing error finished + */ + private isErrorCompleted = { DelegateExecution execution, String result -> + + //errorConditions: processing end error conditions + List<String> errorConditions = execution.getVariable("errorConditions") as List + + result = result.toLowerCase() + if (errorConditions.contains(result)) { + return true + } + return false + } + + + def preUpdateOperationProgress = { DelegateExecution execution -> + logger.trace(Prefix + "prepareUpdateOperationStatus Start") + + def progress = execution.getVariable("progress") as Integer + def initProgress = execution.getVariable("initProgress") as Integer + def endProgress = execution.getVariable("endProgress") as Integer + + def resProgress = (initProgress + (endProgress - initProgress) / 100 * progress) as Integer + + def operationType = execution.getVariable("operationType") + def operationContent = execution.getVariable("processServiceType") + " " + + operationType + " operation processing " + resProgress + + // update status creating + OperationStatus status = new OperationStatus() + status.setServiceId(execution.getVariable("parentServiceInstanceId") as String) + status.setOperationId(execution.getVariable("parentOperationId") as String) + status.setOperation(operationType as String) + status.setResult("processing") + status.setProgress(resProgress as String) + status.setOperationContent(operationContent as String) + status.setUserId(execution.getVariable("globalSubscriberId") as String) + + requestDBUtil.prepareUpdateOperationStatus(execution, status) + logger.trace(Prefix + "prepareUpdateOperationStatus Exit") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy index 4b3c1aa7b4..3da4161953 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy @@ -163,36 +163,20 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { String serInput = jsonUtil.getJsonValue(resourceInputTmp, "requestsInputs") switch (modelName) { - case ~/[\w\s\W]*OLT[\w\s\W]*/ : + case ~/[\w\s\W]*OLT[\w\s\W]*/ : // for backward compatibilty only, this case will be deprecated + case ~/[\w\s\W]*AccessConnectivity[\w\s\W]*/ : // get the required properties and update in resource input def resourceInput = resourceInputObj.getResourceParameters() String incomingRequest = resourceInputObj.getRequestsInputs() String serviceParameters = JsonUtils.getJsonValue(incomingRequest, "service.parameters") String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") - String cvlan - String svlan - String remoteId - - List<Metadatum> metadatum = getMetaDatum(resourceInputObj.getGlobalSubscriberId(), - resourceInputObj.getServiceType(), - resourceInputObj.getServiceInstanceId()) - for(Metadatum datum: metadatum) { - if (datum.getMetaname().equalsIgnoreCase("cvlan")) { - cvlan = datum.getMetaval() - } - - if (datum.getMetaname().equalsIgnoreCase("svlan")) { - svlan = datum.getMetaval() - } - - if (datum.getMetaname().equalsIgnoreCase("remoteId")) { - remoteId = datum.getMetaval() - } - } - - logger.debug("cvlan: "+cvlan+" | svlan: "+svlan+" | remoteId: "+remoteId) - + String cvlan = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.cvlan") + String svlan = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.svlan") + String remoteId = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.edgeinternetprofile_ip_remote_id") String manufacturer = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_manufacturer") String ontsn = jsonUtil.getJsonValue(serInput, @@ -209,7 +193,8 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { logger.debug("new resource Input :" + resourceInputObj.toString()) break - case ~/[\w\s\W]*EdgeInternetProfile[\w\s\W]*/ : + case ~/[\w\s\W]*EdgeInternetProfile[\w\s\W]*/ : // for backward compatibilty only, this case will be deprecated + case ~/[\w\s\W]*InternetProfile[\w\s\W]*/ : // get the required properties and update in resource input def resourceInput = resourceInputObj.getResourceParameters() String incomingRequest = resourceInputObj.getRequestsInputs() @@ -217,37 +202,34 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") JSONObject inputParameters = new JSONObject(requestInputs) - String cvlan - String svlan - String remoteId + String cvlan = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.cvlan") + String svlan = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.svlan") String manufacturer = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_manufacturer") - + String remoteId = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.edgeinternetprofile_ip_remote_id") String ontsn = jsonUtil.getJsonValue(serInput, "service.parameters.requestInputs.ont_ont_serial_num") - - List<Metadatum> metadatum = getMetaDatum(resourceInputObj.getGlobalSubscriberId(), - resourceInputObj.getServiceType(), - resourceInputObj.getServiceInstanceId()) - for(Metadatum datum: metadatum) { - if (datum.getMetaname().equalsIgnoreCase("cvlan")) { - cvlan = datum.getMetaval() - } - - if (datum.getMetaname().equalsIgnoreCase("svlan")) { - svlan = datum.getMetaval() - } - - if (datum.getMetaname().equalsIgnoreCase("remoteId")) { - remoteId = datum.getMetaval() - } - } + String serviceType = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.edgeinternetprofile_ip_service_type") + String macAddr = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.edgeinternetprofile_ip_rg_mac_addr") + String upStream = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.edgeinternetprofile_ip_upstream_speed") + String downStream = jsonUtil.getJsonValue(serInput, + "service.parameters.requestInputs.edgeinternetprofile_ip_downstream_speed") String uResourceInput = jsonUtil.addJsonValue(resourceInput, "requestInputs.c_vlan", cvlan) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.s_vlan", svlan) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.manufacturer", manufacturer) - uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_access_id", remoteId) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_remote_id", remoteId) uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ont_sn", ontsn) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_service_type", serviceType) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_rg_mac_addr", macAddr) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_upstream_speed", upStream) + uResourceInput = jsonUtil.addJsonValue(uResourceInput, "requestInputs.ip_downstream_speed", downStream) logger.debug("old resource input:" + resourceInputObj.toString()) resourceInputObj.setResourceParameters(uResourceInput) execution.setVariable(Prefix + "resourceInput", resourceInputObj.toString()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy new file mode 100644 index 0000000000..d8897a2468 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeallocateNSSI.groovy @@ -0,0 +1,309 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2019, CMCC Technologies Co., Ltd. + # + # Licensed under the Apache License, Version 2.0 (the "License") + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import com.fasterxml.jackson.databind.ObjectMapper +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.logging.filter.base.ONAPComponents +import org.onap.so.beans.nsmf.DeAllocateNssi +import org.onap.so.beans.nsmf.EsrInfo +import org.onap.so.beans.nsmf.JobStatusRequest +import org.onap.so.beans.nsmf.JobStatusResponse +import org.onap.so.beans.nsmf.NetworkType +import org.onap.so.beans.nsmf.NssiDeAllocateRequest +import org.onap.so.beans.nsmf.NssiResponse +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.RequestDBUtil +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.domain.ServiceArtifact +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient +import org.onap.so.client.HttpClientFactory +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.request.beans.OperationStatus +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +import javax.ws.rs.core.Response + + +class DoDeallocateNSSI extends AbstractServiceTaskProcessor +{ + private final String PREFIX ="DoDeallocateNSSI" + + private ExceptionUtil exceptionUtil = new ExceptionUtil() + private JsonUtils jsonUtil = new JsonUtils() + private RequestDBUtil requestDBUtil = new RequestDBUtil() + private static final Logger LOGGER = LoggerFactory.getLogger( DoDeallocateNSSI.class) + + @Override + void preProcessRequest(DelegateExecution execution) { + LOGGER.trace(" ***** ${PREFIX} Start preProcessRequest *****") + + def currentNSSI = execution.getVariable("currentNSSI") + if (!currentNSSI) { + String msg = "currentNSSI is null" + LOGGER.error(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + LOGGER.trace("***** ${PREFIX} Exit preProcessRequest *****") + } + + /** + * + * @param execution + */ + private void prepareDecomposeService(DelegateExecution execution) + { + LOGGER.trace(" *****${PREFIX} Start prepareDecomposeService *****") + try + { + def currentNSSI = execution.getVariable("currentNSSI") + String modelInvariantUuid = currentNSSI['modelInvariantId'] + String modelVersionId = currentNSSI['modelVersionId'] + String serviceModelInfo = """{ + "modelInvariantUuid":"${modelInvariantUuid}", + "modelUuid":"${modelVersionId}", + "modelVersion":"" + }""" + execution.setVariable("serviceModelInfo", serviceModelInfo) + } + catch (any) + { + String exceptionMessage = "Bpmn error encountered in deallocate nssi. Unexpected Error from method prepareDecomposeService() - " + any.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + LOGGER.debug(" ***** ${PREFIX} Exit prepareDecomposeService *****") + } + + /** + * get vendor Info + * @param execution + */ + private void processDecomposition(DelegateExecution execution) { + LOGGER.debug("*****${PREFIX} start processDecomposition *****") + + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") as ServiceDecomposition + ServiceArtifact serviceArtifact = serviceDecomposition ?.getServiceInfo()?.getServiceArtifact()?.get(0) + String content = serviceArtifact.getContent() + String vendor = jsonUtil.getJsonValue(content, "metadata.vendor") + String domainType = jsonUtil.getJsonValue(content, "metadata.domainType") + + def currentNSSI = execution.getVariable("currentNSSI") + currentNSSI['vendor'] = vendor + currentNSSI['domainType'] = domainType + LOGGER.info("processDecomposition, current vendor-domainType:" +String.join("-", vendor, domainType)) + + } catch (any) { + String exceptionMessage = "Bpmn error encountered in deallocate nssi. processDecomposition() - " + any.getMessage() + LOGGER.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + LOGGER.debug("*****${PREFIX} Exit processDecomposition *****") + } + + /** + * send deallocate request to nssmf + * @param execution + */ + private void sendRequestToNSSMF(DelegateExecution execution) + { + LOGGER.debug("*****${PREFIX} start sendRequestToNSSMF *****") + def currentNSSI = execution.getVariable("currentNSSI") + String snssai= currentNSSI['snssai'] + String profileId = currentNSSI['profileId'] + String nssiId = currentNSSI['nssiServiceInstanceId'] + String nsiId = currentNSSI['nsiServiceInstanceId'] + + DeAllocateNssi deAllocateNssi = new DeAllocateNssi() + deAllocateNssi.setNsiId(nsiId) + deAllocateNssi.setNssiId(nssiId) + deAllocateNssi.setTerminateNssiOption(0) + deAllocateNssi.setSnssaiList(Arrays.asList(snssai)) + + NssiDeAllocateRequest deAllocateRequest = new NssiDeAllocateRequest() + deAllocateRequest.setDeAllocateNssi(deAllocateNssi) + deAllocateRequest.setEsrInfo(getEsrInfo(currentNSSI)) + + ObjectMapper mapper = new ObjectMapper() + String json = mapper.writeValueAsString(deAllocateRequest) + + //Prepare auth for NSSMF - Begin + String nssmfRequest = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution) + nssmfRequest = nssmfRequest + String.format("/api/rest/provMns/v1/NSS/SliceProfiles/%s",profileId) + //nssmfRequest = nssmfRequest + String.format(NssmfAdapterUtil.NSSMI_DEALLOCATE_URL,profileId) + //send request to active NSSI TN option + URL url = new URL(nssmfRequest) + LOGGER.info("deallocate nssmfRequest:${nssmfRequest}, reqBody: ${json}") + + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL) + Response httpResponse = httpClient.post(json) + checkNssmfResponse(httpResponse, execution) + + NssiResponse nssmfResponse = httpResponse.readEntity(NssiResponse.class) + currentNSSI['jobId']= nssmfResponse.getJobId() ?: "" + currentNSSI['jobProgress'] = 0 + execution.setVariable("currentNSSI", currentNSSI) + + LOGGER.debug("*****${PREFIX} Exit sendRequestToNSSMF *****") + } + + /** + * send to nssmf query progress + * @param execution + */ + private void getJobStatus(DelegateExecution execution) + { + def currentNSSI = execution.getVariable("currentNSSI") + String jobId = currentNSSI['jobId'] + String nssiId = currentNSSI['nssiServiceInstanceId'] + String nsiId = currentNSSI['nsiServiceInstanceId'] + + JobStatusRequest jobStatusRequest = new JobStatusRequest() + jobStatusRequest.setNssiId(nssiId) + jobStatusRequest.setNsiId(nsiId) + jobStatusRequest.setEsrInfo(getEsrInfo(currentNSSI)) + + ObjectMapper mapper = new ObjectMapper() + String json = mapper.writeValueAsString(jobStatusRequest) + + //Prepare auth for NSSMF - Begin + String nssmfRequest = UrnPropertiesReader.getVariable("mso.adapters.nssmf.endpoint", execution) + nssmfRequest = nssmfRequest + String.format("/api/rest/provMns/v1/NSS/jobs/%s",jobId) + //send request to active NSSI TN option + URL url = new URL(nssmfRequest) + LOGGER.info("get deallocate job status, nssmfRequest:${nssmfRequest}, requestBody: ${json}") + + HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.EXTERNAL) + Response httpResponse = httpClient.post(json) + checkNssmfResponse(httpResponse, execution) + + JobStatusResponse jobStatusResponse = httpResponse.readEntity(JobStatusResponse.class) + def progress = jobStatusResponse?.getResponseDescriptor()?.getProgress() + if(!progress) + { + LOGGER.error("job progress is null or empty!") + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Received a Bad Job progress from NSSMF.") + } + int oldProgress = currentNSSI['jobProgress'] + int currentProgress = progress + + execution.setVariable("isNSSIDeAllocated", (currentProgress == 100)) + execution.setVariable("isNeedUpdateDB", (oldProgress != currentProgress)) + currentNSSI['jobProgress'] = currentProgress + + def statusDescription = jobStatusResponse?.getResponseDescriptor()?.getStatusDescription() + currentNSSI['statusDescription'] = statusDescription + + LOGGER.debug("job status result: nsiId = ${nsiId}, nssiId=${nssiId}, oldProgress=${oldProgress}, progress = ${currentProgress}" ) + } + + private void checkNssmfResponse(Response httpResponse, DelegateExecution execution) { + int responseCode = httpResponse.getStatus() + LOGGER.debug("NSSMF response code is: " + responseCode) + + if ( responseCode < 200 || responseCode > 204 || !httpResponse.hasEntity()) { + exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Response from NSSMF.") + } + } + + + private EsrInfo getEsrInfo(def currentNSSI) + { + String domaintype = currentNSSI['domainType'] + String vendor = currentNSSI['vendor'] + + EsrInfo info = new EsrInfo() + info.setNetworkType(NetworkType.fromString(domaintype)) + info.setVendor(vendor) + return info + } + + /** + * handle job status + * prepare update requestdb + * @param execution + */ + private void handleJobStatus(DelegateExecution execution) + { + def currentNSSI = execution.getVariable("currentNSSI") + int currentProgress = currentNSSI["jobProgress"] + def proportion = currentNSSI['proportion'] + def statusDes = currentNSSI["statusDescription"] + int progress = (currentProgress as int) == 0 ? 0 : (currentProgress as int) / 100 * (proportion as int) + + OperationStatus operationStatus = new OperationStatus() + operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String) + operationStatus.setOperationId(currentNSSI['operationId'] as String) + operationStatus.setOperation("DELETE") + operationStatus.setResult("processing") + operationStatus.setProgress(progress as String) + operationStatus.setOperationContent(statusDes as String) + requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus) + LOGGER.debug("update operation, currentProgress=${currentProgress}, proportion=${proportion}, progress = ${progress}" ) + } + + private void timeDelay(DelegateExecution execution) { + try { + Thread.sleep(10000); + } catch(InterruptedException e) { + LOGGER.error("Time Delay exception" + e) + } + } + + /** + * delete slice profile from aai + * @param execution + */ + private void delSliceProfileFromAAI(DelegateExecution execution) + { + LOGGER.debug("*****${PREFIX} start delSliceProfileFromAAI *****") + def currentNSSI = execution.getVariable("currentNSSI") + String nssiServiceInstanceId = currentNSSI['nssiServiceInstanceId'] + String profileId = currentNSSI['profileId'] + String globalSubscriberId = currentNSSI["globalSubscriberId"] + String serviceType = currentNSSI["serviceType"] + + try + { + LOGGER.debug("delete nssiServiceInstanceId:${nssiServiceInstanceId}, profileId:${profileId}") + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SLICE_PROFILE, globalSubscriberId, serviceType, nssiServiceInstanceId, profileId) + if (!resourceClient.exists(resourceUri)) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai") + } + resourceClient.delete(resourceUri) + } + catch (any) + { + String msg = "delete slice profile from aai failed! cause-"+any.getCause() + LOGGER.error(any.printStackTrace()) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + LOGGER.debug("*****${PREFIX} Exist delSliceProfileFromAAI *****") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy new file mode 100644 index 0000000000..f066f9e878 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CheckServiceProcessStatusTest.groovy @@ -0,0 +1,344 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + # Copyright (c) 2019, CMCC Technologies Co., Ltd. + # + # Licensed under the Apache License, Version 2.0 (the "License") + # you may not use this file except in compliance with the License. + # You may obtain a copy of the License at + # + # http://www.apache.org/licenses/LICENSE-2.0 + # + # Unless required by applicable law or agreed to in writing, software + # distributed under the License is distributed on an "AS IS" BASIS, + # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + # See the License for the specific language governing permissions and + # limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.Test +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.onap.so.bpmn.common.scripts.MsoGroovyTest + +import static org.junit.Assert.assertEquals +import static org.mockito.ArgumentMatchers.eq +import static org.mockito.Mockito.times +import static org.mockito.Mockito.when + +class CheckServiceProcessStatusTest extends MsoGroovyTest { + @Before + void init() throws IOException { + super.init("CheckServiceProcessStatus") + } + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + + @Test + void testPreProcessRequest () { + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("operationId")).thenReturn("54321") + + def successConditions = new ArrayList<>() + successConditions.add("finished") + successConditions.add("completed") + + def errorConditions = new ArrayList<>() + errorConditions.add("error") + errorConditions.add("failed") + + when(mockExecution.getVariable("successConditions")).thenReturn(successConditions) + when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions) + + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + serviceProcessStatus.preProcessRequest(mockExecution) + Mockito.verify(mockExecution, times(9)).setVariable(captor.capture(), captor.capture()) + } + + + @Test + void testPreCheckServiceStatusReq() { + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("operationId")).thenReturn("54321") + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + + serviceProcessStatus.preCheckServiceStatusReq(mockExecution) + Mockito.verify(mockExecution, times(1)).setVariable(eq("getOperationStatus"), captor.capture()) + String res = captor.getValue() + String expect = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:getServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>12345</serviceId> + <operationId>54321</operationId> + </ns:getServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope> + """ + assertEquals(expect.replaceAll("\\s+", ""), res.replaceAll("\\s+", "")) + } + + + @Test + void testHandlerServiceStatusRespSuccess() { + mockData() + when(mockExecution.getVariable("dbResponseCode")).thenReturn(200) + when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("finished")) + def successConditions = new ArrayList<>() + successConditions.add("finished") + successConditions.add("completed") + + when(mockExecution.getVariable("successConditions")).thenReturn(successConditions) + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + serviceProcessStatus.handlerServiceStatusResp(mockExecution) + + Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture()) + def resultSuccess = captor.getAllValues() + + def expect = new ArrayList<>() + expect.add("operationStatus") + expect.add("finished") + expect.add("operationContent") + expect.add("communication service create operation finished success") + expect.add("orchestrationStatus") + expect.add("deactivated") + expect.add("isAllFinished") + expect.add("true") + + assertEquals(expect, resultSuccess) + } + + + @Test + void testHandlerServiceStatusRespError() { + mockData() + when(mockExecution.getVariable("dbResponseCode")).thenReturn(200) + when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("error")) + + def successConditions = new ArrayList<>() + successConditions.add("finished") + successConditions.add("completed") + + def errorConditions = new ArrayList<>() + errorConditions.add("error") + errorConditions.add("failed") + + when(mockExecution.getVariable("successConditions")).thenReturn(successConditions) + when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions) + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + serviceProcessStatus.handlerServiceStatusResp(mockExecution) + + Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture()) + def resultSuccess = captor.getAllValues() + + def expect = new ArrayList<>() + expect.add("operationStatus") + expect.add("error") + expect.add("operationContent") + expect.add("communication service create operation finished with error") + expect.add("orchestrationStatus") + expect.add("error") + expect.add("isAllFinished") + expect.add("true") + + assertEquals(expect, resultSuccess) + } + + + @Test + void testHandlerServiceStatusRespProcessingNo() { + mockData() + when(mockExecution.getVariable("dbResponseCode")).thenReturn(200) + when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("processing")) + when(mockExecution.getVariable("progress")).thenReturn(50) + + def successConditions = new ArrayList<>() + successConditions.add("finished") + successConditions.add("completed") + + def errorConditions = new ArrayList<>() + errorConditions.add("error") + errorConditions.add("failed") + + when(mockExecution.getVariable("successConditions")).thenReturn(successConditions) + when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions) + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + serviceProcessStatus.handlerServiceStatusResp(mockExecution) + + Mockito.verify(mockExecution, times(2)).setVariable(captor.capture(), captor.capture()) + def resultSuccess = captor.getAllValues() + + def expect = new ArrayList<>() + expect.add("isNeedUpdateDB") + expect.add("false") + expect.add("isAllFinished") + expect.add("false") + + assertEquals(expect as String, resultSuccess as String) + } + + + @Test + void testHandlerServiceStatusRespProcessingYes() { + mockData() + when(mockExecution.getVariable("dbResponseCode")).thenReturn(200) + when(mockExecution.getVariable("dbResponse")).thenReturn(getDBResponse("processing")) + when(mockExecution.getVariable("progress")).thenReturn(60) + + def successConditions = new ArrayList<>() + successConditions.add("finished") + successConditions.add("completed") + + def errorConditions = new ArrayList<>() + errorConditions.add("error") + errorConditions.add("failed") + + when(mockExecution.getVariable("successConditions")).thenReturn(successConditions) + when(mockExecution.getVariable("errorConditions")).thenReturn(errorConditions) + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + serviceProcessStatus.handlerServiceStatusResp(mockExecution) + + Mockito.verify(mockExecution, times(3)).setVariable(captor.capture(), captor.capture()) + def resultSuccess = captor.getAllValues() + + def expect = new ArrayList<>() + expect.add("progress") + expect.add("50") + expect.add("isNeedUpdateDB") + expect.add("true") + expect.add("isAllFinished") + expect.add("false") + + assertEquals(expect as String, resultSuccess as String) + } + + + @Test + void testTimeWaitDelayNo() { + mockData() + when(mockExecution.getVariable("startTime")).thenReturn(System.currentTimeMillis()) + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + + serviceProcessStatus.timeWaitDelay(mockExecution) + Mockito.verify(mockExecution, times(1)).setVariable(eq("isTimeOut"), captor.capture()) + def res = captor.getValue() + + assertEquals("NO", res) + } + + + @Test + void testTimeWaitDelayYes() { + mockData() + when(mockExecution.getVariable("startTime")).thenReturn(1000000) + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + + serviceProcessStatus.timeWaitDelay(mockExecution) + Mockito.verify(mockExecution, times(4)).setVariable(captor.capture(), captor.capture()) + def res = captor.getAllValues() + def expect = new ArrayList<>() + expect.add("operationStatus") + expect.add("error") + expect.add("operationContent") + expect.add("communication service create operation finished with timeout") + expect.add("orchestrationStatus") + expect.add("error") + expect.add("isTimeOut") + expect.add("YES") + + assertEquals(expect, res) + } + + + @Test + void testPreUpdateOperationProgress() { + mockData() + when(mockExecution.getVariable("progress")).thenReturn(50) + when(mockExecution.getVariable("initProgress")).thenReturn(20) + when(mockExecution.getVariable("endProgress")).thenReturn(90) + when(mockExecution.getVariable("operationType")).thenReturn("CREATE") + when(mockExecution.getVariable("processServiceType")).thenReturn("communication service") + when(mockExecution.getVariable("parentServiceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("parentOperationId")).thenReturn("54321") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("11111") + + CheckServiceProcessStatus serviceProcessStatus = new CheckServiceProcessStatus() + serviceProcessStatus.preUpdateOperationProgress(mockExecution) + Mockito.verify(mockExecution, times(1)).setVariable(eq("updateOperationStatus"), captor.capture()) + String res = captor.getValue() + + String expect = getExpectPayload("55", + "communication service CREATE operation processing 55") + + assertEquals(expect.replaceAll("\\s+", ""), res.replaceAll("\\s+", "")) + + + } + + + private static String getExpectPayload(String progress, String operationContent) { + String expect = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>12345</serviceId> + <operationId>54321</operationId> + <operationType>CREATE</operationType> + <userId>11111</userId> + <result>processing</result> + <operationContent>${operationContent}</operationContent> + <progress>${progress}</progress> + <reason></reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope> + """ + return expect + } + + + private static String getDBResponse(String result) { + String response = + """<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> + <soap:Body> + <ns2:getServiceOperationStatusResponse xmlns:ns2="http://org.onap.so/requestsdb"> + <return><operation>CREATE</operation> + <operationContent>Prepare service creation</operationContent> + <operationId>077995e3-eb32-44ae-b35d-491fc6983a44</operationId> + <progress>50</progress> + <reason></reason> + <result>${result}</result> + <serviceId>3324f117-696d-4518-b8b5-b01fcc127a03</serviceId> + <userId>5GCustomer</userId> + </return></ns2:getServiceOperationStatusResponse> + </soap:Body> + </soap:Envelope> + """ + return response + } + + + private mockData() { + when(mockExecution.getVariable("processServiceType")).thenReturn("communication service") + when(mockExecution.getVariable("operationType")).thenReturn("create") + } +} diff --git a/bpmn/so-bpmn-infrastructure-flows/pom.xml b/bpmn/so-bpmn-infrastructure-flows/pom.xml index d0c16fc1cc..c7d4f3f894 100644 --- a/bpmn/so-bpmn-infrastructure-flows/pom.xml +++ b/bpmn/so-bpmn-infrastructure-flows/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>so-bpmn-infrastructure-flows</artifactId> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ActivateCommunicationService.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ActivateCommunicationService.bpmn new file mode 100644 index 0000000000..92fd5ef52b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/ActivateCommunicationService.bpmn @@ -0,0 +1,486 @@ +<?xml version="1.0" encoding="UTF-8"?> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="Definitions_1gtu09b" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.4.1"> + <bpmn:process id="ActivateCommunicationService" name="ActivateCommunicationService" isExecutable="true"> + <bpmn:startEvent id="StartEvent_1"> + <bpmn:outgoing>SequenceFlow_199lc2s</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:scriptTask id="ScriptTask_08alvv7" name="Pre Process Incoming Request" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_199lc2s</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0rl5u9x</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.preProcessRequest(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_199lc2s" sourceRef="StartEvent_1" targetRef="ScriptTask_08alvv7" /> + <bpmn:scriptTask id="ScriptTask_0t2aizp" name="Init Service Operation Status" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0cg4k4f</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0xunetn</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.prepareInitOperationStatus(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:serviceTask id="ServiceTask_1h8uywz" name="Init Service Operation Status"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${updateOperationStatus}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="ACS_init_dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="ACS_init_dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_0xunetn</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_07brvnu</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_0xunetn" sourceRef="ScriptTask_0t2aizp" targetRef="ServiceTask_1h8uywz" /> + <bpmn:scriptTask id="ScriptTask_1rshcew" name="Send Sync Ack Response" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_07brvnu</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0c01147</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.sendSyncResponse(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:scriptTask id="ScriptTask_0soxu97" name="check AAI Orch Status of cs" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0rl5u9x</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0337wg2</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.checkAAIOrchStatus(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_0rl5u9x" sourceRef="ScriptTask_08alvv7" targetRef="ScriptTask_0soxu97" /> + <bpmn:sequenceFlow id="SequenceFlow_07brvnu" sourceRef="ServiceTask_1h8uywz" targetRef="ScriptTask_1rshcew" /> + <bpmn:intermediateThrowEvent id="IntermediateThrowEvent_1twqa76" name="Goto Call Active Slice"> + <bpmn:incoming>SequenceFlow_0c01147</bpmn:incoming> + <bpmn:linkEventDefinition name="CallActiveSlice" /> + </bpmn:intermediateThrowEvent> + <bpmn:intermediateCatchEvent id="IntermediateThrowEvent_15alt6m" name="CallActiveSlice"> + <bpmn:outgoing>SequenceFlow_1om5m6o</bpmn:outgoing> + <bpmn:linkEventDefinition id="LinkEventDefinition_0zbmuty" name="CallActiveSlice" /> + </bpmn:intermediateCatchEvent> + <bpmn:sequenceFlow id="SequenceFlow_1om5m6o" sourceRef="IntermediateThrowEvent_15alt6m" targetRef="ScriptTask_0oun39f" /> + <bpmn:exclusiveGateway id="ExclusiveGateway_1j8khf8" name="Is call activate slice Successful?"> + <bpmn:incoming>SequenceFlow_1i6cshg</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_176pwpd</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_1r6lo31</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:scriptTask id="ScriptTask_0fbubvu" name="Update Finish Status In AAI " scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1w1h5vl</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1r6lo31</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1b8q7l5</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.updateFinishStatusInAAI(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:scriptTask id="ScriptTask_1seqo87" name="Prepare Complete Status in requestDB" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1b8q7l5</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_103y3rz</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.prepareCompleteStatus(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:serviceTask id="ServiceTask_10gsfd1" name="Update Service Operation Status Completed"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${updateOperationStatus}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="ACS_complete_dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="ACS_complete_dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_103y3rz</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_15dmqcp</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_1b8q7l5" sourceRef="ScriptTask_0fbubvu" targetRef="ScriptTask_1seqo87" /> + <bpmn:sequenceFlow id="SequenceFlow_103y3rz" sourceRef="ScriptTask_1seqo87" targetRef="ServiceTask_10gsfd1" /> + <bpmn:sequenceFlow id="SequenceFlow_176pwpd" name="yes" sourceRef="ExclusiveGateway_1j8khf8" targetRef="ScriptTask_0zqkikf"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("ProcessNsmfSuccess") == "OK"}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:endEvent id="EndEvent_0z07q3n"> + <bpmn:incoming>SequenceFlow_15dmqcp</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_15dmqcp" sourceRef="ServiceTask_10gsfd1" targetRef="EndEvent_0z07q3n" /> + <bpmn:exclusiveGateway id="ExclusiveGateway_1g73afb" name="Is orchstatus vaild?" default="SequenceFlow_0hpybf9"> + <bpmn:incoming>SequenceFlow_0337wg2</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0cg4k4f</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_0hpybf9</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:sequenceFlow id="SequenceFlow_0cg4k4f" name="yes" sourceRef="ExclusiveGateway_1g73afb" targetRef="ScriptTask_0t2aizp"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("isContinue") == "true"}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_0337wg2" sourceRef="ScriptTask_0soxu97" targetRef="ExclusiveGateway_1g73afb" /> + <bpmn:sequenceFlow id="SequenceFlow_0hpybf9" name="no" sourceRef="ExclusiveGateway_1g73afb" targetRef="EndEvent_02rugcv" /> + <bpmn:endEvent id="EndEvent_02rugcv"> + <bpmn:incoming>SequenceFlow_0hpybf9</bpmn:incoming> + <bpmn:errorEventDefinition errorRef="Error_1ld8i6u" /> + </bpmn:endEvent> + <bpmn:subProcess id="SubProcess_1i9i3h1" name="Sub-process for FalloutHandler and Rollback" triggeredByEvent="true"> + <bpmn:startEvent id="StartEvent_1f90rxc"> + <bpmn:outgoing>SequenceFlow_1dkviys</bpmn:outgoing> + <bpmn:errorEventDefinition id="ErrorEventDefinition_0iyy5ka" /> + </bpmn:startEvent> + <bpmn:endEvent id="EndEvent_1m9nsoo"> + <bpmn:incoming>SequenceFlow_18sqlo7</bpmn:incoming> + </bpmn:endEvent> + <bpmn:scriptTask id="ScriptTask_003nbzc" name="Send Error Response" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1dkviys</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_18sqlo7</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.sendSyncError(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_1dkviys" sourceRef="StartEvent_1f90rxc" targetRef="ScriptTask_003nbzc" /> + <bpmn:sequenceFlow id="SequenceFlow_18sqlo7" sourceRef="ScriptTask_003nbzc" targetRef="EndEvent_1m9nsoo" /> + </bpmn:subProcess> + <bpmn:scriptTask id="ScriptTask_0zqkikf" name="Prepare Update Operation Status" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_176pwpd</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0mruwcs</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.prepareUpdateOperationStatus(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:serviceTask id="ServiceTask_11v60ns" name="Update Service Operation Status processing"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${updateOperationStatus}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="ACS_processing_dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="ACS_processing_dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_0mruwcs</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0f57hgr</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_0mruwcs" sourceRef="ScriptTask_0zqkikf" targetRef="ServiceTask_11v60ns" /> + <bpmn:scriptTask id="ScriptTask_0oun39f" name="Pre Request Send To NSMF" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1om5m6o</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_12ax52p</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.preRequestSend2NSMF(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:serviceTask id="ServiceTask_1pbp58s" name="Send Request To NSMF"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${NSMF_endpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/json</camunda:entry> + <camunda:entry key="Authorization">Basic SW5mcmFQb3J0YWxDbGllbnQ6cGFzc3dvcmQxJA==</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${CSMF_NSMFRequest}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="CSMF_NSMFResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="CSMF_NSMFResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_12ax52p</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1e9r8tc</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:scriptTask id="ScriptTask_167kv01" name="Process NSMF response" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1e9r8tc</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1i6cshg</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.processNSMFResponse(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_12ax52p" sourceRef="ScriptTask_0oun39f" targetRef="ServiceTask_1pbp58s" /> + <bpmn:sequenceFlow id="SequenceFlow_1e9r8tc" sourceRef="ServiceTask_1pbp58s" targetRef="ScriptTask_167kv01" /> + <bpmn:sequenceFlow id="SequenceFlow_1i6cshg" sourceRef="ScriptTask_167kv01" targetRef="ExclusiveGateway_1j8khf8" /> + <bpmn:scriptTask id="ScriptTask_0iubb84" name="Prepare Call CheckServiceProcessStatus" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1hsbli0</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_102nqyb</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def act= new ActivateCommunicationService() +act.prepareCallCheckProcessStatus(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_102nqyb" sourceRef="ScriptTask_0iubb84" targetRef="CallActivity_12eufsa" /> + <bpmn:sequenceFlow id="SequenceFlow_0f57hgr" sourceRef="ServiceTask_11v60ns" targetRef="IntermediateThrowEvent_1u9a1t0" /> + <bpmn:intermediateThrowEvent id="IntermediateThrowEvent_1u9a1t0" name="Goto check processing status"> + <bpmn:incoming>SequenceFlow_0f57hgr</bpmn:incoming> + <bpmn:linkEventDefinition name="CheckProcessingStatus" /> + </bpmn:intermediateThrowEvent> + <bpmn:sequenceFlow id="SequenceFlow_1hsbli0" sourceRef="IntermediateThrowEvent_1lcnqle" targetRef="ScriptTask_0iubb84" /> + <bpmn:intermediateCatchEvent id="IntermediateThrowEvent_1lcnqle" name="CheckProcessingStatus"> + <bpmn:outgoing>SequenceFlow_1hsbli0</bpmn:outgoing> + <bpmn:linkEventDefinition name="CheckProcessingStatus" /> + </bpmn:intermediateCatchEvent> + <bpmn:callActivity id="CallActivity_12eufsa" name="CallCheckServiceProcessStatus" calledElement="CheckServiceProcessStatus"> + <bpmn:extensionElements> + <camunda:in source="e2eServiceInstanceId" target="serviceInstanceId" /> + <camunda:in source="e2eOperationId" target="operationId" /> + <camunda:in source="successConditions" target="successConditions" /> + <camunda:in source="processServiceType" target="processServiceType" /> + <camunda:in source="errorConditions" target="errorConditions" /> + <camunda:in source="timeOut" target="timeOut" /> + <camunda:in source="successParamMap" target="successParamMap" /> + <camunda:in source="errorParamMap" target="errorParamMap" /> + <camunda:out source="orchestrationStatus" target="orchestrationStatus" /> + <camunda:out source="operationStatus" target="operationStatus" /> + <camunda:out source="operationContent" target="operationContent" /> + <camunda:out source="WorkflowException" target="WorkflowException" /> + <camunda:in source="timeOutParamMap" target="timeOutParamMap" /> + <camunda:in source="globalSubscriberId" target="globalSubscriberId" /> + <camunda:in source="operationType" target="operationType" /> + <camunda:in source="initProgress" target="initProgress" /> + <camunda:in source="endProgress" target="endProgress" /> + <camunda:in source="serviceInstanceId" target="parentServiceInstanceId" /> + <camunda:in source="operationId" target="parentOperationId" /> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_102nqyb</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1w1h5vl</bpmn:outgoing> + </bpmn:callActivity> + <bpmn:sequenceFlow id="SequenceFlow_1w1h5vl" sourceRef="CallActivity_12eufsa" targetRef="ScriptTask_0fbubvu" /> + <bpmn:sequenceFlow id="SequenceFlow_1r6lo31" name="No" sourceRef="ExclusiveGateway_1j8khf8" targetRef="ScriptTask_0fbubvu"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("ProcessNsmfSuccess") == "ERROR"}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_0c01147" sourceRef="ScriptTask_1rshcew" targetRef="IntermediateThrowEvent_1twqa76" /> + </bpmn:process> + <bpmn:error id="Error_1ld8i6u" name="MSOWorkflowException" errorCode="MSOWorkflowException" /> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="ActivateCommunicationService"> + <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1"> + <dc:Bounds x="179" y="159" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_08alvv7_di" bpmnElement="ScriptTask_08alvv7"> + <dc:Bounds x="310" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_199lc2s_di" bpmnElement="SequenceFlow_199lc2s"> + <di:waypoint x="215" y="177" /> + <di:waypoint x="310" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0t2aizp_di" bpmnElement="ScriptTask_0t2aizp"> + <dc:Bounds x="760" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_1h8uywz_di" bpmnElement="ServiceTask_1h8uywz"> + <dc:Bounds x="960" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0xunetn_di" bpmnElement="SequenceFlow_0xunetn"> + <di:waypoint x="860" y="177" /> + <di:waypoint x="960" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_1rshcew_di" bpmnElement="ScriptTask_1rshcew"> + <dc:Bounds x="1140" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_0soxu97_di" bpmnElement="ScriptTask_0soxu97"> + <dc:Bounds x="480" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0rl5u9x_di" bpmnElement="SequenceFlow_0rl5u9x"> + <di:waypoint x="410" y="177" /> + <di:waypoint x="480" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_07brvnu_di" bpmnElement="SequenceFlow_07brvnu"> + <di:waypoint x="1060" y="177" /> + <di:waypoint x="1140" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="IntermediateThrowEvent_0bgd82x_di" bpmnElement="IntermediateThrowEvent_1twqa76"> + <dc:Bounds x="1332" y="159" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1314" y="202" width="79" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="IntermediateCatchEvent_0qbtq4z_di" bpmnElement="IntermediateThrowEvent_15alt6m"> + <dc:Bounds x="179" y="402" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="161" y="445" width="73" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1om5m6o_di" bpmnElement="SequenceFlow_1om5m6o"> + <di:waypoint x="215" y="420" /> + <di:waypoint x="310" y="420" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ExclusiveGateway_1j8khf8_di" bpmnElement="ExclusiveGateway_1j8khf8" isMarkerVisible="true"> + <dc:Bounds x="815" y="395" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="799" y="358" width="85" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_0fbubvu_di" bpmnElement="ScriptTask_0fbubvu"> + <dc:Bounds x="790" y="560" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_1seqo87_di" bpmnElement="ScriptTask_1seqo87"> + <dc:Bounds x="960" y="560" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_10gsfd1_di" bpmnElement="ServiceTask_10gsfd1"> + <dc:Bounds x="1140" y="560" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1b8q7l5_di" bpmnElement="SequenceFlow_1b8q7l5"> + <di:waypoint x="890" y="600" /> + <di:waypoint x="960" y="600" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_103y3rz_di" bpmnElement="SequenceFlow_103y3rz"> + <di:waypoint x="1060" y="600" /> + <di:waypoint x="1140" y="600" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_176pwpd_di" bpmnElement="SequenceFlow_176pwpd"> + <di:waypoint x="865" y="420" /> + <di:waypoint x="960" y="420" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="904" y="402" width="17" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_0z07q3n_di" bpmnElement="EndEvent_0z07q3n"> + <dc:Bounds x="1332" y="582" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_15dmqcp_di" bpmnElement="SequenceFlow_15dmqcp"> + <di:waypoint x="1240" y="600" /> + <di:waypoint x="1332" y="600" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ExclusiveGateway_1g73afb_di" bpmnElement="ExclusiveGateway_1g73afb" isMarkerVisible="true"> + <dc:Bounds x="645" y="152" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="648" y="116" width="63" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0cg4k4f_di" bpmnElement="SequenceFlow_0cg4k4f"> + <di:waypoint x="695" y="177" /> + <di:waypoint x="760" y="177" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="719" y="159" width="17" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0337wg2_di" bpmnElement="SequenceFlow_0337wg2"> + <di:waypoint x="580" y="177" /> + <di:waypoint x="645" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0hpybf9_di" bpmnElement="SequenceFlow_0hpybf9"> + <di:waypoint x="670" y="202" /> + <di:waypoint x="670" y="262" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="679" y="229" width="13" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_118l531_di" bpmnElement="EndEvent_02rugcv"> + <dc:Bounds x="652" y="262" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="SubProcess_1i9i3h1_di" bpmnElement="SubProcess_1i9i3h1" isExpanded="true"> + <dc:Bounds x="340" y="730" width="781" height="196" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="StartEvent_1f90rxc_di" bpmnElement="StartEvent_1f90rxc"> + <dc:Bounds x="382" y="816" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="EndEvent_1m9nsoo_di" bpmnElement="EndEvent_1m9nsoo"> + <dc:Bounds x="1052" y="816" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_003nbzc_di" bpmnElement="ScriptTask_003nbzc"> + <dc:Bounds x="670" y="794" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1dkviys_di" bpmnElement="SequenceFlow_1dkviys"> + <di:waypoint x="418" y="834" /> + <di:waypoint x="670" y="834" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_18sqlo7_di" bpmnElement="SequenceFlow_18sqlo7"> + <di:waypoint x="770" y="834" /> + <di:waypoint x="1052" y="834" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0zqkikf_di" bpmnElement="ScriptTask_0zqkikf"> + <dc:Bounds x="960" y="380" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_11v60ns_di" bpmnElement="ServiceTask_11v60ns"> + <dc:Bounds x="1140" y="380" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0mruwcs_di" bpmnElement="SequenceFlow_0mruwcs"> + <di:waypoint x="1060" y="420" /> + <di:waypoint x="1140" y="420" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0oun39f_di" bpmnElement="ScriptTask_0oun39f"> + <dc:Bounds x="310" y="380" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_1pbp58s_di" bpmnElement="ServiceTask_1pbp58s"> + <dc:Bounds x="480" y="380" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_167kv01_di" bpmnElement="ScriptTask_167kv01"> + <dc:Bounds x="640" y="380" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_12ax52p_di" bpmnElement="SequenceFlow_12ax52p"> + <di:waypoint x="410" y="420" /> + <di:waypoint x="480" y="420" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1e9r8tc_di" bpmnElement="SequenceFlow_1e9r8tc"> + <di:waypoint x="580" y="420" /> + <di:waypoint x="640" y="420" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1i6cshg_di" bpmnElement="SequenceFlow_1i6cshg"> + <di:waypoint x="740" y="420" /> + <di:waypoint x="815" y="420" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0iubb84_di" bpmnElement="ScriptTask_0iubb84"> + <dc:Bounds x="310" y="560" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_102nqyb_di" bpmnElement="SequenceFlow_102nqyb"> + <di:waypoint x="410" y="600" /> + <di:waypoint x="540" y="600" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0f57hgr_di" bpmnElement="SequenceFlow_0f57hgr"> + <di:waypoint x="1240" y="420" /> + <di:waypoint x="1332" y="420" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="IntermediateThrowEvent_1wqbbwo_di" bpmnElement="IntermediateThrowEvent_1u9a1t0"> + <dc:Bounds x="1332" y="402" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1308" y="445" width="87" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1hsbli0_di" bpmnElement="SequenceFlow_1hsbli0"> + <di:waypoint x="215" y="600" /> + <di:waypoint x="310" y="600" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="IntermediateCatchEvent_13yvtam_di" bpmnElement="IntermediateThrowEvent_1lcnqle"> + <dc:Bounds x="179" y="582" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="155" y="625" width="86" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="CallActivity_12eufsa_di" bpmnElement="CallActivity_12eufsa"> + <dc:Bounds x="540" y="560" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1w1h5vl_di" bpmnElement="SequenceFlow_1w1h5vl"> + <di:waypoint x="640" y="600" /> + <di:waypoint x="790" y="600" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1r6lo31_di" bpmnElement="SequenceFlow_1r6lo31"> + <di:waypoint x="840" y="445" /> + <di:waypoint x="840" y="560" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="868" y="463" width="15" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0c01147_di" bpmnElement="SequenceFlow_0c01147"> + <di:waypoint x="1240" y="177" /> + <di:waypoint x="1332" y="177" /> + </bpmndi:BPMNEdge> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/CheckServiceProcessStatus.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/CheckServiceProcessStatus.bpmn new file mode 100644 index 0000000000..279dd2a4ad --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/CheckServiceProcessStatus.bpmn @@ -0,0 +1,225 @@ +<?xml version="1.0" encoding="UTF-8"?> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_0lf96js" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.4.1"> + <bpmn:process id="CheckServiceProcessStatus" name="CheckServiceProcessStatus" isExecutable="true"> + <bpmn:startEvent id="StartEvent_1" name="start check processing status"> + <bpmn:outgoing>SequenceFlow_1g4lx01</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:scriptTask id="ScriptTask_1mlave2" name="Prepare service Check Process status Req " scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0e29y0f</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1n5nl53</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0r1x26k</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def csi= new CheckServiceProcessStatus() +csi.preCheckServiceStatusReq(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:serviceTask id="ServiceTask_0w5fmqn" name="get service Operation Status "> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${getOperationStatus}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_0r1x26k</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_009p8v1</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:scriptTask id="ScriptTask_0z37e29" name="handler service status Response " scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_009p8v1</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0yws8fh</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def csi= new CheckServiceProcessStatus() +csi.handlerServiceStatusResp(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:exclusiveGateway id="ExclusiveGateway_0gk7p3l" name="Is service process finished? " default="SequenceFlow_01o92x6"> + <bpmn:incoming>SequenceFlow_0yws8fh</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_18jgpa8</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_01o92x6</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:scriptTask id="ScriptTask_1ao91w3" name="Time Delay" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1pxnqsp</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1ktr440</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0e29y0f</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def csi= new CheckServiceProcessStatus() +csi.timeWaitDelay(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_0e29y0f" sourceRef="ScriptTask_1ao91w3" targetRef="ScriptTask_1mlave2" /> + <bpmn:sequenceFlow id="SequenceFlow_0r1x26k" sourceRef="ScriptTask_1mlave2" targetRef="ServiceTask_0w5fmqn" /> + <bpmn:sequenceFlow id="SequenceFlow_009p8v1" sourceRef="ServiceTask_0w5fmqn" targetRef="ScriptTask_0z37e29" /> + <bpmn:sequenceFlow id="SequenceFlow_0yws8fh" sourceRef="ScriptTask_0z37e29" targetRef="ExclusiveGateway_0gk7p3l" /> + <bpmn:sequenceFlow id="SequenceFlow_18jgpa8" name="yes" sourceRef="ExclusiveGateway_0gk7p3l" targetRef="EndEvent_0a3w3xw"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{(execution.getVariable("isAllFinished") == "true") || (execution.getVariable("isTimeOut") == "YES")}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:endEvent id="EndEvent_0a3w3xw"> + <bpmn:incoming>SequenceFlow_18jgpa8</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_1g4lx01" sourceRef="StartEvent_1" targetRef="Task_1djj44q" /> + <bpmn:sequenceFlow id="SequenceFlow_1n5nl53" sourceRef="Task_1djj44q" targetRef="ScriptTask_1mlave2" /> + <bpmn:scriptTask id="Task_1djj44q" name="Prepare request" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1g4lx01</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1n5nl53</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def csi= new CheckServiceProcessStatus() +csi.preProcessRequest(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:scriptTask id="ScriptTask_0oic8cv" name="prepare Update Service Operation progress" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0591ght</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1q8dls4</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def csi= new CheckServiceProcessStatus() +csi.preUpdateOperationProgress(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_1q8dls4" sourceRef="ScriptTask_0oic8cv" targetRef="ServiceTask_1b60rre" /> + <bpmn:serviceTask id="ServiceTask_1b60rre" name="Update Service Operation Status"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${updateOperationStatus}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="CSMF_dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="CSMF_dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_1q8dls4</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1pxnqsp</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_1pxnqsp" sourceRef="ServiceTask_1b60rre" targetRef="ScriptTask_1ao91w3" /> + <bpmn:sequenceFlow id="SequenceFlow_01o92x6" sourceRef="ExclusiveGateway_0gk7p3l" targetRef="ExclusiveGateway_1pdfjh4" /> + <bpmn:exclusiveGateway id="ExclusiveGateway_1pdfjh4" name="isNeedUpdateDB? " default="SequenceFlow_1ktr440"> + <bpmn:incoming>SequenceFlow_01o92x6</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0591ght</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_1ktr440</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:sequenceFlow id="SequenceFlow_0591ght" name="yes" sourceRef="ExclusiveGateway_1pdfjh4" targetRef="ScriptTask_0oic8cv"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{(execution.getVariable("isNeedUpdateDB" ) == true)}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_1ktr440" name="no" sourceRef="ExclusiveGateway_1pdfjh4" targetRef="ScriptTask_1ao91w3" /> + </bpmn:process> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="CheckServiceProcessStatus"> + <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1"> + <dc:Bounds x="179" y="159" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="156" y="202" width="87" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_1mlave2_di" bpmnElement="ScriptTask_1mlave2"> + <dc:Bounds x="460" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_0w5fmqn_di" bpmnElement="ServiceTask_0w5fmqn"> + <dc:Bounds x="610" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_0z37e29_di" bpmnElement="ScriptTask_0z37e29"> + <dc:Bounds x="770" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ExclusiveGateway_0gk7p3l_di" bpmnElement="ExclusiveGateway_0gk7p3l" isMarkerVisible="true"> + <dc:Bounds x="955" y="152" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="944" y="122" width="89" height="40" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_1ao91w3_di" bpmnElement="ScriptTask_1ao91w3"> + <dc:Bounds x="460" y="290" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0e29y0f_di" bpmnElement="SequenceFlow_0e29y0f"> + <di:waypoint x="510" y="290" /> + <di:waypoint x="510" y="217" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0r1x26k_di" bpmnElement="SequenceFlow_0r1x26k"> + <di:waypoint x="560" y="177" /> + <di:waypoint x="610" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_009p8v1_di" bpmnElement="SequenceFlow_009p8v1"> + <di:waypoint x="710" y="177" /> + <di:waypoint x="770" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0yws8fh_di" bpmnElement="SequenceFlow_0yws8fh"> + <di:waypoint x="870" y="177" /> + <di:waypoint x="955" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_18jgpa8_di" bpmnElement="SequenceFlow_18jgpa8"> + <di:waypoint x="1005" y="177" /> + <di:waypoint x="1132" y="177" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1024" y="159" width="17" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_0a3w3xw_di" bpmnElement="EndEvent_0a3w3xw"> + <dc:Bounds x="1132" y="159" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1g4lx01_di" bpmnElement="SequenceFlow_1g4lx01"> + <di:waypoint x="215" y="177" /> + <di:waypoint x="270" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1n5nl53_di" bpmnElement="SequenceFlow_1n5nl53"> + <di:waypoint x="370" y="177" /> + <di:waypoint x="460" y="177" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_1di7x3h_di" bpmnElement="Task_1djj44q"> + <dc:Bounds x="270" y="137" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_0oic8cv_di" bpmnElement="ScriptTask_0oic8cv"> + <dc:Bounds x="930" y="430" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1q8dls4_di" bpmnElement="SequenceFlow_1q8dls4"> + <di:waypoint x="930" y="470" /> + <di:waypoint x="780" y="470" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ServiceTask_1b60rre_di" bpmnElement="ServiceTask_1b60rre"> + <dc:Bounds x="680" y="430" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1pxnqsp_di" bpmnElement="SequenceFlow_1pxnqsp"> + <di:waypoint x="680" y="470" /> + <di:waypoint x="510" y="470" /> + <di:waypoint x="510" y="370" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_01o92x6_di" bpmnElement="SequenceFlow_01o92x6"> + <di:waypoint x="980" y="202" /> + <di:waypoint x="980" y="305" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="964" y="243" width="13" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ExclusiveGateway_1pdfjh4_di" bpmnElement="ExclusiveGateway_1pdfjh4" isMarkerVisible="true"> + <dc:Bounds x="955" y="305" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1007" y="310" width="86" height="40" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0591ght_di" bpmnElement="SequenceFlow_0591ght"> + <di:waypoint x="980" y="355" /> + <di:waypoint x="980" y="430" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="987" y="390" width="17" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1ktr440_di" bpmnElement="SequenceFlow_1ktr440"> + <di:waypoint x="955" y="330" /> + <di:waypoint x="560" y="330" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="751" y="312" width="13" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeallocateNSSI.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeallocateNSSI.bpmn new file mode 100644 index 0000000000..db805ecb92 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeallocateNSSI.bpmn @@ -0,0 +1,254 @@ +<?xml version="1.0" encoding="UTF-8"?> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_0884541" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.4.1"> + <bpmn:process id="DoDeallocateNSSIV1" name="DoDeallocateNSSIV1" isExecutable="true"> + <bpmn:startEvent id="StartEvent_1" name="start"> + <bpmn:outgoing>SequenceFlow_05jfhy6</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:sequenceFlow id="SequenceFlow_05jfhy6" sourceRef="StartEvent_1" targetRef="Task_1vste9s" /> + <bpmn:scriptTask id="Task_1m8upus" name="Prepare Decompose Service" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0eug5nv</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0wlyy5i</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.prepareDecomposeService(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_0wlyy5i" sourceRef="Task_1m8upus" targetRef="Task_1giechg" /> + <bpmn:callActivity id="Task_1giechg" name="Call Decompose Service" calledElement="DecomposeService"> + <bpmn:extensionElements> + <camunda:in source="msoRequestId" target="msoRequestId" /> + <camunda:in source="serviceInstanceId" target="serviceInstanceId" /> + <camunda:in source="serviceModelInfo" target="serviceModelInfo" /> + <camunda:out source="serviceDecomposition" target="serviceDecomposition" /> + <camunda:out source="serviceDecompositionString" target="serviceDecompositionString" /> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_0wlyy5i</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1e451y9</bpmn:outgoing> + </bpmn:callActivity> + <bpmn:sequenceFlow id="SequenceFlow_1e451y9" sourceRef="Task_1giechg" targetRef="Task_15ut397" /> + <bpmn:scriptTask id="Task_15ut397" name="processDecomposition" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1e451y9</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1e7o57n</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.processDecomposition(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_1e7o57n" sourceRef="Task_15ut397" targetRef="Task_0vi4ijv" /> + <bpmn:scriptTask id="Task_0vi4ijv" name="Send deallocate request to NSSMF" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1e7o57n</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_03b0822</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.sendRequestToNSSMF(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_03b0822" sourceRef="Task_0vi4ijv" targetRef="Task_0kl6lcq" /> + <bpmn:scriptTask id="Task_0kl6lcq" name="Query Job Status" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_03b0822</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1anlirk</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1jj0p5q</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.getJobStatus(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_1jj0p5q" sourceRef="Task_0kl6lcq" targetRef="ExclusiveGateway_0nhfsui" /> + <bpmn:exclusiveGateway id="ExclusiveGateway_0nhfsui" name="Is deallocate finish?" default="SequenceFlow_0sfh52b"> + <bpmn:incoming>SequenceFlow_1jj0p5q</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0xq380j</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_0sfh52b</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:scriptTask id="Task_13vaezk" name="Delete Slice Profile From AAI" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0xq380j</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1ii5002</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.delSliceProfileFromAAI(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:endEvent id="EndEvent_1f579t4" name="end"> + <bpmn:incoming>SequenceFlow_1ii5002</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_1ii5002" sourceRef="Task_13vaezk" targetRef="EndEvent_1f579t4" /> + <bpmn:sequenceFlow id="SequenceFlow_0xq380j" name="yes" sourceRef="ExclusiveGateway_0nhfsui" targetRef="Task_13vaezk"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{(execution.getVariable("isNSSIDeAllocated" ) == true)}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_0eug5nv" sourceRef="Task_1vste9s" targetRef="Task_1m8upus" /> + <bpmn:scriptTask id="Task_1vste9s" name="PreProcess Incoming Request" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_05jfhy6</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0eug5nv</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.preProcessRequest(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:sequenceFlow id="SequenceFlow_1anlirk" sourceRef="Task_0fxuz4i" targetRef="Task_0kl6lcq" /> + <bpmn:scriptTask id="Task_0fxuz4i" name="TimeDelay" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_1ugva41</bpmn:incoming> + <bpmn:incoming>SequenceFlow_1u66wjs</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1anlirk</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.timeDelay(execution)</bpmn:script> + </bpmn:scriptTask> + <bpmn:serviceTask id="Task_0amt4hu" name="Update Service Operation Status"> + <bpmn:extensionElements> + <camunda:connector> + <camunda:inputOutput> + <camunda:inputParameter name="url">${dbAdapterEndpoint}</camunda:inputParameter> + <camunda:inputParameter name="headers"> + <camunda:map> + <camunda:entry key="content-type">application/soap+xml</camunda:entry> + <camunda:entry key="Authorization">Basic YnBlbDpwYXNzd29yZDEk</camunda:entry> + </camunda:map> + </camunda:inputParameter> + <camunda:inputParameter name="payload">${updateOperationStatus}</camunda:inputParameter> + <camunda:inputParameter name="method">POST</camunda:inputParameter> + <camunda:outputParameter name="DeNSSI_dbResponseCode">${statusCode}</camunda:outputParameter> + <camunda:outputParameter name="DeNSSI_dbResponse">${response}</camunda:outputParameter> + </camunda:inputOutput> + <camunda:connectorId>http-connector</camunda:connectorId> + </camunda:connector> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_04vg0c2</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1ugva41</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:exclusiveGateway id="ExclusiveGateway_0y0w592" name="IsNeedUpdateDB?" default="SequenceFlow_1u66wjs"> + <bpmn:incoming>SequenceFlow_0sfh52b</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0r95j9m</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_1u66wjs</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:sequenceFlow id="SequenceFlow_0sfh52b" sourceRef="ExclusiveGateway_0nhfsui" targetRef="ExclusiveGateway_0y0w592" /> + <bpmn:sequenceFlow id="SequenceFlow_0r95j9m" sourceRef="ExclusiveGateway_0y0w592" targetRef="Task_1renmzf"> + <bpmn:documentation>#{(execution.getVariable("isNeedUpdateDB" ) == true)}</bpmn:documentation> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{(execution.getVariable("isNeedUpdateDB" ) == true)}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_04vg0c2" sourceRef="Task_1renmzf" targetRef="Task_0amt4hu" /> + <bpmn:sequenceFlow id="SequenceFlow_1ugva41" sourceRef="Task_0amt4hu" targetRef="Task_0fxuz4i" /> + <bpmn:sequenceFlow id="SequenceFlow_1u66wjs" sourceRef="ExclusiveGateway_0y0w592" targetRef="Task_0fxuz4i" /> + <bpmn:scriptTask id="Task_1renmzf" name="Prepare Update Operation Status" scriptFormat="groovy"> + <bpmn:incoming>SequenceFlow_0r95j9m</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_04vg0c2</bpmn:outgoing> + <bpmn:script>import org.onap.so.bpmn.infrastructure.scripts.* +def dnssi= new DoDeallocateNSSI() +dnssi.handleJobStatus(execution)</bpmn:script> + </bpmn:scriptTask> + </bpmn:process> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="DoDeallocateNSSIV1"> + <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1"> + <dc:Bounds x="192" y="112" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="199" y="155" width="22" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_05jfhy6_di" bpmnElement="SequenceFlow_05jfhy6"> + <di:waypoint x="228" y="130" /> + <di:waypoint x="310" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_159g5ey_di" bpmnElement="Task_1m8upus"> + <dc:Bounds x="490" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0wlyy5i_di" bpmnElement="SequenceFlow_0wlyy5i"> + <di:waypoint x="590" y="130" /> + <di:waypoint x="660" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="CallActivity_1ep4ama_di" bpmnElement="Task_1giechg"> + <dc:Bounds x="660" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1e451y9_di" bpmnElement="SequenceFlow_1e451y9"> + <di:waypoint x="760" y="130" /> + <di:waypoint x="820" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_1yt5s46_di" bpmnElement="Task_15ut397"> + <dc:Bounds x="820" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1e7o57n_di" bpmnElement="SequenceFlow_1e7o57n"> + <di:waypoint x="920" y="130" /> + <di:waypoint x="970" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_16dxpvz_di" bpmnElement="Task_0vi4ijv"> + <dc:Bounds x="970" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_03b0822_di" bpmnElement="SequenceFlow_03b0822"> + <di:waypoint x="1070" y="130" /> + <di:waypoint x="1120" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0arl3j9_di" bpmnElement="Task_0kl6lcq"> + <dc:Bounds x="1120" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1jj0p5q_di" bpmnElement="SequenceFlow_1jj0p5q"> + <di:waypoint x="1220" y="130" /> + <di:waypoint x="1505" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ExclusiveGateway_0nhfsui_di" bpmnElement="ExclusiveGateway_0nhfsui" isMarkerVisible="true"> + <dc:Bounds x="1505" y="105" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1501" y="75" width="63" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ScriptTask_1rfdrw3_di" bpmnElement="Task_13vaezk"> + <dc:Bounds x="1690" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="EndEvent_1f579t4_di" bpmnElement="EndEvent_1f579t4"> + <dc:Bounds x="1862" y="112" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1871" y="155" width="19" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1ii5002_di" bpmnElement="SequenceFlow_1ii5002"> + <di:waypoint x="1790" y="130" /> + <di:waypoint x="1862" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0xq380j_di" bpmnElement="SequenceFlow_0xq380j"> + <di:waypoint x="1555" y="130" /> + <di:waypoint x="1690" y="130" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1614" y="112" width="17" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0eug5nv_di" bpmnElement="SequenceFlow_0eug5nv"> + <di:waypoint x="410" y="130" /> + <di:waypoint x="490" y="130" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_1dytya8_di" bpmnElement="Task_1vste9s"> + <dc:Bounds x="310" y="90" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1anlirk_di" bpmnElement="SequenceFlow_1anlirk"> + <di:waypoint x="1170" y="190" /> + <di:waypoint x="1170" y="170" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_0a4zalz_di" bpmnElement="Task_0fxuz4i"> + <dc:Bounds x="1120" y="190" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_0vegqix_di" bpmnElement="Task_0amt4hu"> + <dc:Bounds x="1280" y="300" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ExclusiveGateway_0y0w592_di" bpmnElement="ExclusiveGateway_0y0w592" isMarkerVisible="true"> + <dc:Bounds x="1505" y="205" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1567" y="216" width="86" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0sfh52b_di" bpmnElement="SequenceFlow_0sfh52b"> + <di:waypoint x="1530" y="155" /> + <di:waypoint x="1530" y="205" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0r95j9m_di" bpmnElement="SequenceFlow_0r95j9m"> + <di:waypoint x="1530" y="255" /> + <di:waypoint x="1530" y="300" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_04vg0c2_di" bpmnElement="SequenceFlow_04vg0c2"> + <di:waypoint x="1480" y="340" /> + <di:waypoint x="1380" y="340" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1ugva41_di" bpmnElement="SequenceFlow_1ugva41"> + <di:waypoint x="1280" y="340" /> + <di:waypoint x="1170" y="340" /> + <di:waypoint x="1170" y="270" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1u66wjs_di" bpmnElement="SequenceFlow_1u66wjs"> + <di:waypoint x="1505" y="230" /> + <di:waypoint x="1220" y="230" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ScriptTask_10pw6ot_di" bpmnElement="Task_1renmzf"> + <dc:Bounds x="1480" y="300" width="100" height="80" /> + </bpmndi:BPMNShape> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-tasks/pom.xml b/bpmn/so-bpmn-tasks/pom.xml index d37120b452..14081960e6 100644 --- a/bpmn/so-bpmn-tasks/pom.xml +++ b/bpmn/so-bpmn-tasks/pom.xml @@ -3,7 +3,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>so-bpmn-tasks</artifactId> diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java index 8a6c4c2796..33b60a9ed3 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java @@ -6,6 +6,7 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * Modifications Copyright (c) 2019 Bell Canada. + * Modifications Copyright (c) 2020 Nokia * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,43 +71,21 @@ public class AAIUpdateTasks { /** * BPMN access method to update the status of Service to Assigned in AAI - * - * @param execution */ public void updateOrchestrationStatusAssignedService(BuildingBlockExecution execution) { - try { - ServiceInstance serviceInstance = - extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); - aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, - OrchestrationStatus.ASSIGNED); - execution.setVariable("aaiServiceInstanceRollback", true); - } catch (Exception ex) { - logger.error("Exception occurred in AAIUpdateTasks updateOrchestrationStatusAssignedService", ex); - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); - } + updateOrchestrationStatusForService(execution, OrchestrationStatus.ASSIGNED); + execution.setVariable("aaiServiceInstanceRollback", true); } /** * BPMN access method to update status of Service to Active in AAI - * - * @param execution */ public void updateOrchestrationStatusActiveService(BuildingBlockExecution execution) { - try { - ServiceInstance serviceInstance = - extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); - aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, - OrchestrationStatus.ACTIVE); - } catch (Exception ex) { - logger.error("Exception occurred in AAIUpdateTasks updateOrchestrationStatusActiveService", ex); - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); - } + updateOrchestrationStatusForService(execution, OrchestrationStatus.ACTIVE); } /** * BPMN access method to update status of Pnf to Assigned in AAI - * - * @param execution */ public void updateOrchestrationStatusAssignedPnf(BuildingBlockExecution execution) { updateOrchestrationStatusForPnf(execution, OrchestrationStatus.ASSIGNED); @@ -114,8 +93,6 @@ public class AAIUpdateTasks { /** * BPMN access method to update status of Pnf to Active in AAI - * - * @param execution */ public void updateOrchestrationStatusActivePnf(BuildingBlockExecution execution) { updateOrchestrationStatusForPnf(execution, OrchestrationStatus.ACTIVE); @@ -135,44 +112,18 @@ public class AAIUpdateTasks { updateOrchestrationStatusForPnf(execution, OrchestrationStatus.REGISTERED); } - private void updateOrchestrationStatusForPnf(BuildingBlockExecution execution, OrchestrationStatus status) { - try { - Pnf pnf = extractPojosForBB.extractByKey(execution, ResourceKey.PNF); - aaiPnfResources.updateOrchestrationStatusPnf(pnf, status); - } catch (Exception ex) { - logger.error("Exception occurred in AAIUpdateTasks during update Orchestration Status to {}", status, ex); - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); - } - } - /** * BPMN access method to update status of Vnf to Assigned in AAI - * - * @param execution */ public void updateOrchestrationStatusAssignedVnf(BuildingBlockExecution execution) { - try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); - aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.ASSIGNED); - } catch (Exception ex) { - logger.error("Exception occurred in AAIUpdateTasks updateOrchestrationStatusAssignedVnf", ex); - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); - } + updateOrchestrationStatusForVnf(execution, OrchestrationStatus.ASSIGNED); } /** * BPMN access method to update status of Vnf to Active in AAI - * - * @param execution */ public void updateOrchestrationStatusActiveVnf(BuildingBlockExecution execution) { - try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); - aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.ACTIVE); - } catch (Exception ex) { - logger.error("Exception occurred in AAIUpdateTasks updateOrchestrationStatusActiveVnf", ex); - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); - } + updateOrchestrationStatusForVnf(execution, OrchestrationStatus.ACTIVE); } /** @@ -839,4 +790,38 @@ public class AAIUpdateTasks { throw new IllegalArgumentException("Invalid action to set Orchestration status: " + action); } } + + private void updateOrchestrationStatusForService(BuildingBlockExecution execution, OrchestrationStatus status) { + try { + ServiceInstance serviceInstance = + extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, status); + } catch (Exception ex) { + logger.error("Exception occurred in AAIUpdateTasks during update orchestration status to {} for service", + status, ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + + private void updateOrchestrationStatusForPnf(BuildingBlockExecution execution, OrchestrationStatus status) { + try { + Pnf pnf = extractPojosForBB.extractByKey(execution, ResourceKey.PNF); + aaiPnfResources.updateOrchestrationStatusPnf(pnf, status); + } catch (Exception ex) { + logger.error("Exception occurred in AAIUpdateTasks during update Orchestration Status to {}", status, ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + + private void updateOrchestrationStatusForVnf(BuildingBlockExecution execution, OrchestrationStatus status) { + try { + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + aaiVnfResources.updateOrchestrationStatusVnf(vnf, status); + } catch (Exception ex) { + logger.error("Exception occurred in AAIUpdateTasks during update orchestration status to {} for vnf", + status, ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java index 4285e9aa84..663b097b78 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java @@ -121,7 +121,7 @@ public class VnfAdapterCreateTasks { try { volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); } catch (BBObjectNotFoundException bbException) { - logger.error("Exception occurred if bb objrct not found in VnfAdapterCreateTasks createVfModule ", + logger.error("Exception occurred if bb object not found in VnfAdapterCreateTasks createVfModule ", bbException); } CloudRegion cloudRegion = gBBInput.getCloudRegion(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java index 79ccd9216f..00d0fdc01d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java @@ -6,12 +6,14 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,7 +31,6 @@ import java.util.Optional; import org.onap.so.logger.LoggingAnchor; import org.json.JSONArray; import org.json.JSONObject; -import org.onap.aai.domain.yang.Vserver; import org.onap.appc.client.lcm.model.Action; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.core.json.JsonUtils; @@ -143,7 +144,7 @@ public class AppcRunTasks { ControllerSelectionReference controllerSelectionReference = catalogDbClient .getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, action.toString()); - String controllerType = null; + String controllerType; if (controllerSelectionReference != null) { controllerType = controllerSelectionReference.getControllerName(); } else { @@ -191,13 +192,13 @@ public class AppcRunTasks { logger.error("Error Message: {}", appcMessage); logger.error("ERROR CODE: {}", appcCode); logger.trace("End of runAppCommand "); - if (appcCode != null && !appcCode.equals("0")) { + if (appcCode != null && !"0".equals(appcCode)) { exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(appcCode), appcMessage); } } protected void mapRollbackVariables(BuildingBlockExecution execution, Action action, String appcCode) { - if (appcCode != null && appcCode.equals("0") && action != null) { + if ("0".equals(appcCode) && action != null) { if (action.equals(Action.Lock)) { execution.setVariable(ROLLBACK_VNF_LOCK, true); } else if (action.equals(Action.Unlock)) { @@ -216,7 +217,7 @@ public class AppcRunTasks { private HashMap<String, String> buildPayloadInfo(String vnfName, String aicIdentity, String vnfHostIpAddress, String vmIdList, String vserverIdList, String identityUrl, String vfModuleId) { - HashMap<String, String> payloadInfo = new HashMap<String, String>(); + HashMap<String, String> payloadInfo = new HashMap<>(); payloadInfo.put("vnfName", vnfName); payloadInfo.put("aicIdentity", aicIdentity); payloadInfo.put("vnfHostIpAddress", vnfHostIpAddress); @@ -242,44 +243,39 @@ public class AppcRunTasks { return payload; } - protected void getVserversForAppc(BuildingBlockExecution execution, GenericVnf vnf) throws Exception { + protected void getVserversForAppc(BuildingBlockExecution execution, GenericVnf vnf) throws RuntimeException { AAIResultWrapper aaiRW = aaiVnfResources.queryVnfWrapperById(vnf); - if (aaiRW != null && aaiRW.getRelationships() != null && aaiRW.getRelationships().isPresent()) { - Relationships relationships = aaiRW.getRelationships().get(); - if (relationships != null) { - List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER); - JSONArray vserverIds = new JSONArray(); - JSONArray vserverSelfLinks = new JSONArray(); - if (vserverUris != null) { - for (AAIResourceUri j : vserverUris) { - if (j != null) { - if (j.getURIKeys() != null) { - String vserverId = j.getURIKeys().get("vserver-id"); - vserverIds.put(vserverId); - } - Optional<Vserver> oVserver = aaiVnfResources.getVserver(j); - if (oVserver.isPresent()) { - Vserver vserver = oVserver.get(); - if (vserver != null) { - String vserverSelfLink = vserver.getVserverSelflink(); - vserverSelfLinks.put(vserverSelfLink); - } - } - } + if (aaiRW == null || aaiRW.getRelationships() == null || !aaiRW.getRelationships().isPresent()) { + return; + } + Relationships relationships = aaiRW.getRelationships().get(); + List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER); + JSONArray vserverIds = new JSONArray(); + JSONArray vserverSelfLinks = new JSONArray(); + if (vserverUris != null) { + for (AAIResourceUri j : vserverUris) { + if (j != null) { + if (j.getURIKeys() != null) { + String vserverId = j.getURIKeys().get("vserver-id"); + vserverIds.put(vserverId); } + aaiVnfResources.getVserver(j).ifPresent((vserver) -> { + String vserverSelfLink = vserver.getVserverSelflink(); + vserverSelfLinks.put(vserverSelfLink); + }); } - - JSONObject vmidsArray = new JSONObject(); - JSONObject vserveridsArray = new JSONObject(); - vmidsArray.put("vmIds", vserverSelfLinks.toString()); - vserveridsArray.put("vserverIds", vserverIds.toString()); - logger.debug("vmidsArray is: {}", vmidsArray.toString()); - logger.debug("vserveridsArray is: {}", vserveridsArray.toString()); - - execution.setVariable("vmIdList", vmidsArray.toString()); - execution.setVariable("vserverIdList", vserveridsArray.toString()); } } + + JSONObject vmidsArray = new JSONObject(); + JSONObject vserveridsArray = new JSONObject(); + vmidsArray.put("vmIds", vserverSelfLinks.toString()); + vserveridsArray.put("vserverIds", vserverIds.toString()); + logger.debug("vmidsArray is: {}", vmidsArray.toString()); + logger.debug("vserveridsArray is: {}", vserveridsArray.toString()); + + execution.setVariable("vmIdList", vmidsArray.toString()); + execution.setVariable("vserverIdList", vserveridsArray.toString()); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java index 64f0072991..1cde9fb8f6 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -29,11 +31,9 @@ import org.onap.so.client.exception.BBObjectNotFoundException; import org.onap.so.client.exception.ExceptionBuilder; import org.onap.so.client.exception.OrchestrationStatusValidationException; import org.onap.so.db.catalog.beans.BuildingBlockDetail; -import org.onap.so.db.catalog.beans.OrchestrationAction; import org.onap.so.db.catalog.beans.OrchestrationStatus; import org.onap.so.db.catalog.beans.OrchestrationStatusStateTransitionDirective; import org.onap.so.db.catalog.beans.OrchestrationStatusValidationDirective; -import org.onap.so.db.catalog.beans.ResourceType; import org.onap.so.db.catalog.client.CatalogDbClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,8 +52,6 @@ public class OrchestrationStatusValidator { "Orchestration Status Validation failed. ResourceType=(%s), TargetAction=(%s), OrchestrationStatus=(%s)"; private static final String ORCHESTRATION_STATUS_VALIDATION_RESULT = "orchestrationStatusValidationResult"; private static final String ALACARTE = "aLaCarte"; - private static final String MULTI_STAGE_DESIGN_OFF = "false"; - private static final String MULTI_STAGE_DESIGN_ON = "true"; @Autowired private ExtractPojosForBB extractPojosForBB; @@ -86,7 +84,7 @@ public class OrchestrationStatusValidator { String.format(BUILDING_BLOCK_DETAIL_NOT_FOUND, buildingBlockFlowName)); } - OrchestrationStatus orchestrationStatus = null; + OrchestrationStatus orchestrationStatus; switch (buildingBlockDetail.getResourceType()) { case SERVICE: diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java index 9ee0104a5f..f8a4d910f4 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowAction.java @@ -47,6 +47,7 @@ import org.onap.aai.domain.yang.Vnfc; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.aai.domain.yang.VpnBinding; import org.onap.so.bpmn.common.BBConstants; +import org.onap.so.bpmn.infrastructure.workflow.tasks.utils.WorkflowResourceIdsUtils; import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; @@ -185,7 +186,7 @@ public class WorkflowAction { List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>(); WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution); List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>(); - List<Resource> resourceCounter = new ArrayList<>(); + List<Resource> resourceList = new ArrayList<>(); execution.setVariable("sentSyncResponse", false); execution.setVariable("homing", false); execution.setVariable("calledHoming", false); @@ -304,7 +305,7 @@ public class WorkflowAction { } } if (containsService) { - traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction); + traverseUserParamsService(execution, resourceList, sIRequest, requestAction); } } else { buildAndThrowException(execution, @@ -327,11 +328,10 @@ public class WorkflowAction { } } if (containsService) { - foundRelated = - traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction); + foundRelated = traverseUserParamsService(execution, resourceList, sIRequest, requestAction); } if (!foundRelated) { - traverseCatalogDbService(execution, sIRequest, resourceCounter, aaiResourceIds); + traverseCatalogDbService(execution, sIRequest, resourceList, aaiResourceIds); } } else if (resourceType == WorkflowType.SERVICE && ("activateInstance".equalsIgnoreCase(requestAction) @@ -342,20 +342,20 @@ public class WorkflowAction { // SERVICE-MACRO-DELETE // Will never get user params with service, macro will have // to query the SI in AAI to find related instances. - traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds); + traverseAAIService(execution, resourceList, resourceId, aaiResourceIds); } else if (resourceType == WorkflowType.SERVICE && "deactivateInstance".equalsIgnoreCase(requestAction)) { - resourceCounter.add(new Resource(WorkflowType.SERVICE, "", false)); + resourceList.add(new Resource(WorkflowType.SERVICE, "", false)); } else if (resourceType == WorkflowType.VNF && ("replaceInstance".equalsIgnoreCase(requestAction) || ("recreateInstance".equalsIgnoreCase(requestAction)))) { - traverseAAIVnf(execution, resourceCounter, workflowResourceIds.getServiceInstanceId(), + traverseAAIVnf(execution, resourceList, workflowResourceIds.getServiceInstanceId(), workflowResourceIds.getVnfId(), aaiResourceIds); } else { buildAndThrowException(execution, "Current Macro Request is not supported"); } String foundObjects = ""; for (WorkflowType type : WorkflowType.values()) { - foundObjects = foundObjects + type + " - " + resourceCounter.stream() + foundObjects = foundObjects + type + " - " + resourceList.stream() .filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()).size() + " "; } @@ -370,9 +370,9 @@ public class WorkflowAction { || "replaceInstanceRetainAssignments".equalsIgnoreCase(requestAction))) { vnfReplace = true; } - flowsToExecute = buildExecuteBuildingBlockList(orchFlows, resourceCounter, requestId, apiVersion, + flowsToExecute = buildExecuteBuildingBlockList(orchFlows, resourceList, requestId, apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, vnfReplace); - if (!resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) + if (!resourceList.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) .collect(Collectors.toList()).isEmpty()) { logger.info("Sorting for Vlan Tagging"); flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction); @@ -380,16 +380,16 @@ public class WorkflowAction { // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE if (resourceType == WorkflowType.SERVICE && (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE)) - && !resourceCounter.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType())) + && !resourceList.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType())) .collect(Collectors.toList()).isEmpty()) { execution.setVariable("homing", true); execution.setVariable("calledHoming", false); } if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE) || requestAction.equalsIgnoreCase(CREATEINSTANCE))) { - generateResourceIds(flowsToExecute, resourceCounter, serviceInstanceId); + generateResourceIds(flowsToExecute, resourceList, serviceInstanceId); } else { - updateResourceIdsFromAAITraversal(flowsToExecute, resourceCounter, aaiResourceIds, + updateResourceIdsFromAAITraversal(flowsToExecute, resourceList, aaiResourceIds, serviceInstanceId); } } @@ -471,9 +471,7 @@ public class WorkflowAction { List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(type); for (AAIResultWrapper vnfcResultWrapper : vnfcResultWrappers) { Optional<T> vnfcOp = vnfcResultWrapper.asBean(resultClass); - if (vnfcOp.isPresent()) { - vnfcs.add(vnfcOp.get()); - } + vnfcOp.ifPresent(vnfcs::add); } } return vnfcs; @@ -493,9 +491,7 @@ public class WorkflowAction { this.getResultWrappersFromRelationships(relationships, type); for (AAIResultWrapper configurationResultWrapper : configurationResultWrappers) { Optional<T> configurationOp = configurationResultWrapper.asBean(resultClass); - if (configurationOp.isPresent()) { - configurations.add(configurationOp.get()); - } + configurationOp.ifPresent(configurations::add); } } return configurations; @@ -574,8 +570,6 @@ public class WorkflowAction { protected List<OrchestrationFlow> getVfModuleReplaceBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) throws Exception { - List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>(); - String vnfId = dataObj.getWorkflowResourceIds().getVnfId(); String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId(); @@ -639,19 +633,15 @@ public class WorkflowAction { if (!relationshipsOp.isPresent()) { logger.debug("No relationships were found for Configuration in AAI"); return null; - } else { - Relationships relationships = relationshipsOp.get(); - List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(AAIObjectType.VNFC); - if (vnfcResultWrappers.size() > 1 || vnfcResultWrappers.isEmpty()) { - logger.debug("Too many vnfcs or no vnfc found that are related to configuration"); - } - Optional<Vnfc> vnfcOp = vnfcResultWrappers.get(0).asBean(Vnfc.class); - if (vnfcOp.isPresent()) { - return vnfcOp.get().getVnfcName(); - } else { - return null; - } } + Relationships relationships = relationshipsOp.get(); + List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(AAIObjectType.VNFC); + if (vnfcResultWrappers.size() > 1 || vnfcResultWrappers.isEmpty()) { + logger.debug("Too many vnfcs or no vnfc found that are related to configuration"); + } + Optional<Vnfc> vnfcOp = vnfcResultWrappers.get(0).asBean(Vnfc.class); + return vnfcOp.map(Vnfc::getVnfcName).orElse(null); + } protected List<Resource> sortVfModulesByBaseFirst(List<Resource> vfModuleResources) { @@ -679,18 +669,15 @@ public class WorkflowAction { } private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute, - List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) { + List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) { for (Pair<WorkflowType, String> pair : aaiResourceIds) { logger.debug(pair.getValue0() + ", " + pair.getValue1()); } Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> { - List<Resource> resources = - resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()); - for (int i = 0; i < resources.size(); i++) { - updateWorkflowResourceIds(flowsToExecute, type, resources.get(i).getResourceId(), - retrieveAAIResourceId(aaiResourceIds, type), null, serviceInstanceId); - } + resourceList.stream().filter(resource -> type.equals(resource.getResourceType())) + .forEach(resource -> updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), + retrieveAAIResourceId(aaiResourceIds, type), null, serviceInstanceId)); }); } @@ -706,21 +693,16 @@ public class WorkflowAction { return id; } - private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceCounter, + private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceList, String serviceInstanceId) { Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> { - List<Resource> resources = - resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()); - for (int i = 0; i < resources.size(); i++) { - Resource resource = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())) - .collect(Collectors.toList()).get(i); - updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), null, - resource.getVirtualLinkKey(), serviceInstanceId); - } + resourceList.stream().filter(resource -> type.equals(resource.getResourceType())) + .forEach(resource -> updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), null, + resource.getVirtualLinkKey(), serviceInstanceId)); }); } - protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resource, + protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resourceType, String key, String id, String virtualLinkKey, String serviceInstanceId) { String resourceId = id; if (resourceId == null) { @@ -728,24 +710,10 @@ public class WorkflowAction { } for (ExecuteBuildingBlock ebb : flowsToExecute) { if (key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey()) - && ebb.getBuildingBlock().getBpmnFlowName().contains(resource.toString())) { + && ebb.getBuildingBlock().getBpmnFlowName().contains(resourceType.toString())) { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId(serviceInstanceId); - if (resource == WorkflowType.VNF) { - workflowResourceIds.setVnfId(resourceId); - } else if (resource == WorkflowType.PNF) { - workflowResourceIds.setPnfId(resourceId); - } else if (resource == WorkflowType.VFMODULE) { - workflowResourceIds.setVfModuleId(resourceId); - } else if (resource == WorkflowType.VOLUMEGROUP) { - workflowResourceIds.setVolumeGroupId(resourceId); - } else if (resource == WorkflowType.NETWORK) { - workflowResourceIds.setNetworkId(resourceId); - } else if (resource == WorkflowType.NETWORKCOLLECTION) { - workflowResourceIds.setNetworkCollectionId(resourceId); - } else if (resource == WorkflowType.CONFIGURATION) { - workflowResourceIds.setConfigurationId(resourceId); - } + WorkflowResourceIdsUtils.setResourceIdByWorkflowType(workflowResourceIds, resourceType, resourceId); ebb.setWorkflowResourceIds(workflowResourceIds); } if (virtualLinkKey != null && ebb.getBuildingBlock().isVirtualLink() @@ -779,29 +747,28 @@ public class WorkflowAction { } protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest, - List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds) + List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds) throws JsonProcessingException, VrfBondingServiceException { String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId(); org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID); if (service == null) { buildAndThrowException(execution, "Could not find the service model in catalog db."); } else { - resourceCounter.add(new Resource(WorkflowType.SERVICE, service.getModelUUID(), false)); + resourceList.add(new Resource(WorkflowType.SERVICE, service.getModelUUID(), false)); RelatedInstance relatedVpnBinding = bbInputSetupUtils.getRelatedInstanceByType(sIRequest.getRequestDetails(), ModelType.vpnBinding); RelatedInstance relatedLocalNetwork = bbInputSetupUtils.getRelatedInstanceByType(sIRequest.getRequestDetails(), ModelType.network); if (relatedVpnBinding != null && relatedLocalNetwork != null) { - traverseVrfConfiguration(aaiResourceIds, resourceCounter, service, relatedVpnBinding, - relatedLocalNetwork); + traverseVrfConfiguration(aaiResourceIds, resourceList, service, relatedVpnBinding, relatedLocalNetwork); } else { - traverseNetworkCollection(execution, resourceCounter, service); + traverseNetworkCollection(execution, resourceList, service); } } } protected void traverseVrfConfiguration(List<Pair<WorkflowType, String>> aaiResourceIds, - List<Resource> resourceCounter, org.onap.so.db.catalog.beans.Service service, + List<Resource> resourceList, org.onap.so.db.catalog.beans.Service service, RelatedInstance relatedVpnBinding, RelatedInstance relatedLocalNetwork) throws VrfBondingServiceException, JsonProcessingException { org.onap.aai.domain.yang.L3Network aaiLocalNetwork = @@ -816,9 +783,9 @@ public class WorkflowAction { vrfValidation.aaiRouteTargetValidation(aaiLocalNetwork); String existingAAIVrfConfiguration = getExistingAAIVrfConfiguration(relatedVpnBinding, aaiLocalNetwork); if (existingAAIVrfConfiguration != null) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, existingAAIVrfConfiguration)); + aaiResourceIds.add(new Pair<>(WorkflowType.CONFIGURATION, existingAAIVrfConfiguration)); } - resourceCounter.add(new Resource(WorkflowType.CONFIGURATION, + resourceList.add(new Resource(WorkflowType.CONFIGURATION, service.getConfigurationCustomizations().get(0).getModelCustomizationUUID(), false)); } @@ -869,7 +836,7 @@ public class WorkflowAction { return false; } - protected void traverseNetworkCollection(DelegateExecution execution, List<Resource> resourceCounter, + protected void traverseNetworkCollection(DelegateExecution execution, List<Resource> resourceList, org.onap.so.db.catalog.beans.Service service) { if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) { List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations(); @@ -879,7 +846,7 @@ public class WorkflowAction { CollectionResourceCustomization collectionResourceCustomization = findCatalogNetworkCollection(execution, service); if (collectionResourceCustomization != null) { - resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION, + resourceList.add(new Resource(WorkflowType.NETWORKCOLLECTION, collectionResourceCustomization.getModelCustomizationUUID(), false)); logger.debug("Found a network collection"); if (collectionResourceCustomization.getCollectionResource() != null) { @@ -921,7 +888,7 @@ public class WorkflowAction { Resource resource = new Resource(WorkflowType.VIRTUAL_LINK, collectionNetworkResourceCust.getModelCustomizationUUID(), false); resource.setVirtualLinkKey(Integer.toString(i)); - resourceCounter.add(resource); + resourceList.add(resource); } } } else { @@ -938,13 +905,13 @@ public class WorkflowAction { logger.debug("No Network Collection Customization found"); } } - if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) + if (resourceList.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) .collect(Collectors.toList()).isEmpty()) { if (service.getNetworkCustomizations() == null) { logger.debug("No networks were found on this service model"); } else { for (int i = 0; i < service.getNetworkCustomizations().size(); i++) { - resourceCounter.add(new Resource(WorkflowType.NETWORK, + resourceList.add(new Resource(WorkflowType.NETWORK, service.getNetworkCustomizations().get(i).getModelCustomizationUUID(), false)); } } @@ -955,32 +922,30 @@ public class WorkflowAction { } } - protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceCounter, String resourceId, + protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceList, String resourceId, List<Pair<WorkflowType, String>> aaiResourceIds) { try { ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(resourceId); org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup.getExistingServiceInstance(serviceInstanceAAI); - resourceCounter.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false)); + resourceList.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false)); if (serviceInstanceMSO.getVnfs() != null) { for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId())); - resourceCounter.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false)); + aaiResourceIds.add(new Pair<>(WorkflowType.VNF, vnf.getVnfId())); + resourceList.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false)); if (vnf.getVfModules() != null) { for (VfModule vfModule : vnf.getVfModules()) { - aaiResourceIds.add( - new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId())); + aaiResourceIds.add(new Pair<>(WorkflowType.VFMODULE, vfModule.getVfModuleId())); Resource resource = new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false); resource.setBaseVfModule(vfModule.getModelInfoVfModule().getIsBaseBoolean()); - resourceCounter.add(resource); + resourceList.add(resource); } } if (vnf.getVolumeGroups() != null) { for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf .getVolumeGroups()) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, - volumeGroup.getVolumeGroupId())); - resourceCounter + aaiResourceIds.add(new Pair<>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId())); + resourceList .add(new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false)); } } @@ -989,15 +954,15 @@ public class WorkflowAction { if (serviceInstanceMSO.getNetworks() != null) { for (org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network : serviceInstanceMSO .getNetworks()) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORK, network.getNetworkId())); - resourceCounter.add(new Resource(WorkflowType.NETWORK, network.getNetworkId(), false)); + aaiResourceIds.add(new Pair<>(WorkflowType.NETWORK, network.getNetworkId())); + resourceList.add(new Resource(WorkflowType.NETWORK, network.getNetworkId(), false)); } } if (serviceInstanceMSO.getCollection() != null) { logger.debug("found networkcollection"); - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORKCOLLECTION, - serviceInstanceMSO.getCollection().getId())); - resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION, + aaiResourceIds + .add(new Pair<>(WorkflowType.NETWORKCOLLECTION, serviceInstanceMSO.getCollection().getId())); + resourceList.add(new Resource(WorkflowType.NETWORKCOLLECTION, serviceInstanceMSO.getCollection().getId(), false)); } if (serviceInstanceMSO.getConfigurations() != null) { @@ -1008,9 +973,8 @@ public class WorkflowAction { for (Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()) { if (relationship.getRelatedTo().contains("vnfc") || relationship.getRelatedTo().contains("vpn-binding")) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, - config.getConfigurationId())); - resourceCounter.add( + aaiResourceIds.add(new Pair<>(WorkflowType.CONFIGURATION, config.getConfigurationId())); + resourceList.add( new Resource(WorkflowType.CONFIGURATION, config.getConfigurationId(), false)); break; } @@ -1025,34 +989,32 @@ public class WorkflowAction { } } - private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceCounter, String serviceId, + private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceList, String serviceId, String vnfId, List<Pair<WorkflowType, String>> aaiResourceIds) { try { ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId); org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup.getExistingServiceInstance(serviceInstanceAAI); - resourceCounter.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false)); + resourceList.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false)); if (serviceInstanceMSO.getVnfs() != null) { for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) { if (vnf.getVnfId().equals(vnfId)) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId())); - resourceCounter.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false)); + aaiResourceIds.add(new Pair<>(WorkflowType.VNF, vnf.getVnfId())); + resourceList.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false)); if (vnf.getVfModules() != null) { for (VfModule vfModule : vnf.getVfModules()) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, - vfModule.getVfModuleId())); - resourceCounter - .add(new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false)); + aaiResourceIds.add(new Pair<>(WorkflowType.VFMODULE, vfModule.getVfModuleId())); + resourceList.add(new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false)); findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(), - resourceCounter, aaiResourceIds); + resourceList, aaiResourceIds); } } if (vnf.getVolumeGroups() != null) { for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf .getVolumeGroups()) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, - volumeGroup.getVolumeGroupId())); - resourceCounter.add( + aaiResourceIds + .add(new Pair<>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId())); + resourceList.add( new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false)); } } @@ -1068,7 +1030,7 @@ public class WorkflowAction { } private void findConfigurationsInsideVfModule(DelegateExecution execution, String vnfId, String vfModuleId, - List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds) { + List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds) { try { org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId); AAIResultWrapper vfModuleWrapper = new AAIResultWrapper( @@ -1081,9 +1043,8 @@ public class WorkflowAction { Optional<Configuration> config = workflowActionUtils.extractRelationshipsConfiguration(relationshipsOp.get()); if (config.isPresent()) { - aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, - config.get().getConfigurationId())); - resourceCounter.add( + aaiResourceIds.add(new Pair<>(WorkflowType.CONFIGURATION, config.get().getConfigurationId())); + resourceList.add( new Resource(WorkflowType.CONFIGURATION, config.get().getConfigurationId(), false)); } } @@ -1094,7 +1055,7 @@ public class WorkflowAction { } } - protected boolean traverseUserParamsService(DelegateExecution execution, List<Resource> resourceCounter, + protected boolean traverseUserParamsService(DelegateExecution execution, List<Resource> resourceList, ServiceInstancesRequest sIRequest, String requestAction) throws IOException { boolean foundRelated = false; boolean foundVfModuleOrVG = false; @@ -1107,11 +1068,11 @@ public class WorkflowAction { ObjectMapper obj = new ObjectMapper(); String input = obj.writeValueAsString(params.get(USERPARAMSERVICE)); Service validate = obj.readValue(input, Service.class); - resourceCounter.add( + resourceList.add( new Resource(WorkflowType.SERVICE, validate.getModelInfo().getModelVersionId(), false)); if (validate.getResources().getVnfs() != null) { for (Vnfs vnf : validate.getResources().getVnfs()) { - resourceCounter.add(new Resource(WorkflowType.VNF, + resourceList.add(new Resource(WorkflowType.VNF, vnf.getModelInfo().getModelCustomizationId(), false)); foundRelated = true; if (vnf.getModelInfo() != null && vnf.getModelInfo().getModelCustomizationUuid() != null) { @@ -1127,7 +1088,7 @@ public class WorkflowAction { if (vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null && vfModuleCustomization.getVolumeHeatEnv() != null) { - resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP, + resourceList.add(new Resource(WorkflowType.VOLUMEGROUP, vfModuleCustomization.getModelCustomizationUUID(), false)); foundRelated = true; foundVfModuleOrVG = true; @@ -1146,7 +1107,7 @@ public class WorkflowAction { } else { resource.setBaseVfModule(false); } - resourceCounter.add(resource); + resourceList.add(resource); if (vfModule.getModelInfo() != null && vfModule.getModelInfo().getModelCustomizationUuid() != null) { vfModuleCustomizationUUID = @@ -1165,7 +1126,7 @@ public class WorkflowAction { vnf.getModelInfo().getModelCustomizationId()); resource.setVfModuleCustomizationId( vfModule.getModelInfo().getModelCustomizationId()); - resourceCounter.add(configResource); + resourceList.add(configResource); } } } @@ -1180,22 +1141,21 @@ public class WorkflowAction { } if (validate.getResources().getPnfs() != null) { for (Pnfs pnf : validate.getResources().getPnfs()) { - resourceCounter.add(new Resource(WorkflowType.PNF, + resourceList.add(new Resource(WorkflowType.PNF, pnf.getModelInfo().getModelCustomizationId(), false)); foundRelated = true; } } if (validate.getResources().getNetworks() != null) { for (Networks network : validate.getResources().getNetworks()) { - resourceCounter.add(new Resource(WorkflowType.NETWORK, + resourceList.add(new Resource(WorkflowType.NETWORK, network.getModelInfo().getModelCustomizationId(), false)); foundRelated = true; } if (requestAction.equals(CREATEINSTANCE)) { String networkColCustId = queryCatalogDBforNetworkCollection(execution, sIRequest); if (networkColCustId != null) { - resourceCounter - .add(new Resource(WorkflowType.NETWORKCOLLECTION, networkColCustId, false)); + resourceList.add(new Resource(WorkflowType.NETWORKCOLLECTION, networkColCustId, false)); foundRelated = true; } } @@ -1242,21 +1202,14 @@ public class WorkflowAction { } protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) { - WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); - workflowResourceIds.setServiceInstanceId((String) execution.getVariable("serviceInstanceId")); - workflowResourceIds.setNetworkId((String) execution.getVariable("networkId")); - workflowResourceIds.setVfModuleId((String) execution.getVariable("vfModuleId")); - workflowResourceIds.setVnfId((String) execution.getVariable("vnfId")); - workflowResourceIds.setVolumeGroupId((String) execution.getVariable("volumeGroupId")); - workflowResourceIds.setInstanceGroupId((String) execution.getVariable("instanceGroupId")); - return workflowResourceIds; + return WorkflowResourceIdsUtils.getWorkflowResourceIdsFromExecution(execution); } protected Resource extractResourceIdAndTypeFromUri(String uri) { Pattern patt = Pattern.compile("[vV]\\d+.*?(?:(?:/(?<type>" + SUPPORTEDTYPES + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?(?:/resume)?)?$"); Matcher m = patt.matcher(uri); - Boolean generated = false; + boolean generated = false; if (m.find()) { logger.debug("found match on {} : {} ", uri, m); @@ -1366,7 +1319,7 @@ public class WorkflowAction { } else if (ebb.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB) || ebb.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)) { continue; - } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) { + } else if (!"".equals(ebb.getBuildingBlock().getBpmnFlowName())) { sortedOrchFlows.add(ebb); } } @@ -1405,11 +1358,10 @@ public class WorkflowAction { String resourceId, String requestAction, String vnfType, WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, boolean isVirtualLink, boolean isConfiguration) { - List<Resource> serviceResources = resourceList.stream() - .filter(resource -> resource.getResourceType().equals(workflowType)).collect(Collectors.toList()); - serviceResources.forEach(resource -> flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, - apiVersion, resourceId, requestAction, false, vnfType, workflowResourceIds, requestDetails, - isVirtualLink, resource.getVirtualLinkKey(), null, isConfiguration))); + resourceList.stream().filter(resource -> resource.getResourceType().equals(workflowType)) + .forEach(resource -> flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, + apiVersion, resourceId, requestAction, false, vnfType, workflowResourceIds, requestDetails, + isVirtualLink, resource.getVirtualLinkKey(), null, isConfiguration))); } protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows, @@ -1539,13 +1491,8 @@ public class WorkflowAction { requestAction, resourceName.toString(), aLaCarte, CLOUD_OWNER); } if (northBoundRequest == null) { - if (aLaCarte) { - buildAndThrowException(execution, - "The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API."); - } else { - buildAndThrowException(execution, - "The request: Macro " + resourceName + " " + requestAction + " is not supported by GR_API."); - } + buildAndThrowException(execution, String.format("The request: %s %s %s is not supported by GR_API.", + (aLaCarte ? "AlaCarte" : "Macro"), resourceName, requestAction)); } else { if (northBoundRequest.getIsToplevelflow() != null) { execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow()); @@ -1557,9 +1504,7 @@ public class WorkflowAction { if (!flow.getFlowName().contains("BB") && !flow.getFlowName().contains("Activity")) { List<OrchestrationFlow> macroQueryFlows = catalogDbClient.getOrchestrationFlowByAction(flow.getFlowName()); - for (OrchestrationFlow macroFlow : macroQueryFlows) { - listToExecute.add(macroFlow); - } + listToExecute.addAll(macroQueryFlows); } else { listToExecute.add(flow); } @@ -1582,11 +1527,11 @@ public class WorkflowAction { public void handleRuntimeException(DelegateExecution execution) { StringBuilder wfeExpMsg = new StringBuilder("Runtime error "); - String runtimeErrorMessage = null; + String runtimeErrorMessage; try { String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg"); if (javaExpMsg != null && !javaExpMsg.isEmpty()) { - wfeExpMsg = wfeExpMsg.append(": ").append(javaExpMsg); + wfeExpMsg.append(": ").append(javaExpMsg); } runtimeErrorMessage = wfeExpMsg.toString(); logger.error(runtimeErrorMessage); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/utils/WorkflowResourceIdsUtils.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/utils/WorkflowResourceIdsUtils.java new file mode 100644 index 0000000000..d16eac147e --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/utils/WorkflowResourceIdsUtils.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Nokia Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.workflow.tasks.utils; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowType; +import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; + +public final class WorkflowResourceIdsUtils { + + private WorkflowResourceIdsUtils() { + throw new IllegalStateException("Utility class"); + } + + public static void setResourceIdByWorkflowType(WorkflowResourceIds workflowResourceIds, WorkflowType resourceType, + String resourceId) { + switch (resourceType) { + case SERVICE: + workflowResourceIds.setServiceInstanceId(resourceId); + break; + case VNF: + workflowResourceIds.setVnfId(resourceId); + break; + case PNF: + workflowResourceIds.setPnfId(resourceId); + break; + case VFMODULE: + workflowResourceIds.setVfModuleId(resourceId); + break; + case VOLUMEGROUP: + workflowResourceIds.setVolumeGroupId(resourceId); + break; + case NETWORK: + workflowResourceIds.setNetworkId(resourceId); + break; + case NETWORKCOLLECTION: + workflowResourceIds.setNetworkCollectionId(resourceId); + break; + case CONFIGURATION: + workflowResourceIds.setConfigurationId(resourceId); + break; + case INSTANCE_GROUP: + workflowResourceIds.setInstanceGroupId(resourceId); + break; + } + } + + public static WorkflowResourceIds getWorkflowResourceIdsFromExecution(DelegateExecution execution) { + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId((String) execution.getVariable("serviceInstanceId")); + workflowResourceIds.setNetworkId((String) execution.getVariable("networkId")); + workflowResourceIds.setVfModuleId((String) execution.getVariable("vfModuleId")); + workflowResourceIds.setVnfId((String) execution.getVariable("vnfId")); + workflowResourceIds.setVolumeGroupId((String) execution.getVariable("volumeGroupId")); + workflowResourceIds.setInstanceGroupId((String) execution.getVariable("instanceGroupId")); + return workflowResourceIds; + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java index d78fa69680..3f81e432e1 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapper.java @@ -4,12 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -52,6 +54,7 @@ import org.onap.so.entity.MsoRequest; import org.onap.so.openstack.beans.NetworkRollback; import org.onap.so.openstack.beans.RouteTarget; import org.onap.so.openstack.beans.Subnet; +import org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -65,8 +68,7 @@ public class NetworkAdapterObjectMapper { public CreateNetworkRequest createNetworkRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, - Map<String, String> userInput, String cloudRegionPo, Customer customer) - throws UnsupportedEncodingException { + Map<String, String> userInput, String cloudRegionPo, Customer customer) { CreateNetworkRequest createNetworkRequest = new CreateNetworkRequest(); // set cloudSiteId as determined for cloud region PO instead of cloudRegion.getLcpCloudRegionId() @@ -119,7 +121,7 @@ public class NetworkAdapterObjectMapper { } public DeleteNetworkRequest deleteNetworkRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, - ServiceInstance serviceInstance, L3Network l3Network) throws UnsupportedEncodingException { + ServiceInstance serviceInstance, L3Network l3Network) { DeleteNetworkRequest deleteNetworkRequest = new DeleteNetworkRequest(); deleteNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId()); @@ -150,14 +152,14 @@ public class NetworkAdapterObjectMapper { /** * Access method to build Rollback Network Request - * + * * @return * @throws UnsupportedEncodingException */ public RollbackNetworkRequest createNetworkRollbackRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, Map<String, String> userInput, String cloudRegionPo, - CreateNetworkResponse createNetworkResponse) throws UnsupportedEncodingException { + CreateNetworkResponse createNetworkResponse) { RollbackNetworkRequest rollbackNetworkRequest = new RollbackNetworkRequest(); rollbackNetworkRequest = setCommonRollbackRequestFields(rollbackNetworkRequest, requestContext); @@ -171,7 +173,7 @@ public class NetworkAdapterObjectMapper { public UpdateNetworkRequest createNetworkUpdateRequestMapper(RequestContext requestContext, CloudRegion cloudRegion, OrchestrationContext orchestrationContext, ServiceInstance serviceInstance, L3Network l3Network, - Map<String, String> userInput, Customer customer) throws UnsupportedEncodingException { + Map<String, String> userInput, Customer customer) { UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest(); updateNetworkRequest.setCloudSiteId(cloudRegion.getLcpCloudRegionId()); @@ -198,11 +200,10 @@ public class NetworkAdapterObjectMapper { } private RollbackNetworkRequest setCommonRollbackRequestFields(RollbackNetworkRequest request, - RequestContext requestContext) throws UnsupportedEncodingException { + RequestContext requestContext) { request.setSkipAAI(true); String messageId = requestContext.getMsoRequestId(); request.setMessageId(messageId); - // request.setNotificationUrl(createCallbackUrl("NetworkAResponse", messageId)); return request; } @@ -240,7 +241,7 @@ public class NetworkAdapterObjectMapper { return UUID.randomUUID().toString(); } - protected String createCallbackUrl(String messageType, String correlator) throws UnsupportedEncodingException { + protected String createCallbackUrl(String messageType, String correlator) { String endpoint = this.getEndpoint(); while (endpoint.endsWith("/")) { @@ -256,14 +257,14 @@ public class NetworkAdapterObjectMapper { /** * Use BB L3Network object to build subnets list of type org.onap.so.openstack.beans.Subnet - * + * * @param L3Network * @return List<org.onap.so.openstack.beans.Subnet> */ protected List<Subnet> buildOpenstackSubnetList(L3Network l3Network) { List<org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet> subnets = l3Network.getSubnets(); - List<org.onap.so.openstack.beans.Subnet> subnetList = new ArrayList<org.onap.so.openstack.beans.Subnet>(); + List<org.onap.so.openstack.beans.Subnet> subnetList = new ArrayList<>(); // create mapper from onap Subnet to openstack bean Subnet if (modelMapper.getTypeMap(org.onap.so.bpmn.servicedecomposition.bbobjects.Subnet.class, org.onap.so.openstack.beans.Subnet.class) == null) { @@ -292,7 +293,7 @@ public class NetworkAdapterObjectMapper { .setCidr(subnet.getNetworkStartAddress().concat(FORWARD_SLASH).concat(subnet.getCidrMask())); List<org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute> hostRouteList = subnet.getHostRoutes(); List<org.onap.so.openstack.beans.HostRoute> openstackHostRouteList = new ArrayList<>(); - org.onap.so.openstack.beans.HostRoute openstackHostRoute = null; + org.onap.so.openstack.beans.HostRoute openstackHostRoute; // TODO only 2 fields available on openstack object. Confirm it is sufficient or add as needed for (org.onap.so.bpmn.servicedecomposition.bbobjects.HostRoute hostRoute : hostRouteList) { openstackHostRoute = new org.onap.so.openstack.beans.HostRoute(); @@ -319,10 +320,9 @@ public class NetworkAdapterObjectMapper { private ProviderVlanNetwork buildProviderVlanNetwork(L3Network l3Network) { ProviderVlanNetwork providerVlanNetwork = new ProviderVlanNetwork(); providerVlanNetwork.setPhysicalNetworkName(l3Network.getPhysicalNetworkName()); - List<Integer> vlans = new ArrayList<Integer>(); - List<org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment> segmentationAssignments = - l3Network.getSegmentationAssignments(); - for (org.onap.so.bpmn.servicedecomposition.bbobjects.SegmentationAssignment assignment : segmentationAssignments) { + List<Integer> vlans = new ArrayList<>(); + List<SegmentationAssignment> segmentationAssignments = l3Network.getSegmentationAssignments(); + for (SegmentationAssignment assignment : segmentationAssignments) { vlans.add(Integer.valueOf(assignment.getSegmentationId())); } providerVlanNetwork.setVlans(vlans); @@ -401,7 +401,7 @@ public class NetworkAdapterObjectMapper { private Map<String, String> addSharedAndExternal(Map<String, String> userInput, L3Network l3Network) { if (userInput == null) - userInput = new HashMap<String, String>(); + userInput = new HashMap<>(); if (!userInput.containsKey("shared")) { userInput.put("shared", Optional.ofNullable(l3Network.isIsSharedNetwork()).orElse(false).toString()); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java index 3d3058da0b..362f64d720 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/namingservice/NamingRequestObject.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,7 +26,7 @@ import java.util.HashMap; public class NamingRequestObject { - private HashMap<String, String> namingRequestMap = new HashMap<String, String>(); + private HashMap<String, String> namingRequestMap = new HashMap<>(); public HashMap<String, String> getNamingRequestObjectMap() { return this.namingRequestMap; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java index fc1528526c..9b104f3250 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -37,14 +39,11 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.aai.mapper.AAIObjectMapper; import org.onap.so.db.catalog.beans.OrchestrationStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class AAIServiceInstanceResources { - private static final Logger logger = LoggerFactory.getLogger(AAIServiceInstanceResources.class); @Autowired private InjectionHelper injectionHelper; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java index 5513122560..dba1693e5d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/NamingServiceResources.java @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -33,14 +35,11 @@ import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.namingservice.NamingClient; import org.onap.so.client.namingservice.NamingRequestObject; import org.onap.so.client.namingservice.NamingRequestObjectBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class NamingServiceResources { - private static final Logger logger = LoggerFactory.getLogger(NamingServiceResources.class); private static final String NAMING_TYPE = "instanceGroup"; @Autowired @@ -53,14 +52,14 @@ public class NamingServiceResources { throws BadResponseException, IOException { Element element = namingRequestObjectBuilder.elementMapper(instanceGroup.getId(), policyInstanceName, NAMING_TYPE, nfNamingCode, instanceGroup.getInstanceGroupName()); - List<Element> elements = new ArrayList<Element>(); + List<Element> elements = new ArrayList<>(); elements.add(element); return (namingClient.postNameGenRequest(namingRequestObjectBuilder.nameGenRequestMapper(elements))); } public String deleteInstanceGroupName(InstanceGroup instanceGroup) throws BadResponseException, IOException { Deleteelement deleteElement = namingRequestObjectBuilder.deleteElementMapper(instanceGroup.getId()); - List<Deleteelement> deleteElements = new ArrayList<Deleteelement>(); + List<Deleteelement> deleteElements = new ArrayList<>(); deleteElements.add(deleteElement); return (namingClient .deleteNameGenRequest(namingRequestObjectBuilder.nameGenDeleteRequestMapper(deleteElements))); @@ -70,8 +69,8 @@ public class NamingServiceResources { throws BadResponseException, IOException { HashMap<String, String> nsRequestObject = namingRequestObject.getNamingRequestObjectMap(); Element element = new Element(); - nsRequestObject.forEach((k, v) -> element.put(k, v)); - List<Element> elements = new ArrayList<Element>(); + nsRequestObject.forEach(element::put); + List<Element> elements = new ArrayList<>(); elements.add(element); return (namingClient.postNameGenRequest(namingRequestObjectBuilder.nameGenRequestMapper(elements))); } @@ -81,7 +80,7 @@ public class NamingServiceResources { HashMap<String, String> nsRequestObject = namingRequestObject.getNamingRequestObjectMap(); Deleteelement delElement = new Deleteelement(); nsRequestObject.forEach((k, v) -> delElement.setExternalKey(v)); - List<Deleteelement> delElements = new ArrayList<Deleteelement>(); + List<Deleteelement> delElements = new ArrayList<>(); delElements.add(delElement); return (namingClient.deleteNameGenRequest(namingRequestObjectBuilder.nameGenDeleteRequestMapper(delElements))); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/utils/WorkflowResourceIdsUtilsTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/utils/WorkflowResourceIdsUtilsTest.java new file mode 100644 index 0000000000..0d68cf362b --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/utils/WorkflowResourceIdsUtilsTest.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2020 Nokia Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.workflow.tasks.utils; + +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Before; +import org.junit.Test; +import org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowType; +import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; +import java.util.function.Supplier; +import static org.junit.Assert.assertEquals; + + +public class WorkflowResourceIdsUtilsTest { + + private static final String SERVICE_ID = "serviceId"; + private static final String NETWORK_ID = "networkId"; + private static final String VF_MODULE_ID = "vfModuleId"; + private static final String VNF_ID = "vnfId"; + private static final String VOLUME_GROUP_ID = "volumeGroupId"; + private static final String INSTANCE_GROUP_ID = "instanceGroupId"; + private static final String PNF_ID = "pnfId"; + private static final String NETWORK_COLLECTION_ID = "networkCollectionId"; + private static final String CONFIGURATION_ID = "configurationId"; + + private WorkflowResourceIds workflowResourceIds; + + @Before + public void setUp() { + workflowResourceIds = new WorkflowResourceIds(); + } + + @Test + public void shouldProperlySetFieldsFromExecution() { + DelegateExecutionFake execution = new DelegateExecutionFake(); + execution.setVariable("serviceInstanceId", SERVICE_ID); + execution.setVariable("networkId", NETWORK_ID); + execution.setVariable("vfModuleId", VF_MODULE_ID); + execution.setVariable("vnfId", VNF_ID); + execution.setVariable("volumeGroupId", VOLUME_GROUP_ID); + execution.setVariable("instanceGroupId", INSTANCE_GROUP_ID); + + workflowResourceIds = WorkflowResourceIdsUtils.getWorkflowResourceIdsFromExecution(execution); + + assertEquals(SERVICE_ID, workflowResourceIds.getServiceInstanceId()); + assertEquals(NETWORK_ID, workflowResourceIds.getNetworkId()); + assertEquals(VF_MODULE_ID, workflowResourceIds.getVfModuleId()); + assertEquals(VNF_ID, workflowResourceIds.getVnfId()); + assertEquals(VOLUME_GROUP_ID, workflowResourceIds.getVolumeGroupId()); + assertEquals(INSTANCE_GROUP_ID, workflowResourceIds.getInstanceGroupId()); + } + + @Test + public void shouldProperlySetServiceInstanceId() { + assertFieldSetProperly(WorkflowType.SERVICE, SERVICE_ID, workflowResourceIds::getServiceInstanceId); + } + + @Test + public void shouldProperlySetVnfId() { + assertFieldSetProperly(WorkflowType.VNF, VNF_ID, workflowResourceIds::getVnfId); + + } + + @Test + public void shouldProperlySetPnfId() { + assertFieldSetProperly(WorkflowType.PNF, PNF_ID, workflowResourceIds::getPnfId); + } + + @Test + public void shouldProperlySetVfModuleId() { + assertFieldSetProperly(WorkflowType.VFMODULE, VF_MODULE_ID, workflowResourceIds::getVfModuleId); + } + + @Test + public void shouldProperlySetVolumeGroupId() { + assertFieldSetProperly(WorkflowType.VOLUMEGROUP, VOLUME_GROUP_ID, workflowResourceIds::getVolumeGroupId); + } + + @Test + public void shouldProperlySetNetworkId() { + assertFieldSetProperly(WorkflowType.NETWORK, NETWORK_ID, workflowResourceIds::getNetworkId); + } + + @Test + public void shouldProperlySetNetworkCollectionId() { + assertFieldSetProperly(WorkflowType.NETWORKCOLLECTION, NETWORK_COLLECTION_ID, + workflowResourceIds::getNetworkCollectionId); + + } + + @Test + public void shouldProperlySetConfigurationId() { + assertFieldSetProperly(WorkflowType.CONFIGURATION, CONFIGURATION_ID, workflowResourceIds::getConfigurationId); + } + + @Test + public void shouldProperlySetInstanceGroupId() { + assertFieldSetProperly(WorkflowType.INSTANCE_GROUP, INSTANCE_GROUP_ID, workflowResourceIds::getInstanceGroupId); + } + + private void assertFieldSetProperly(WorkflowType workflowType, String expectedId, + Supplier<String> testedObjectField) { + WorkflowResourceIdsUtils.setResourceIdByWorkflowType(workflowResourceIds, workflowType, expectedId); + assertEquals(expectedId, testedObjectField.get()); + } +} diff --git a/cloudify-client/pom.xml b/cloudify-client/pom.xml index 6f4ea03ca5..6bb9357c38 100644 --- a/cloudify-client/pom.xml +++ b/cloudify-client/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so</groupId> diff --git a/common/pom.xml b/common/pom.xml index 04deacf129..3b33d6ed37 100644 --- a/common/pom.xml +++ b/common/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>common</artifactId> <name>MSO Common classes</name> diff --git a/common/src/main/java/org/onap/so/beans/nsmf/ActDeActNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/ActDeActNssi.java new file mode 100644 index 0000000000..8d45048ee4 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/ActDeActNssi.java @@ -0,0 +1,51 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ActDeActNssi { + + public final static String ACT_URL = "/api/rest/provMns/v1/NSS/%s" + "/activation"; + + public final static String DE_ACT_URL = "/api/rest/provMns/v1/NSS/%s" + "/deactivation"; + + private String nsiId; + + private String nssiId; + + public String getNsiId() { + return nsiId; + } + + public void setNsiId(String nsiId) { + this.nsiId = nsiId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/AllocateAnNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/AllocateAnNssi.java new file mode 100644 index 0000000000..484f5b42b1 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/AllocateAnNssi.java @@ -0,0 +1,109 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AllocateAnNssi { + + public final static String URL = "/api/rest/provMns/v1/an/NSS" + "/SliceProfiles"; + + private String nsstId; + + private String flavorId; + + private String nssiId; + + private String nssiName; + + private AnSliceProfile sliceProfile; + + private String scriptName; + + private Object extension; + + private NsiInfo nsiInfo; + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public String getNssiName() { + return nssiName; + } + + public void setNssiName(String nssiName) { + this.nssiName = nssiName; + } + + public AnSliceProfile getSliceProfile() { + return sliceProfile; + } + + public void setSliceProfile(AnSliceProfile sliceProfile) { + this.sliceProfile = sliceProfile; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public Object getExtension() { + return extension; + } + + public void setExtension(Object extension) { + this.extension = extension; + } + + public NsiInfo getNsiInfo() { + return nsiInfo; + } + + public void setNsiInfo(NsiInfo nsiInfo) { + this.nsiInfo = nsiInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/AllocateCnNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/AllocateCnNssi.java new file mode 100644 index 0000000000..d03673368c --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/AllocateCnNssi.java @@ -0,0 +1,110 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.io.Serializable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AllocateCnNssi implements Serializable { + + public final static String URL = "/api/rest/provMns/v1/NSS/SliceProfiles"; + + private String nsstId; + + private String flavorId; + + private String nssiId; + + private String nssiName; + + private CnSliceProfile sliceProfile; + + private String scriptName; + + private Object extension; + + private NsiInfo nsiInfo; + + public NsiInfo getNsiInfo() { + return nsiInfo; + } + + public void setNsiInfo(NsiInfo nsiInfo) { + this.nsiInfo = nsiInfo; + } + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public CnSliceProfile getSliceProfile() { + return sliceProfile; + } + + public void setSliceProfile(CnSliceProfile sliceProfile) { + this.sliceProfile = sliceProfile; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public String getNssiName() { + return nssiName; + } + + public void setNssiName(String nssiName) { + this.nssiName = nssiName; + } + + public void setExtension(Object extension) { + this.extension = extension; + } + + public Object getExtension() { + return extension; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/AllocateTnNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/AllocateTnNssi.java new file mode 100644 index 0000000000..b66fb133d2 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/AllocateTnNssi.java @@ -0,0 +1,109 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AllocateTnNssi { + + public final static String URL = "/api/rest/provMns/v1/tn/NSS" + "/SliceProfiles"; + + private String nsstId; + + private String flavorId; + + private String nssiId; + + private String nssiName; + + private TnSliceProfile sliceProfile; + + private String scriptName; + + private Object extension; + + private NsiInfo nsiInfo; + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public String getNssiName() { + return nssiName; + } + + public void setNssiName(String nssiName) { + this.nssiName = nssiName; + } + + public TnSliceProfile getSliceProfile() { + return sliceProfile; + } + + public void setSliceProfile(TnSliceProfile sliceProfile) { + this.sliceProfile = sliceProfile; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public Object getExtension() { + return extension; + } + + public void setExtension(Object extension) { + this.extension = extension; + } + + public NsiInfo getNsiInfo() { + return nsiInfo; + } + + public void setNsiInfo(NsiInfo nsiInfo) { + this.nsiInfo = nsiInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/AnSliceProfile.java b/common/src/main/java/org/onap/so/beans/nsmf/AnSliceProfile.java new file mode 100644 index 0000000000..3d60949385 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/AnSliceProfile.java @@ -0,0 +1,61 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class AnSliceProfile { + + @JsonProperty("5QI") + private String qi; + + private List<String> coverageAreaTAList; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int latency; + + public String getQi() { + return qi; + } + + public void setQi(String qi) { + this.qi = qi; + } + + public List<String> getCoverageAreaTAList() { + return coverageAreaTAList; + } + + public void setCoverageAreaTAList(List<String> coverageAreaTAList) { + this.coverageAreaTAList = coverageAreaTAList; + } + + public int getLatency() { + return latency; + } + + public void setLatency(int latency) { + this.latency = latency; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/CnSliceProfile.java b/common/src/main/java/org/onap/so/beans/nsmf/CnSliceProfile.java new file mode 100644 index 0000000000..3bd155d512 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/CnSliceProfile.java @@ -0,0 +1,120 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CnSliceProfile { + + private List<String> snssaiList; + + private String sliceProfileId; + + private List<String> plmnIdList; + + private PerfReq perfReq; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int maxNumberofUEs; + + private List<String> coverageAreaTAList; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int latency; + + private UeMobilityLevel ueMobilityLevel; + + private ResourceSharingLevel resourceSharingLevel; + + public String getSliceProfileId() { + return sliceProfileId; + } + + public void setSliceProfileId(String sliceProfileId) { + this.sliceProfileId = sliceProfileId; + } + + public List<String> getPlmnIdList() { + return plmnIdList; + } + + public void setPlmnIdList(List<String> plmnIdList) { + this.plmnIdList = plmnIdList; + } + + public PerfReq getPerfReq() { + return perfReq; + } + + public void setPerfReq(PerfReq perfReq) { + this.perfReq = perfReq; + } + + public int getMaxNumberofUEs() { + return maxNumberofUEs; + } + + public void setMaxNumberofUEs(int maxNumberofUEs) { + this.maxNumberofUEs = maxNumberofUEs; + } + + public List<String> getCoverageAreaTAList() { + return coverageAreaTAList; + } + + public void setCoverageAreaTAList(List<String> coverageAreaTAList) { + this.coverageAreaTAList = coverageAreaTAList; + } + + public int getLatency() { + return latency; + } + + public void setLatency(int latency) { + this.latency = latency; + } + + public UeMobilityLevel getUeMobilityLevel() { + return ueMobilityLevel; + } + + public void setUeMobilityLevel(UeMobilityLevel ueMobilityLevel) { + this.ueMobilityLevel = ueMobilityLevel; + } + + public ResourceSharingLevel getResourceSharingLevel() { + return resourceSharingLevel; + } + + public void setResourceSharingLevel(ResourceSharingLevel resourceSharingLevel) { + this.resourceSharingLevel = resourceSharingLevel; + } + + public List<String> getSnssaiList() { + return snssaiList; + } + + public void setSnssaiList(List<String> snssaiList) { + this.snssaiList = snssaiList; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/CreateCnNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/CreateCnNssi.java new file mode 100644 index 0000000000..424966948e --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/CreateCnNssi.java @@ -0,0 +1,89 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CreateCnNssi { + + public final static String URL = "/api/rest/provMns/v1/NSS/nssi"; + + private String nsstId; + + private String flavorId; + + private String nssiName; + + private String scriptName; + + private String extension; + + private NsiInfo nsiInfo; + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } + + public String getNssiName() { + return nssiName; + } + + public void setNssiName(String nssiName) { + this.nssiName = nssiName; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public NsiInfo getNsiInfo() { + return nsiInfo; + } + + public void setNsiInfo(NsiInfo nsiInfo) { + this.nsiInfo = nsiInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/DeAllocateNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/DeAllocateNssi.java new file mode 100644 index 0000000000..648fd4985f --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/DeAllocateNssi.java @@ -0,0 +1,91 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DeAllocateNssi { + + public final static String URL = "/api/rest/provMns/v1/NSS" + "/SliceProfiles/%s"; + + private String nsiId; + + private String nssiId; + + private List<String> snssaiList; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int terminateNssiOption; + + private String scriptName; + + private String extension; + + public String getNsiId() { + return nsiId; + } + + public void setNsiId(String nsiId) { + this.nsiId = nsiId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public List<String> getSnssaiList() { + return snssaiList; + } + + public void setSnssaiList(List<String> snssaiList) { + this.snssaiList = snssaiList; + } + + public int getTerminateNssiOption() { + return terminateNssiOption; + } + + public void setTerminateNssiOption(int terminateNssiOption) { + this.terminateNssiOption = terminateNssiOption; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/EsrInfo.java b/common/src/main/java/org/onap/so/beans/nsmf/EsrInfo.java new file mode 100644 index 0000000000..c124bfa944 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/EsrInfo.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EsrInfo { + + private String vendor; + + private NetworkType networkType; + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public NetworkType getNetworkType() { + return networkType; + } + + public void setNetworkType(NetworkType networkType) { + this.networkType = networkType; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/JobStatusRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/JobStatusRequest.java new file mode 100644 index 0000000000..cc8503c250 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/JobStatusRequest.java @@ -0,0 +1,70 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class JobStatusRequest { + + public final static String URL = "/api/rest/provMns/v1/NSS/jobs/%s"; + + private String nsiId; + + private String nssiId; + + private String responseId; + + private EsrInfo esrInfo; + + public String getNsiId() { + return nsiId; + } + + public void setNsiId(String nsiId) { + this.nsiId = nsiId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + + public String getResponseId() { + return responseId; + } + + public void setResponseId(String responseId) { + this.responseId = responseId; + } + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/JobStatusResponse.java b/common/src/main/java/org/onap/so/beans/nsmf/JobStatusResponse.java new file mode 100644 index 0000000000..9259d51591 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/JobStatusResponse.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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class JobStatusResponse { + + private ResponseDescriptor responseDescriptor; + + public ResponseDescriptor getResponseDescriptor() { + return responseDescriptor; + } + + public void setResponseDescriptor(ResponseDescriptor responseDescriptor) { + this.responseDescriptor = responseDescriptor; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NetworkType.java b/common/src/main/java/org/onap/so/beans/nsmf/NetworkType.java new file mode 100644 index 0000000000..2e10fe5746 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NetworkType.java @@ -0,0 +1,58 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public enum NetworkType { + + ACCESS("an"), + + CORE("cn"), + + TRANSPORT("tn"); + + private String networkType; + + NetworkType(String networkType) { + this.networkType = networkType; + } + + @JsonValue + public String getNetworkType() { + return networkType; + } + + @JsonCreator + public NetworkType forValue(String value) { + return valueOf(value); + } + + public static NetworkType fromString(String value) { + for (NetworkType nType : NetworkType.values()) { + if (nType.networkType.equalsIgnoreCase(value)) { + return nType; + } + } + return null; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NewNsst.java b/common/src/main/java/org/onap/so/beans/nsmf/NewNsst.java new file mode 100644 index 0000000000..e13aa5000a --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NewNsst.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NewNsst { + + private String nsstId; + + private String flavorId; + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NsiInfo.java b/common/src/main/java/org/onap/so/beans/nsmf/NsiInfo.java new file mode 100644 index 0000000000..0ff554d10d --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NsiInfo.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NsiInfo { + + private String nsiName; + + private String nsiId; + + public String getNsiName() { + return nsiName; + } + + public void setNsiName(String nsiName) { + this.nsiName = nsiName; + } + + public void setNsiId(String nsiId) { + this.nsiId = nsiId; + } + + public String getNsiId() { + return nsiId; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiActDeActRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiActDeActRequest.java new file mode 100644 index 0000000000..fbba8c77b1 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiActDeActRequest.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiActDeActRequest { + + private EsrInfo esrInfo; + + private ActDeActNssi actDeActNssi; + + public ActDeActNssi getActDeActNssi() { + return actDeActNssi; + } + + public void setActDeActNssi(ActDeActNssi actDeActNssi) { + this.actDeActNssi = actDeActNssi; + } + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiAllocateRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiAllocateRequest.java new file mode 100644 index 0000000000..f72a74a063 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiAllocateRequest.java @@ -0,0 +1,67 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiAllocateRequest { + + private EsrInfo esrInfo; + + private AllocateCnNssi allocateCnNssi; + + private AllocateTnNssi allocateTnNssi; + + private AllocateAnNssi allocateAnNssi; + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } + + public AllocateCnNssi getAllocateCnNssi() { + return allocateCnNssi; + } + + public void setAllocateCnNssi(AllocateCnNssi allocateCnNssi) { + this.allocateCnNssi = allocateCnNssi; + } + + public AllocateTnNssi getAllocateTnNssi() { + return allocateTnNssi; + } + + public void setAllocateTnNssi(AllocateTnNssi allocateTnNssi) { + this.allocateTnNssi = allocateTnNssi; + } + + public AllocateAnNssi getAllocateAnNssi() { + return allocateAnNssi; + } + + public void setAllocateAnNssi(AllocateAnNssi allocateAnNssi) { + this.allocateAnNssi = allocateAnNssi; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiCreateRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiCreateRequest.java new file mode 100644 index 0000000000..ca26e9f0cb --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiCreateRequest.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiCreateRequest { + + private EsrInfo esrInfo; + + private CreateCnNssi createCnNssi; + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } + + public CreateCnNssi getCreateCnNssi() { + return createCnNssi; + } + + public void setCreateCnNssi(CreateCnNssi createCnNssi) { + this.createCnNssi = createCnNssi; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiDeAllocateRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiDeAllocateRequest.java new file mode 100644 index 0000000000..bbfc30c37a --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiDeAllocateRequest.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiDeAllocateRequest { + + private DeAllocateNssi deAllocateNssi; + + private EsrInfo esrInfo; + + public DeAllocateNssi getDeAllocateNssi() { + return deAllocateNssi; + } + + public void setDeAllocateNssi(DeAllocateNssi deAllocateNssi) { + this.deAllocateNssi = deAllocateNssi; + } + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiResponse.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiResponse.java new file mode 100644 index 0000000000..66368be6b8 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiResponse.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiResponse { + + private String nssiId; + + private String jobId; + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public String getJobId() { + return jobId; + } + + public void setJobId(String jobId) { + this.jobId = jobId; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiTerminateRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiTerminateRequest.java new file mode 100644 index 0000000000..df0a463584 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiTerminateRequest.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiTerminateRequest { + + private TerminateNssi terminateNssi; + + private EsrInfo esrInfo; + + public TerminateNssi getTerminateNssi() { + return terminateNssi; + } + + public void setTerminateNssi(TerminateNssi terminateNssi) { + this.terminateNssi = terminateNssi; + } + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiUpdateRequest.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiUpdateRequest.java new file mode 100644 index 0000000000..6642734b7f --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiUpdateRequest.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiUpdateRequest { + + private UpdateCnNssi updateCnNssi; + + private EsrInfo esrInfo; + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } + + public UpdateCnNssi getUpdateCnNssi() { + return updateCnNssi; + } + + public void setUpdateCnNssi(UpdateCnNssi updateCnNssi) { + this.updateCnNssi = updateCnNssi; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssiUpdateRequestById.java b/common/src/main/java/org/onap/so/beans/nsmf/NssiUpdateRequestById.java new file mode 100644 index 0000000000..0554d2fcfd --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssiUpdateRequestById.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssiUpdateRequestById { + + private UpdateCnNssiById updateCnNssiById; + + private EsrInfo esrInfo; + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } + + public UpdateCnNssiById getUpdateCnNssiById() { + return updateCnNssiById; + } + + public void setUpdateCnNssiById(UpdateCnNssiById updateCnNssiById) { + this.updateCnNssiById = updateCnNssiById; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssmiReqInfo.java b/common/src/main/java/org/onap/so/beans/nsmf/NssmiReqInfo.java new file mode 100644 index 0000000000..093825f0ff --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssmiReqInfo.java @@ -0,0 +1,57 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssmiReqInfo { + + private String nsiId; + + private String nssiId; + + private EsrInfo esrInfo; + + public String getNsiId() { + return nsiId; + } + + public void setNsiId(String nsiId) { + this.nsiId = nsiId; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public EsrInfo getEsrInfo() { + return esrInfo; + } + + public void setEsrInfo(EsrInfo esrInfo) { + this.esrInfo = esrInfo; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/NssmiResInfo.java b/common/src/main/java/org/onap/so/beans/nsmf/NssmiResInfo.java new file mode 100644 index 0000000000..e75934a7a9 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/NssmiResInfo.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class NssmiResInfo { + + private String jobId; + + private String status; + + public String getJobId() { + return jobId; + } + + public void setJobId(String jobId) { + this.jobId = jobId; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/PerfReq.java b/common/src/main/java/org/onap/so/beans/nsmf/PerfReq.java new file mode 100644 index 0000000000..4aabc3f26f --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/PerfReq.java @@ -0,0 +1,48 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PerfReq { + + private List<PerfReqEmbbList> perfReqEmbbList; + + private List<PerfReqUrllcList> perfReqUrllcList; + + public List<PerfReqEmbbList> getPerfReqEmbbList() { + return perfReqEmbbList; + } + + public void setPerfReqEmbbList(List<PerfReqEmbbList> perfReqEmbbList) { + this.perfReqEmbbList = perfReqEmbbList; + } + + public List<PerfReqUrllcList> getPerfReqUrllcList() { + return perfReqUrllcList; + } + + public void setPerfReqUrllcList(List<PerfReqUrllcList> perfReqUrllcList) { + this.perfReqUrllcList = perfReqUrllcList; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/PerfReqEmbbList.java b/common/src/main/java/org/onap/so/beans/nsmf/PerfReqEmbbList.java new file mode 100644 index 0000000000..9e9fcaa19e --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/PerfReqEmbbList.java @@ -0,0 +1,82 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PerfReqEmbbList { + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int expDataRateDL; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int expDataRateUL; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int areaTrafficCapDL; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int areaTrafficCapUL; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int activityFactor; + + public int getExpDataRateDL() { + return expDataRateDL; + } + + public void setExpDataRateDL(int expDataRateDL) { + this.expDataRateDL = expDataRateDL; + } + + public int getExpDataRateUL() { + return expDataRateUL; + } + + public void setExpDataRateUL(int expDataRateUL) { + this.expDataRateUL = expDataRateUL; + } + + public int getAreaTrafficCapDL() { + return areaTrafficCapDL; + } + + public void setAreaTrafficCapDL(int areaTrafficCapDL) { + this.areaTrafficCapDL = areaTrafficCapDL; + } + + public int getAreaTrafficCapUL() { + return areaTrafficCapUL; + } + + public void setAreaTrafficCapUL(int areaTrafficCapUL) { + this.areaTrafficCapUL = areaTrafficCapUL; + } + + public int getActivityFactor() { + return activityFactor; + } + + public void setActivityFactor(int activityFactor) { + this.activityFactor = activityFactor; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/PerfReqUrllcList.java b/common/src/main/java/org/onap/so/beans/nsmf/PerfReqUrllcList.java new file mode 100644 index 0000000000..00f0a917aa --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/PerfReqUrllcList.java @@ -0,0 +1,135 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PerfReqUrllcList { + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int e2eLatency; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int jitter; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int survivalTime; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private float csAvailability; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private float reliability; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int expDataRate; + + private String payloadSize; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int trafficDensity; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int connDensity; + + private String serviceAreaDimension; + + public int getE2eLatency() { + return e2eLatency; + } + + public void setE2eLatency(int e2eLatency) { + this.e2eLatency = e2eLatency; + } + + public int getJitter() { + return jitter; + } + + public void setJitter(int jitter) { + this.jitter = jitter; + } + + public int getSurvivalTime() { + return survivalTime; + } + + public void setSurvivalTime(int survivalTime) { + this.survivalTime = survivalTime; + } + + public float getReliability() { + return reliability; + } + + public void setReliability(float reliability) { + this.reliability = reliability; + } + + public int getExpDataRate() { + return expDataRate; + } + + public void setExpDataRate(int expDataRate) { + this.expDataRate = expDataRate; + } + + public String getPayloadSize() { + return payloadSize; + } + + public void setPayloadSize(String payloadSize) { + this.payloadSize = payloadSize; + } + + public int getTrafficDensity() { + return trafficDensity; + } + + public void setTrafficDensity(int trafficDensity) { + this.trafficDensity = trafficDensity; + } + + public int getConnDensity() { + return connDensity; + } + + public void setConnDensity(int connDensity) { + this.connDensity = connDensity; + } + + public String getServiceAreaDimension() { + return serviceAreaDimension; + } + + public void setServiceAreaDimension(String serviceAreaDimension) { + this.serviceAreaDimension = serviceAreaDimension; + } + + public float getCsAvailability() { + return csAvailability; + } + + public void setCsAvailability(float csAvailability) { + this.csAvailability = csAvailability; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/PnfErrorList.java b/common/src/main/java/org/onap/so/beans/nsmf/PnfErrorList.java new file mode 100644 index 0000000000..66bfbdcea9 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/PnfErrorList.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PnfErrorList { + + private String pnfId; + + private String pnfErrorDesc; + + public String getPnfId() { + return pnfId; + } + + public void setPnfId(String pnfId) { + this.pnfId = pnfId; + } + + public String getPnfErrorDesc() { + return pnfErrorDesc; + } + + public void setPnfErrorDesc(String pnfErrorDesc) { + this.pnfErrorDesc = pnfErrorDesc; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/ResourceSharingLevel.java b/common/src/main/java/org/onap/so/beans/nsmf/ResourceSharingLevel.java new file mode 100644 index 0000000000..405429c34d --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/ResourceSharingLevel.java @@ -0,0 +1,56 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public enum ResourceSharingLevel { + + SHARED("shared"), + + NON_SHARED("non-shared"); + + private String resourceSharingLevel; + + ResourceSharingLevel(String resourceSharingLevel) { + this.resourceSharingLevel = resourceSharingLevel; + } + + @JsonValue + public String getResourceSharingLevel() { + return resourceSharingLevel; + } + + @JsonCreator + public ResourceSharingLevel forValue(String value) { + return valueOf(value); + } + + public static ResourceSharingLevel fromString(String value) { + for (ResourceSharingLevel rscLvl : ResourceSharingLevel.values()) { + if (rscLvl.resourceSharingLevel.equalsIgnoreCase(value)) { + return rscLvl; + } + } + return null; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/ResponseDescriptor.java b/common/src/main/java/org/onap/so/beans/nsmf/ResponseDescriptor.java new file mode 100644 index 0000000000..469d212ef9 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/ResponseDescriptor.java @@ -0,0 +1,85 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ResponseDescriptor { + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int progress; + + private String status; + + private String statusDescription; + + private String errorCode; + + private List<VnfErrorList> vnfErrorList; + + private List<PnfErrorList> pnfErrorList; + + private String responseId; + + private List<ResponseHistory> responseHistoryList; + + public int getProgress() { + return progress; + } + + public void setProgress(int progress) { + this.progress = progress; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getStatusDescription() { + return statusDescription; + } + + public void setStatusDescription(String statusDescription) { + this.statusDescription = statusDescription; + } + + public String getResponseId() { + return responseId; + } + + public void setResponseId(String responseId) { + this.responseId = responseId; + } + + public List<ResponseHistory> getResponseHistoryList() { + return responseHistoryList; + } + + public void setResponseHistoryList(List<ResponseHistory> responseHistoryList) { + this.responseHistoryList = responseHistoryList; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/ResponseHistory.java b/common/src/main/java/org/onap/so/beans/nsmf/ResponseHistory.java new file mode 100644 index 0000000000..c71441a80a --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/ResponseHistory.java @@ -0,0 +1,94 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ResponseHistory { + + private int progress; + + private String status; + + private String errorCode; + + private String statusDescription; + + private String responseId; + + private List<VnfErrorList> vnfErrorList; + + private List<PnfErrorList> pnfErrorList; + + public int getProgress() { + return progress; + } + + public void setProgress(int progress) { + this.progress = progress; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getStatusDescription() { + return statusDescription; + } + + public void setStatusDescription(String statusDescription) { + this.statusDescription = statusDescription; + } + + public String getResponseId() { + return responseId; + } + + public void setResponseId(String responseId) { + this.responseId = responseId; + } + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public List<VnfErrorList> getVnfErrorList() { + return vnfErrorList; + } + + public List<PnfErrorList> getPnfErrorList() { + return pnfErrorList; + } + + public void setPnfErrorList(List<PnfErrorList> pnfErrorList) { + this.pnfErrorList = pnfErrorList; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/TerminateNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/TerminateNssi.java new file mode 100644 index 0000000000..28cc565272 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/TerminateNssi.java @@ -0,0 +1,59 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class TerminateNssi { + + public final static String URL = "/api/rest/provMns/v1/NSS/nssi/%s"; + + private String nsiId; + + private String scriptName; + + private String extension; + + public String getNsiId() { + return nsiId; + } + + public void setNsiId(String nsiId) { + this.nsiId = nsiId; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/TnSliceProfile.java b/common/src/main/java/org/onap/so/beans/nsmf/TnSliceProfile.java new file mode 100644 index 0000000000..c3548f15af --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/TnSliceProfile.java @@ -0,0 +1,48 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class TnSliceProfile { + + private String bandwidth; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int latency; + + public String getBandwidth() { + return bandwidth; + } + + public void setBandwidth(String bandwidth) { + this.bandwidth = bandwidth; + } + + public int getLatency() { + return latency; + } + + public void setLatency(int latency) { + this.latency = latency; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/UeMobilityLevel.java b/common/src/main/java/org/onap/so/beans/nsmf/UeMobilityLevel.java new file mode 100644 index 0000000000..ffb7229838 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/UeMobilityLevel.java @@ -0,0 +1,60 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +public enum UeMobilityLevel { + + STATIONARY("stationary"), + + NOMADIC("nomadic"), + + RESTRICTED_MOBILITY("restricted mobility"), + + FULLY_MOBILITY("fully mobility"); + + private String ueMobilityLevel; + + UeMobilityLevel(String ueMobilityLevel) { + this.ueMobilityLevel = ueMobilityLevel; + } + + @JsonValue + public String getUeMobilityLevel() { + return ueMobilityLevel; + } + + @JsonCreator + public UeMobilityLevel forValue(String value) { + return valueOf(value); + } + + public static UeMobilityLevel fromString(String value) { + for (UeMobilityLevel ueLvl : UeMobilityLevel.values()) { + if (ueLvl.ueMobilityLevel.equalsIgnoreCase(value)) { + return ueLvl; + } + } + return null; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/UpdateCnNssi.java b/common/src/main/java/org/onap/so/beans/nsmf/UpdateCnNssi.java new file mode 100644 index 0000000000..9fb8f26440 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/UpdateCnNssi.java @@ -0,0 +1,119 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateCnNssi { + + public final static String URL = "/api/rest/provMns/v1/NSS/SliceProfiles/%s"; + + private String snssai; + + private String nssiId; + + private String nsstId; + + private String flavorId; + + private UpdateSliceProfile sliceProfile; + + private String scriptName; + + private String extension; + + private NsiInfo nsiInfo; + + private NewNsst newNsst; + + public String getSnssai() { + return snssai; + } + + public void setSnssai(String snssai) { + this.snssai = snssai; + } + + public String getNssiId() { + return nssiId; + } + + public void setNssiId(String nssiId) { + this.nssiId = nssiId; + } + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } + + public UpdateSliceProfile getSliceProfile() { + return sliceProfile; + } + + public void setSliceProfile(UpdateSliceProfile sliceProfile) { + this.sliceProfile = sliceProfile; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public NsiInfo getNsiInfo() { + return nsiInfo; + } + + public void setNsiInfo(NsiInfo nsiInfo) { + this.nsiInfo = nsiInfo; + } + + public NewNsst getNewNsst() { + return newNsst; + } + + public void setNewNsst(NewNsst newNsst) { + this.newNsst = newNsst; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/UpdateCnNssiById.java b/common/src/main/java/org/onap/so/beans/nsmf/UpdateCnNssiById.java new file mode 100644 index 0000000000..26e6ca02bb --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/UpdateCnNssiById.java @@ -0,0 +1,89 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateCnNssiById { + + public final static String URL = "/api/rest/provMns/v1/NSS/nssi/%s"; + + private String nsstId; + + private String flavorId; + + private String scriptName; + + private String extension; + + private NsiInfo nsiInfo; + + private NewNsst newNsst; + + public String getNsstId() { + return nsstId; + } + + public void setNsstId(String nsstId) { + this.nsstId = nsstId; + } + + public String getFlavorId() { + return flavorId; + } + + public void setFlavorId(String flavorId) { + this.flavorId = flavorId; + } + + public String getScriptName() { + return scriptName; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public String getExtension() { + return extension; + } + + public void setExtension(String extension) { + this.extension = extension; + } + + public NsiInfo getNsiInfo() { + return nsiInfo; + } + + public void setNsiInfo(NsiInfo nsiInfo) { + this.nsiInfo = nsiInfo; + } + + public NewNsst getNewNsst() { + return newNsst; + } + + public void setNewNsst(NewNsst newNsst) { + this.newNsst = newNsst; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/UpdateSliceProfile.java b/common/src/main/java/org/onap/so/beans/nsmf/UpdateSliceProfile.java new file mode 100644 index 0000000000..74ea7ae424 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/UpdateSliceProfile.java @@ -0,0 +1,101 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateSliceProfile { + + private List<String> plmnIdList; + + private PerfReq perfReq; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int maxNumberofUEs; + + private List<String> coverageAreaTAList; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int latency; + + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private int ueMobilityLevel; + + private String resourceSharingLevel; + + public List<String> getPlmnIdList() { + return plmnIdList; + } + + public void setPlmnIdList(List<String> plmnIdList) { + this.plmnIdList = plmnIdList; + } + + public PerfReq getPerfReq() { + return perfReq; + } + + public void setPerfReq(PerfReq perfReq) { + this.perfReq = perfReq; + } + + public int getMaxNumberofUEs() { + return maxNumberofUEs; + } + + public void setMaxNumberofUEs(int maxNumberofUEs) { + this.maxNumberofUEs = maxNumberofUEs; + } + + public List<String> getCoverageAreaTAList() { + return coverageAreaTAList; + } + + public void setCoverageAreaTAList(List<String> coverageAreaTAList) { + this.coverageAreaTAList = coverageAreaTAList; + } + + public int getLatency() { + return latency; + } + + public void setLatency(int latency) { + this.latency = latency; + } + + public int getUeMobilityLevel() { + return ueMobilityLevel; + } + + public void setUeMobilityLevel(int ueMobilityLevel) { + this.ueMobilityLevel = ueMobilityLevel; + } + + public String getResourceSharingLevel() { + return resourceSharingLevel; + } + + public void setResourceSharingLevel(String resourceSharingLevel) { + this.resourceSharingLevel = resourceSharingLevel; + } +} diff --git a/common/src/main/java/org/onap/so/beans/nsmf/VnfErrorList.java b/common/src/main/java/org/onap/so/beans/nsmf/VnfErrorList.java new file mode 100644 index 0000000000..6388ca6106 --- /dev/null +++ b/common/src/main/java/org/onap/so/beans/nsmf/VnfErrorList.java @@ -0,0 +1,47 @@ +/*- + * ============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.beans.nsmf; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class VnfErrorList { + + private String vnfInstanceId; + + private String vnfErrorDesc; + + public String getVnfInstanceId() { + return vnfInstanceId; + } + + public void setVnfInstanceId(String vnfInstanceId) { + this.vnfInstanceId = vnfInstanceId; + } + + public String getVnfErrorDesc() { + return vnfErrorDesc; + } + + public void setVnfErrorDesc(String vnfErrorDesc) { + this.vnfErrorDesc = vnfErrorDesc; + } +} diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java index c2c8e933b1..f78ac737ed 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java @@ -58,6 +58,7 @@ import org.onap.aai.domain.yang.PortGroup; import org.onap.aai.domain.yang.Project; import org.onap.aai.domain.yang.Pserver; import org.onap.aai.domain.yang.RouteTableReference; +import org.onap.aai.domain.yang.Service; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.ServiceSubscription; import org.onap.aai.domain.yang.SpPartner; @@ -122,6 +123,8 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { public static final AAIObjectType SERVICE_INSTANCE_METADATA = new AAIObjectType( AAIObjectType.SERVICE_INSTANCE + "/metadata", org.onap.aai.domain.yang.v13.Metadata.class); + public static final AAIObjectType SERVICE = new AAIObjectType( + AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/services/service/{service-id}", Service.class); public static final AAIObjectType SERVICE_INSTANCE = new AAIObjectType(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), ServiceInstance.class); public static final AAIObjectType PROJECT = new AAIObjectType(AAINamespaceConstants.BUSINESS, Project.class); @@ -188,6 +191,11 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { public static final AAIObjectType CLOUD_ESR_SYSTEM_INFO_LIST = new AAIObjectType( AAIObjectType.CLOUD_REGION.uriTemplate(), "/esr-system-info-list", "cloud-esr-system-info-list"); public static final AAIObjectType ZONE = new AAIObjectType(AAINamespaceConstants.NETWORK, Zone.class); + public static final AAIObjectType THIRDPARTY_SDNC_LIST = new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM, + "/esr-thirdparty-sdnc-list", "thirdparty-sdnc-list"); + public static final AAIObjectType THIRDPARTY_SDNC_SYSTEM_INFO_LIST = + new AAIObjectType(AAINamespaceConstants.EXTERNAL_SYSTEM + "/esr-thirdparty-sdnc-list", + "/esr-thirdparty-sdnc/{sdnc-id}/esr-system-info-list", "thirdparty-sdnc-system-info-list"); private final String uriTemplate; private final String parentUri; diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java index 5ae1082464..3e85cc5ec6 100644 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java @@ -3,6 +3,7 @@ package org.onap.so.logging.jaxrs.filter; import javax.annotation.Priority; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.PreMatching; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.logger.LogConstants; @@ -11,6 +12,7 @@ import org.springframework.stereotype.Component; import org.onap.logging.filter.base.AuditLogContainerFilter; @Priority(1) +@PreMatching @Component public class SOAuditLogContainerFilter extends AuditLogContainerFilter { @@ -26,9 +28,4 @@ public class SOAuditLogContainerFilter extends AuditLogContainerFilter { } MDC.put(LogConstants.URI_BASE, request.getUriInfo().getBaseUri().toString()); } - - @Override - protected void additionalPostHandling(ContainerResponseContext response) { - // override to add additional post handling - } } diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java index 69046a2eba..4434dce4e3 100644 --- a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java @@ -21,6 +21,7 @@ package org.onap.so.rest.service; import com.google.common.base.Optional; +import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; /** @@ -39,6 +40,16 @@ public interface HttpRestServiceProvider { /** * Execute the HTTP GET to the given URI template + * + * @param url the URL + * @param headers request headers + * @param clazz the type of the return value + * @return Returns the body of this entity. + */ + <T> Optional<T> get(final String url, final HttpHeaders headers, final Class<T> clazz); + + /** + * Execute the HTTP GET to the given URI template * * @param url the URL * @param clazz the type of the return value @@ -46,6 +57,15 @@ public interface HttpRestServiceProvider { */ <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz); + /** + * Execute the HTTP GET to the given URI template + * + * @param url the URL + * @param headers request headers + * @param clazz the type of the return value + * @return Returns the {@link ResponseEntity}. + */ + <T> ResponseEntity<T> getHttpResponse(final String url, final HttpHeaders headers, final Class<T> clazz); /** * Execute the HTTP POST to the given URI template @@ -68,6 +88,18 @@ public interface HttpRestServiceProvider { <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz); /** + * Execute the HTTP POST to the given URI template + * + * @param object the entity (i.e. body) to write to the request + * @param url the URL + * @param clazz the type of the return value + * @param headers request headers + * @return Returns the {@link ResponseEntity}. + */ + <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final HttpHeaders headers, + final Class<T> clazz); + + /** * Execute the HTTP PUT to the given URI template * * @param object the entity (i.e. body) to write to the request diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java index 6211b76561..04dd0bbb7a 100644 --- a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java @@ -20,8 +20,6 @@ package org.onap.so.rest.service; -import com.google.common.base.Optional; -import org.onap.so.configuration.rest.BasicHttpHeadersProvider; import org.onap.so.configuration.rest.HttpHeadersProvider; import org.onap.so.rest.exceptions.HttpResouceNotFoundException; import org.onap.so.rest.exceptions.InvalidRestRequestException; @@ -36,6 +34,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import com.google.common.base.Optional; /** * A Service to perform HTTP requests @@ -46,16 +45,27 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestServiceProviderImpl.class); private final RestTemplate restTemplate; - private final HttpHeadersProvider httpHeadersProvider; + private final HttpHeaders defaultHttpHeaders; public HttpRestServiceProviderImpl(final RestTemplate restTemplate) { this.restTemplate = restTemplate; - this.httpHeadersProvider = new BasicHttpHeadersProvider(); + this.defaultHttpHeaders = new HttpHeaders(); + } + + public HttpRestServiceProviderImpl(final RestTemplate restTemplate, final HttpHeaders defaultHttpHeaders) { + this.restTemplate = restTemplate; + this.defaultHttpHeaders = defaultHttpHeaders; } + /** + * + * @deprecated this constructor is deprecated in favor of using {@link HttpRestServiceProviderImpl(RestTemplate + * restTemplate, HttpHeaders defaultHttpHeaders)} + */ + @Deprecated public HttpRestServiceProviderImpl(final RestTemplate restTemplate, final HttpHeadersProvider httpHeadersProvider) { this.restTemplate = restTemplate; - this.httpHeadersProvider = httpHeadersProvider; + this.defaultHttpHeaders = httpHeadersProvider.getHttpHeaders(); } @Override @@ -64,10 +74,21 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { return createOptional(response, url, HttpMethod.GET); } + @Override + public <T> Optional<T> get(final String url, final HttpHeaders headers, final Class<T> clazz) { + final ResponseEntity<T> response = invokeHttpRequest(new HttpEntity<>(headers), HttpMethod.GET, url, clazz); + return createOptional(response, url, HttpMethod.GET); + } @Override public <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz) { - final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders()); + final HttpEntity<?> request = new HttpEntity<>(getDefaultHttpHeaders()); + return invokeHttpRequest(request, HttpMethod.GET, url, clazz); + } + + @Override + public <T> ResponseEntity<T> getHttpResponse(final String url, final HttpHeaders headers, final Class<T> clazz) { + final HttpEntity<?> request = new HttpEntity<>(headers); return invokeHttpRequest(request, HttpMethod.GET, url, clazz); } @@ -79,7 +100,14 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { @Override public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz) { - final HttpEntity<?> request = new HttpEntity<>(object, getHttpHeaders()); + final HttpEntity<?> request = new HttpEntity<>(object, getDefaultHttpHeaders()); + return invokeHttpRequest(request, HttpMethod.POST, url, clazz); + } + + @Override + public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final HttpHeaders headers, + final Class<T> clazz) { + final HttpEntity<?> request = new HttpEntity<>(object, headers); return invokeHttpRequest(request, HttpMethod.POST, url, clazz); } @@ -91,7 +119,7 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { @Override public <T> ResponseEntity<T> putHttpRequest(final Object object, final String url, final Class<T> clazz) { - final HttpEntity<?> request = new HttpEntity<>(object, getHttpHeaders()); + final HttpEntity<?> request = new HttpEntity<>(object, getDefaultHttpHeaders()); return invokeHttpRequest(request, HttpMethod.PUT, url, clazz); } @@ -140,7 +168,7 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { @Override public <T> ResponseEntity<T> deleteHttpRequest(final String url, final Class<T> clazz) { try { - final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders()); + final HttpEntity<?> request = new HttpEntity<>(getDefaultHttpHeaders()); return restTemplate.exchange(url, HttpMethod.DELETE, request, clazz); } catch (final HttpStatusCodeException httpStatusCodeException) { @@ -162,7 +190,7 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { } } - private HttpHeaders getHttpHeaders() { - return httpHeadersProvider.getHttpHeaders(); + private HttpHeaders getDefaultHttpHeaders() { + return defaultHttpHeaders; } } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java b/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java index 4a284b55ec..777dcc6171 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/CloudConfiguration.java @@ -37,6 +37,8 @@ public class CloudConfiguration implements Serializable { protected String aicNodeClli; @JsonProperty("tenantId") protected String tenantId; + @JsonProperty("tenantName") + protected String tenantName; @JsonProperty("cloudOwner") protected String cloudOwner = Defaults.CLOUD_OWNER.toString(); @JsonProperty("lcpCloudRegionId") @@ -82,6 +84,13 @@ public class CloudConfiguration implements Serializable { this.tenantId = value; } + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } public String getLcpCloudRegionId() { return lcpCloudRegionId; @@ -102,7 +111,8 @@ public class CloudConfiguration implements Serializable { @Override public String toString() { return new ToStringBuilder(this).append("aicNodeClli", getAicNodeClli()).append("tenantId", getTenantId()) - .append("cloudOwner", getCloudOwner()).append("lcpCloudRegionId", getLcpCloudRegionId()).toString(); + .append("tenantName", getTenantName()).append("cloudOwner", getCloudOwner()) + .append("lcpCloudRegionId", getLcpCloudRegionId()).toString(); } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java index 250c5df5ce..026db1e644 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java @@ -43,6 +43,8 @@ public class RequestInfo implements Serializable { protected String orderNumber; @JsonProperty("productFamilyId") protected String productFamilyId; + @JsonProperty("productFamilyName") + protected String productFamilyName; @JsonProperty("orderVersion") protected Integer orderVersion; @JsonSerialize(include = Inclusion.ALWAYS) @@ -180,6 +182,14 @@ public class RequestInfo implements Serializable { public void setProductFamilyId(String productFamilyId) { this.productFamilyId = productFamilyId; + }; + + public String getProductFamilyName() { + return productFamilyName; + } + + public void setProductFamilyName(String productFamilyName) { + this.productFamilyName = productFamilyName; } /** @@ -215,9 +225,9 @@ public class RequestInfo implements Serializable { public String toString() { return "RequestInfo [billingAccountNumber=" + billingAccountNumber + ", callbackUrl=" + callbackUrl + ", correlator=" + correlator + ", orderNumber=" + orderNumber + ", productFamilyId=" + productFamilyId - + ", orderVersion=" + orderVersion + ", source=" + source + ", instanceName=" + instanceName - + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + ", applicationId=" - + applicationId + "]"; + + ", productFamilyName=" + productFamilyName + ", orderVersion=" + orderVersion + ", source=" + source + + ", instanceName=" + instanceName + ", suppressRollback=" + suppressRollback + ", requestorId=" + + requestorId + ", applicationId=" + applicationId + "]"; } diff --git a/cxf-logging/pom.xml b/cxf-logging/pom.xml index f0c969aeb1..c056daf6f8 100644 --- a/cxf-logging/pom.xml +++ b/cxf-logging/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> <name>CXFLogging</name> <description>Common CXF Logging Classes</description> diff --git a/deployment-configs/pom.xml b/deployment-configs/pom.xml index 6935a15955..002cd19f81 100644 --- a/deployment-configs/pom.xml +++ b/deployment-configs/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>deployment-configs</artifactId> <name>deployment-configs</name> diff --git a/deployment-configs/src/main/resources/logger/logback-spring.xml b/deployment-configs/src/main/resources/logger/logback-spring.xml index 831a33a490..3f022f55fb 100644 --- a/deployment-configs/src/main/resources/logger/logback-spring.xml +++ b/deployment-configs/src/main/resources/logger/logback-spring.xml @@ -27,7 +27,7 @@ <property name="currentTimeStamp" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",UTC}"/> <property name="errorPattern" - value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestID}|%thread|%X{ServiceName:-Unknown}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode:-900}|%X{ErrorDesc:-UnknownError}|%msg%n" /> + value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestID}|%thread|%X{ServiceName:-Unknown}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode:-900}|%X{ErrorDesc:-UnknownError}|%msg%nopex%n" /> <property name="debugPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{RequestID}|%logger{50} - %msg%n" /> diff --git a/mso-api-handlers/mso-api-handler-common/pom.xml b/mso-api-handlers/mso-api-handler-common/pom.xml index a3fd37ce2b..865de7998f 100644 --- a/mso-api-handlers/mso-api-handler-common/pom.xml +++ b/mso-api-handlers/mso-api-handler-common/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index 9944984d33..3a7c7ad477 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index 31e026b332..ce371203ab 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -42,7 +42,11 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.Tenant; import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; @@ -97,7 +101,6 @@ import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; - @Component public class MsoRequest { @@ -107,6 +110,9 @@ public class MsoRequest { @Autowired private ResponseBuilder builder; + @Autowired + private AAIDataRetrieval aaiDataRet; + @Value("${mso.enforceDLP:false}") private boolean enforceDLP; @@ -316,6 +322,25 @@ public class MsoRequest { aq.setPnfName(servInsReq.getPnfName()); } + if (servInsReq.getRequestDetails() != null && servInsReq.getRequestDetails().getRequestInfo() != null + && servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId() != null) { + logger.debug("Retrieving productFamilyName to put into requests db"); + + org.onap.aai.domain.yang.Service service = + aaiDataRet.getService(servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId()); + if (service != null) { + logger.debug("Found service by service-id"); + String productFamilyName = service.getServiceDescription(); + if (productFamilyName != null) { + aq.setProductFamilyName(productFamilyName); + } + } + } + + aq.setProductFamilyName(getProductFamilyNameFromAAI(servInsReq)); + + aq.setTenantName(getTenantNameFromAAI(servInsReq)); + if (ModelType.service.name().equalsIgnoreCase(requestScope)) { if (servInsReq.getRequestDetails().getRequestInfo() != null) { if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { @@ -683,4 +708,31 @@ public class MsoRequest { return vnfType; } + protected String getTenantNameFromAAI(ServiceInstancesRequest servInsReq) { + String tenantName = null; + if (servInsReq.getRequestDetails() != null && servInsReq.getRequestDetails().getCloudConfiguration() != null + && servInsReq.getRequestDetails().getCloudConfiguration().getTenantId() != null) { + Tenant tenant = aaiDataRet.getTenant(servInsReq.getRequestDetails().getCloudConfiguration().getCloudOwner(), + servInsReq.getRequestDetails().getCloudConfiguration().getLcpCloudRegionId(), + servInsReq.getRequestDetails().getCloudConfiguration().getTenantId()); + if (tenant != null) { + tenantName = tenant.getTenantName(); + } + } + return tenantName; + } + + protected String getProductFamilyNameFromAAI(ServiceInstancesRequest servInsReq) { + String productFamilyName = null; + if (servInsReq.getRequestDetails() != null && servInsReq.getRequestDetails().getRequestInfo() != null + && servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId() != null) { + org.onap.aai.domain.yang.Service service = + aaiDataRet.getService(servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId()); + if (service != null) { + productFamilyName = service.getServiceDescription(); + } + } + return productFamilyName; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index ae68cc6032..fec93f72e4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -347,6 +347,13 @@ public class OrchestrationRequests { } else { requestDetails = mapper.readValue(requestBody, RequestDetails.class); } + if (requestDetails.getRequestInfo() != null && iar.getProductFamilyName() != null) { + requestDetails.getRequestInfo().setProductFamilyName(iar.getProductFamilyName()); + } + if (requestDetails.getCloudConfiguration() != null && iar.getTenantName() != null) { + requestDetails.getCloudConfiguration().setTenantName(iar.getTenantName()); + } + } catch (IOException e) { logger.error("Exception occurred", e); ErrorLoggerInfo errorLoggerInfo = diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java index 21129d7c2d..90cf50262b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java @@ -206,4 +206,95 @@ public class OrchestrationTasks { } } + @POST + @Path("/{version:[vV][4-7]}/{taskId}/commit") + @Operation(description = "Commit an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response CommitOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) { + OrchestrationTask orchestrationTask; + try { + orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Commit", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + try { + String taskName = orchestrationTask.getName(); + Map<String, String> commitVar = new HashMap<>(); + commitVar.put("taskAction", "commit"); + JSONObject msgJson = createMessageBody(taskId, taskName, commitVar); + camundaRequestHandler.sendCamundaMessages(msgJson); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.ERROR_FROM_BPEL, null, version); + return response; + } + + } + + @POST + @Path("/{version:[vV][4-7]}/{taskId}/abort") + @Operation(description = "Commit an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response AbortOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) { + OrchestrationTask orchestrationTask; + try { + orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Commit", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + try { + String taskName = orchestrationTask.getName(); + Map<String, String> commitVar = new HashMap<>(); + commitVar.put("taskAction", "abort"); + JSONObject msgJson = createMessageBody(taskId, taskName, commitVar); + camundaRequestHandler.sendCamundaMessages(msgJson); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.ERROR_FROM_BPEL, null, version); + return response; + } + + } + + private JSONObject createMessageBody(String taskId, String taskName, Map<String, ?> variables) { + JSONObject msgJson = new JSONObject(); + msgJson.put("messageName", taskName); + msgJson.put("businessKey", taskId); + JSONObject processVariables = new JSONObject(); + for (Map.Entry<String, ?> entry : variables.entrySet()) { + JSONObject valueInfo = new JSONObject(); + String key = entry.getKey(); + Object value = entry.getValue(); + valueInfo.put("value", value.toString()); + valueInfo.put("type", value.getClass().getSimpleName()); + processVariables.put(key, valueInfo); + } + msgJson.put("processVariables", processVariables); + return msgJson; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java index 344e5438c9..fee7a3a8f4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java @@ -3,7 +3,9 @@ package org.onap.so.apihandlerinfra.infra.rest; import java.util.Optional; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.Service; import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.Tenant; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; @@ -34,7 +36,6 @@ public class AAIDataRetrieval { }); } - public VfModule getAAIVfModule(String vnfId, String vfModuleId) { return this.getAaiResourcesClient() .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) @@ -75,6 +76,24 @@ public class AAIDataRetrieval { }); } + public Service getService(String serviceId) { + return this.getAaiResourcesClient() + .get(Service.class, AAIUriFactory.createResourceUri(AAIObjectType.SERVICE, serviceId)).orElseGet(() -> { + logger.debug("No Service found in A&AI ServiceId: {}", serviceId); + return null; + }); + } + + public Tenant getTenant(String cloudOwner, String cloudRegion, String tenantId) { + return this.getAaiResourcesClient() + .get(Tenant.class, + AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegion, tenantId)) + .orElseGet(() -> { + logger.debug("No Tenant found in A&AI TenantId: {}", tenantId); + return null; + }); + } + protected AAIResourcesClient getAaiResourcesClient() { if (aaiResourcesClient == null) { aaiResourcesClient = new AAIResourcesClient(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java index f1d5a5487f..d1e5dc717e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java @@ -22,6 +22,7 @@ package org.onap.so.apihandlerinfra; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; @@ -34,12 +35,19 @@ import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.HttpStatus; +import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.domain.yang.Service; +import org.onap.aai.domain.yang.Tenant; import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.test.context.junit4.rules.SpringClassRule; @@ -75,6 +83,17 @@ public class MsoRequestTest extends BaseTest { @Rule public ExpectedException thrown = ExpectedException.none(); + @Mock + private AAIDataRetrieval aaiDataRet; + + @InjectMocks + private MsoRequest msoRequestMock; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + public String inputStream(String JsonInput) throws IOException { JsonInput = "src/test/resources/MsoRequestTest" + JsonInput; String input = new String(Files.readAllBytes(Paths.get(JsonInput))); @@ -1056,5 +1075,37 @@ public class MsoRequestTest extends BaseTest { assertNotNull(result); } + @Test + public void getTenantNameFromAAITest() throws Exception { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), + ServiceInstancesRequest.class); + String tenantId = "88a6ca3ee0394ade9403f075db23167e"; + String tenantNameFromAAI = "testTenantName"; + String cloudRegion = "mdt1"; + String cloudOwner = "cloudOwner"; + this.sir.getRequestDetails().getCloudConfiguration().setCloudOwner(cloudOwner); + Tenant tenant = new Tenant(); + tenant.setTenantId(tenantId); + tenant.setTenantName(tenantNameFromAAI); + doReturn(tenant).when(aaiDataRet).getTenant(cloudOwner, cloudRegion, tenantId); + String tenantName = msoRequestMock.getTenantNameFromAAI(this.sir); + assertEquals(tenantNameFromAAI, tenantName); + } + + + @Test + public void getProductFamilyNameFromAAITest() throws Exception { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), + ServiceInstancesRequest.class); + String serviceId = "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"; + String serviceDescription = "testServiceDescription"; + Service service = new Service(); + service.setServiceId(serviceId); + service.setServiceDescription(serviceDescription); + doReturn(service).when(aaiDataRet).getService(serviceId); + String productFamilyName = msoRequestMock.getProductFamilyNameFromAAI(this.sir); + assertEquals(serviceDescription, productFamilyName); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index f566628ee3..1332ffd913 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -441,6 +441,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); @@ -483,6 +487,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); @@ -524,6 +532,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); @@ -1939,6 +1951,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); @@ -2114,6 +2130,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/aai/ServiceFromAAI.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/aai/ServiceFromAAI.json new file mode 100644 index 0000000000..f0d511789f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/aai/ServiceFromAAI.json @@ -0,0 +1,4 @@ +{ + "service-id": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "service-description": "testServiceDescription" +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index 1a1e9bec79..85a17dd369 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -1297,6 +1297,8 @@ CREATE TABLE `infra_active_requests` ( `ORIGINAL_REQUEST_ID` varchar(45) DEFAULT NULL, `EXT_SYSTEM_ERROR_SOURCE` varchar(80) DEFAULT NULL, `ROLLBACK_EXT_SYSTEM_ERROR_SOURCE` varchar(80) DEFAULT NULL, + `TENANT_NAME` varchar(200) DEFAULT NULL, + `PRODUCT_FAMILY_NAME` varchar(200) DEFAULT NULL, PRIMARY KEY (`REQUEST_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; diff --git a/mso-api-handlers/mso-requests-db-repositories/pom.xml b/mso-api-handlers/mso-requests-db-repositories/pom.xml index 4dbf22cd87..efc81384d4 100644 --- a/mso-api-handlers/mso-requests-db-repositories/pom.xml +++ b/mso-api-handlers/mso-requests-db-repositories/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-requests-db-repositories</artifactId> diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql index 1efd125c2b..c6d22f5402 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql @@ -100,7 +100,10 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( REQUEST_URL VARCHAR SELECTIVITY 1, ORIGINAL_REQUEST_ID VARCHAR SELECTIVITY 1, EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1, - ROLLBACK_EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1 + ROLLBACK_EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1, + TENANT_NAME VARCHAR SELECTIVITY 1, + PRODUCT_FAMILY_NAME VARCHAR SELECTIVITY 1 + ); INSERT INTO PUBLIC.INFRA_ACTIVE_REQUESTS(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES @@ -169,7 +172,9 @@ CREATE CACHED TABLE PUBLIC.ARCHIVED_INFRA_REQUESTS( OPERATIONAL_ENV_NAME VARCHAR SELECTIVITY 1, INSTANCE_GROUP_ID VARCHAR SELECTIVITY 1, INSTANCE_GROUP_NAME VARCHAR SELECTIVITY 1, - REQUEST_URL VARCHAR SELECTIVITY 1 + REQUEST_URL VARCHAR SELECTIVITY 1, + TENANT_NAME VARCHAR SELECTIVITY 1, + PRODUCT_FAMILY_NAME VARCHAR SELECTIVITY 1 ); CREATE TABLE IF NOT EXISTS cloud_api_requests( diff --git a/mso-api-handlers/mso-requests-db/pom.xml b/mso-api-handlers/mso-requests-db/pom.xml index 031f86282a..37bb4175a5 100644 --- a/mso-api-handlers/mso-requests-db/pom.xml +++ b/mso-api-handlers/mso-requests-db/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-requests-db</artifactId> diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 9b246460b8..750fa13c77 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -89,6 +89,7 @@ public class InfraActiveRequests extends InfraRequests { .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()) .append("originalRequestId", getOriginalRequestId()) .append("extSystemErrorSource", getExtSystemErrorSource()) - .append("rollbackExtSystemErrorSource", getRollbackExtSystemErrorSource()).toString(); + .append("rollbackExtSystemErrorSource", getRollbackExtSystemErrorSource()) + .append("tenantName", getTenantName()).append("productFamilyName", getProductFamilyName()).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java index 6d6b5a825e..66768ea349 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java @@ -149,6 +149,10 @@ public abstract class InfraRequests implements java.io.Serializable { private String extSystemErrorSource; @Column(name = "ROLLBACK_EXT_SYSTEM_ERROR_SOURCE", length = 80) private String rollbackExtSystemErrorSource; + @Column(name = "TENANT_NAME", length = 80) + private String tenantName; + @Column(name = "PRODUCT_FAMILY_NAME", length = 80) + private String productFamilyName; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID", updatable = false) @@ -550,6 +554,22 @@ public abstract class InfraRequests implements java.io.Serializable { this.rollbackExtSystemErrorSource = rollbackExtSystemErrorSource; } + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public String getProductFamilyName() { + return productFamilyName; + } + + public void setProductFamilyName(String productFamilyName) { + this.productFamilyName = productFamilyName; + } + @PrePersist protected void onCreate() { if (requestScope == null) @@ -609,6 +629,7 @@ public abstract class InfraRequests implements java.io.Serializable { .append("operationalEnvName", getOperationalEnvName()).append("instanceGroupId", getInstanceGroupId()) .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()) .append("originalRequestId", originalRequestId).append("extSystemErrorSource", extSystemErrorSource) - .append("rollbackExtSystemErrorSource", rollbackExtSystemErrorSource).toString(); + .append("rollbackExtSystemErrorSource", rollbackExtSystemErrorSource).append("tenantName", tenantName) + .append("productFamilyName", productFamilyName).toString(); } } diff --git a/mso-api-handlers/pom.xml b/mso-api-handlers/pom.xml index b4d5c7070a..5c84ab1d77 100644 --- a/mso-api-handlers/pom.xml +++ b/mso-api-handlers/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>mso-api-handlers</artifactId> diff --git a/mso-catalog-db/pom.xml b/mso-catalog-db/pom.xml index 6a4a6774e6..7444866315 100644 --- a/mso-catalog-db/pom.xml +++ b/mso-catalog-db/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-catalog-db</artifactId> diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceArtifact.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceArtifact.java new file mode 100644 index 0000000000..a8884a81bb --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceArtifact.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019, CMCC Technologies Co., Ltd. + * ================================================================================ + * 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.db.catalog.beans; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.openpojo.business.annotation.BusinessKey; +import org.apache.commons.lang3.builder.ToStringBuilder; +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.Objects; + +@Entity +@Table(name = "service_artifact") +public class ServiceArtifact implements Serializable { + + private static final long serialVersionUID = 768026109321305392L; + + @BusinessKey + @Id + @Column(name = "ARTIFACT_UUID") + private String artifactUUID; + + @Column(name = "TYPE") + private String type; + + @Column(name = "NAME") + private String name; + + @Column(name = "VERSION") + private String version; + + @Column(name = "DESCRIPTION") + private String description; + + @Column(name = "CONTENT", columnDefinition = "LONGTEXT") + private String content; + + @Column(name = "CHECKSUM") + private String checksum; + + @Column(name = "CREATION_TIMESTAMP", updatable = false) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") + @Temporal(TemporalType.TIMESTAMP) + private Date creationTimestamp; + + @ManyToOne(cascade = CascadeType.ALL) + @JoinColumn(name = "SERVICE_MODEL_UUID") + private Service service; + + @PrePersist + protected void onCreate() { + this.creationTimestamp = new Date(); + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getChecksum() { + return checksum; + } + + public void setChecksum(String checksum) { + this.checksum = checksum; + } + + public Date getCreationTimestamp() { + return creationTimestamp; + } + + public void setCreationTimestamp(Date creationTimestamp) { + this.creationTimestamp = creationTimestamp; + } + + public Service getService() { + return service; + } + + public void setService(Service service) { + this.service = service; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("artifactUUID", artifactUUID).append("type", type).append("name", name) + .append("version", version).append("description", description).append("content", content) + .append("checksum", checksum).append("creationTimestamp", creationTimestamp).toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + ServiceArtifact that = (ServiceArtifact) o; + return artifactUUID.equals(that.artifactUUID); + } + + @Override + public int hashCode() { + return Objects.hash(artifactUUID); + } +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceInfo.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceInfo.java new file mode 100644 index 0000000000..f9c95767f6 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/ServiceInfo.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (c) 2019, CMCC Technologies Co., Ltd. + * ================================================================================ + * 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.db.catalog.beans; + +import com.openpojo.business.annotation.BusinessKey; +import org.apache.commons.lang3.builder.ToStringBuilder; +import uk.co.blackpepper.bowman.annotation.LinkedResource; +import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@Table(name = "service_info") +public class ServiceInfo implements Serializable { + + private static final long serialVersionUID = 768026109321305392L; + + @Id + @BusinessKey + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "ID") + private Integer id; + + @Column(name = "SERVICE_INPUT") + private String serviceInput; + + @Column(name = "SERVICE_PROPERTIES") + private String serviceProperties; + + @OneToOne(cascade = CascadeType.ALL) + @JoinTable(name = "service_to_service_info", joinColumns = @JoinColumn(name = "SERVICE_INFO_ID"), + inverseJoinColumns = @JoinColumn(name = "SERVICE_MODEL_UUID")) + private Service service; + + public Integer getId() { + return id; + } + + public void setId(Integer serviceInfoId) { + this.id = serviceInfoId; + } + + public String getServiceInput() { + return serviceInput; + } + + public void setServiceInput(String serviceInput) { + this.serviceInput = serviceInput; + } + + public String getServiceProperties() { + return serviceProperties; + } + + public void setServiceProperties(String serviceProperties) { + this.serviceProperties = serviceProperties; + } + + @LinkedResource + public Service getService() { + return service; + } + + public void setService(Service service) { + this.service = service; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("id", id).append("serviceProperties", serviceProperties) + .append("serviceInput", serviceInput).toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + ServiceInfo that = (ServiceInfo) o; + return id.equals(that.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } +} diff --git a/packages/docker/pom.xml b/packages/docker/pom.xml index c78979eccb..8d95d063da 100644 --- a/packages/docker/pom.xml +++ b/packages/docker/pom.xml @@ -6,7 +6,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>packages</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <packaging>pom</packaging> @@ -257,6 +257,31 @@ </build> </image> <image> + <name>${docker.image.prefix}/nssmf-adapter</name> + <build> + <cleanup>try</cleanup> + <dockerFileDir>docker-files</dockerFileDir> + <dockerFile>Dockerfile.so-app</dockerFile> + <tags> + <tag>${project.version}</tag> + <tag>${project.version}-${maven.build.timestamp}</tag> + <tag>${project.docker.latesttag.version}</tag> + </tags> + <assembly> + <inline> + <dependencySets> + <dependencySet> + <includes> + <include>org.onap.so.adapters:mso-nssmf-adapter</include> + </includes> + <outputFileNameMapping>app.jar</outputFileNameMapping> + </dependencySet> + </dependencySets> + </inline> + </assembly> + </build> + </image> + <image> <name>${docker.image.prefix}/so-appc-orchestrator</name> <build> <cleanup>try</cleanup> @@ -437,7 +462,7 @@ <goal>push</goal> </goals> <configuration> - <image>${docker.image.prefix}/catalog-db-adapter,${docker.image.prefix}/request-db-adapter,${docker.image.prefix}/sdnc-adapter,${docker.image.prefix}/openstack-adapter,${docker.image.prefix}/vfc-adapter,${docker.image.prefix}/sdc-controller,${docker.image.prefix}/bpmn-infra,${docker.image.prefix}/api-handler-infra,${docker.image.prefix}/so-monitoring,${docker.image.prefix}/so-simulator</image> + <image>${docker.image.prefix}/catalog-db-adapter,${docker.image.prefix}/request-db-adapter,${docker.image.prefix}/sdnc-adapter,${docker.image.prefix}/openstack-adapter,${docker.image.prefix}/vfc-adapter,${docker.image.prefix}/sdc-controller,${docker.image.prefix}/bpmn-infra,${docker.image.prefix}/api-handler-infra,${docker.image.prefix}/so-monitoring,${docker.image.prefix}/so-simulator,${docker.image.prefix}/mso-nssmf-adapter</image> </configuration> </execution> </executions> @@ -492,6 +517,11 @@ </dependency> <dependency> <groupId>org.onap.so.adapters</groupId> + <artifactId>mso-nssmf-adapter</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.so.adapters</groupId> <artifactId>so-appc-orchestrator</artifactId> <version>${project.version}</version> </dependency> diff --git a/packages/pom.xml b/packages/pom.xml index 029fa3d446..af302405cc 100644 --- a/packages/pom.xml +++ b/packages/pom.xml @@ -4,7 +4,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>packages</artifactId> @@ -11,7 +11,7 @@ <groupId>org.onap.so</groupId> <artifactId>so</artifactId> <packaging>pom</packaging> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> <name>so</name> <description>This Maven project is responsible to build and package all child projects - contributions in the MSO project. This build can be configured to run Functional tests and to start/stop a jboss server + Mysql DB. @@ -49,7 +49,7 @@ <sonar.cpd.exclusions>**/*</sonar.cpd.exclusions> <jacoco.version>0.8.5</jacoco.version> <org.apache.maven.user-settings /> - <openstack.version>1.5.1</openstack.version> + <openstack.version>1.5.2-SNAPSHOT</openstack.version> <maven.build.timestamp.format>yyyyMMdd'T'HHmm</maven.build.timestamp.format> <originalClassifier>original</originalClassifier> <docker.skip>true</docker.skip> @@ -670,17 +670,17 @@ <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-slf4j</artifactId> - <version>1.6.3-SNAPSHOT</version> + <version>1.6.4</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-base</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>1.6.4</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-spring</artifactId> - <version>1.6.3-SNAPSHOT</version> + <version>1.6.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> diff --git a/so-monitoring/pom.xml b/so-monitoring/pom.xml index 243073554e..206a0f2851 100644 --- a/so-monitoring/pom.xml +++ b/so-monitoring/pom.xml @@ -24,7 +24,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <groupId>org.onap.so.monitoring</groupId> diff --git a/so-monitoring/so-monitoring-handler/pom.xml b/so-monitoring/so-monitoring-handler/pom.xml index 59546861c5..176328a434 100644 --- a/so-monitoring/so-monitoring-handler/pom.xml +++ b/so-monitoring/so-monitoring-handler/pom.xml @@ -24,7 +24,7 @@ <parent> <groupId>org.onap.so.monitoring</groupId> <artifactId>so-monitoring</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>so-monitoring-handler</artifactId> <name>${project.artifactId}</name> diff --git a/so-monitoring/so-monitoring-service/pom.xml b/so-monitoring/so-monitoring-service/pom.xml index 762e3a5ee6..110c3fe863 100644 --- a/so-monitoring/so-monitoring-service/pom.xml +++ b/so-monitoring/so-monitoring-service/pom.xml @@ -24,7 +24,7 @@ <parent> <groupId>org.onap.so.monitoring</groupId> <artifactId>so-monitoring</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>so-monitoring-service</artifactId> <name>${project.artifactId}</name> diff --git a/so-monitoring/so-monitoring-ui/pom.xml b/so-monitoring/so-monitoring-ui/pom.xml index c362a83a9b..6488c7d7df 100644 --- a/so-monitoring/so-monitoring-ui/pom.xml +++ b/so-monitoring/so-monitoring-ui/pom.xml @@ -24,7 +24,7 @@ <parent> <groupId>org.onap.so.monitoring</groupId> <artifactId>so-monitoring</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>so-monitoring-ui</artifactId> diff --git a/so-simulator/pom.xml b/so-simulator/pom.xml index 6e0d125ddb..35964d6de6 100644 --- a/so-simulator/pom.xml +++ b/so-simulator/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> <modelVersion>4.0.0</modelVersion> <artifactId>so-simulator</artifactId> @@ -17,8 +17,19 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <citrus.simulator.version>1.1.0</citrus.simulator.version> + <spring.boot.version>2.0.9.RELEASE</spring.boot.version> </properties> - + <dependencyManagement> + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-dependencies</artifactId> + <version>${spring.boot.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> |