diff options
317 files changed, 12457 insertions, 2932 deletions
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/SecurityFilters.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/SecurityFilters.java new file mode 100644 index 0000000000..040723501b --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.catalogdb; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/SoCadiFilter.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/SoCadiFilter.java new file mode 100644 index 0000000000..e7e360d444 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.adapters.catalogdb; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java index 1d58975e6b..8cadb00f8f 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebSecurityConfigImpl.java @@ -24,27 +24,57 @@ package org.onap.so.adapters.catalogdb; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() + .httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/application-aaf.yaml b/adapters/mso-catalog-db-adapter/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/application-aaf.yaml diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/application-basic.yaml b/adapters/mso-catalog-db-adapter/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/application-basic.yaml diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql index 13d736e747..9527986f52 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql @@ -25,6 +25,8 @@ INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, I ('VolumeGroup-Delete', 'deleteInstance', 'VolumeGroup', true,true, '7','7', 'DEFAULT', '*'), ('VFModule-Create', 'createInstance', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), ('VFModule-Delete', 'deleteInstance', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), +('VFModule-Replace', 'replaceInstance', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), +('VFModule-Replace-Retain-Assignments', 'replaceInstanceRetainAssignments', 'VfModule', true,true, '7','7', 'DEFAULT', '*'), ('NetworkCollection-Macro-Create', 'createInstance', 'NetworkCollection', false,true, '7','7', 'DEFAULT', '*'), ('NetworkCollection-Macro-Delete', 'deleteInstance', 'NetworkCollection', false,true, '7','7', 'DEFAULT', '*'), ('VFModule-ScaleOut', 'scaleOut', 'VfModule', true, true, '7','7', 'DEFAULT', '*'); @@ -147,7 +149,35 @@ INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FL ('VFModule-ScaleOut', '3', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), ('VFModule-ScaleOut', '4', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), ('VFModule-ScaleOut', '5', 'ConfigurationScaleOutBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), -('VFModule-ScaleOut', '6', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')); +('VFModule-ScaleOut', '6', 'GenericVnfHealthCheckBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-ScaleOut' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '3', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '4', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '5', 'UnassignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '6', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '7', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '8', 'AssignVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '9', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '10', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '11', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '12', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '13', 'ChangeModelVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace', '14', 'ChangeModelServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '1', 'DeactivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '2', 'DeleteVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '3', 'DeactivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '4', 'DeleteVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '5', 'UnassignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '6', 'AssignVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '7', 'ChangeModelVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '8', 'CreateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '9', 'ActivateVolumeGroupBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '10', 'CreateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '11', 'ActivateVfModuleBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '12', 'ChangeModelVnfBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')), +('VFModule-Replace-Retain-Assignments', '13', 'ChangeModelServiceInstanceBB', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VFModule-Replace-Retain-Assignments' and CLOUD_OWNER = 'DEFAULT')); + INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY) VALUES @@ -815,3 +845,7 @@ VALUES UPDATE rainy_day_handler_macro SET reg_ex_error_message = '*' WHERE reg_ex_error_message IS null; UPDATE rainy_day_handler_macro SET SERVICE_ROLE = '*' WHERE SERVICE_ROLE IS null; + +INSERT INTO vnf_components_recipe (VNF_TYPE, VNF_COMPONENT_TYPE, ACTION, VERSION, ORCHESTRATION_URI, RECIPE_TIMEOUT) +VALUES +(NULL, 'vfModule', 'replaceInstanceRetainAssignments', '1', '/mso/async/services/WorkflowActionBB', 180); diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql index 137f73cf65..42df1adf13 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__WorkflowDesignerData.sql @@ -202,4 +202,6 @@ INSERT INTO `workflow` (`ARTIFACT_UUID`,`ARTIFACT_NAME`,`NAME`,`OPERATION_NAME`, VALUES ('9d45cd30-1a89-4993-87c1-6dd09c1696cf','VFModule-ScaleOut','VNF Scale Out','ScaleOut',1.0,'native static workflow to support ScaleOut','vfModule','native'), ('da6478e4-ea33-3346-ac12-ab121284a333','VnfInPlaceUpdate.bpmn','VnfInPlaceUpdate','inPlaceSoftwareUpdate',1.0,'native static workflow to support inPlaceSoftwareUpdate','vnf','native'), -('fdb3ac48-70f9-4584-bd92-253bdbdec1e1','VnfConfigUpdate.bpmn','VnfConfigUpdate','applyConfigModify',1.0,'native static workflow to support applyConfigModify','vnf','native'); +('fdb3ac48-70f9-4584-bd92-253bdbdec1e1','VnfConfigUpdate.bpmn','VnfConfigUpdate','applyConfigModify',1.0,'native static workflow to support applyConfigModify','vnf','native'), +('b2fd5627-55e4-4f4f-8064-9e6f443e9152','DummyPnfWorkflow','Dummy Pnf Workflow','DummyPnfWorkflow',1.0,'Dummy Pnf Workflow to test custom Pnf workflow','pnf','native'); + diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql index e44a6b97ba..8641e51862 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7.1__WorkFlowDesignerTables.sql @@ -40,6 +40,27 @@ CREATE TABLE IF NOT EXISTS `catalogdb`.`vnf_resource_to_workflow` ( ENGINE = InnoDB DEFAULT CHARACTER SET = latin1; +CREATE TABLE IF NOT EXISTS `catalogdb`.`pnf_resource_to_workflow` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `PNF_RESOURCE_MODEL_UUID` VARCHAR(200) NOT NULL, + `WORKFLOW_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_pnf_resource_to_workflow` (`PNF_RESOURCE_MODEL_UUID` ASC, `WORKFLOW_ID` ASC), + INDEX `fk_pnf_resource_to_workflow__workflow1_idx` (`WORKFLOW_ID` ASC), + INDEX `fk_pnf_resource_to_workflow__pnf_res_mod_uuid_idx` (`PNF_RESOURCE_MODEL_UUID` ASC), + CONSTRAINT `fk_pnf_resource_to_workflow__pnf_resource1` + FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) + REFERENCES `catalogdb`.`pnf_resource` (`MODEL_UUID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_pnf_resource_to_workflow__workflow1` + FOREIGN KEY (`WORKFLOW_ID`) + REFERENCES `catalogdb`.`workflow` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(200) NOT NULL, diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.1__AddControllerActorAndBlueprint.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.1__AddControllerActorAndBlueprint.sql new file mode 100644 index 0000000000..5560dcc0de --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.1__AddControllerActorAndBlueprint.sql @@ -0,0 +1,23 @@ +use catalogdb; + +ALTER TABLE service +ADD CONTROLLER_ACTOR varchar(200) null; + +ALTER TABLE service +ADD CDS_BLUEPRINT_NAME varchar(200) null; + +ALTER TABLE service +ADD CDS_BLUEPRINT_VERSION varchar(20) null; + +ALTER TABLE service +ADD SKIP_POST_INSTANTIATION_CONFIGURATION boolean default true; + +ALTER TABLE vnf_resource_customization +ADD CONTROLLER_ACTOR varchar(200) null; + +ALTER TABLE pnf_resource_customization +ADD CONTROLLER_ACTOR varchar(200) null; + +ALTER TABLE vf_module_customization +ADD SKIP_POST_INSTANTIATION_CONFIGURATION boolean default true; + diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.2__AddScopeAndActionColumnsInOrchestrationFlowReference.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.2__AddScopeAndActionColumnsInOrchestrationFlowReference.sql new file mode 100644 index 0000000000..19bfb0f1e1 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.2__AddScopeAndActionColumnsInOrchestrationFlowReference.sql @@ -0,0 +1,5 @@ +use catalogdb; + +ALTER TABLE orchestration_flow_reference +ADD SCOPE VARCHAR (200) DEFAULT NULL, +ADD ACTION VARCHAR (200) DEFAULT NULL;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java index 347bce5b17..69a23a0eba 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java @@ -21,21 +21,11 @@ package org.onap.so.adapters.catalogdb.catalogrest; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.INVOCATION_ID; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.LOG_TIMESTAMP; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.PARTNER_NAME; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_CODE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; import java.io.IOException; -import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.JSONException; import org.junit.Test; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest; import org.onap.so.db.catalog.beans.ServiceRecipe; import org.skyscreamer.jsonassert.JSONAssert; @@ -46,7 +36,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; -import ch.qos.logback.classic.spi.ILoggingEvent; public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { @@ -109,26 +98,6 @@ public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { restTemplate.exchange(createURLWithPort("/manage/health"), HttpMethod.GET, entity, String.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.spring.interceptor.LoggingInterceptor") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/manage/health", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } } /* Service Resources Endpoint */ @@ -815,31 +784,6 @@ public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); JSONAssert.assertEquals(badQueryParamResponse, response.getBody().toString(), false); - - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("v2/vfModules", mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(LOG_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("500", mdc.get(RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("v2/vfModules", mdc.get(SERVICE_NAME)); - assertEquals("ERROR", mdc.get(RESPONSE_STATUS_CODE)); - assertNotNull(mdc.get(RESPONSE_DESCRIPTION)); - } } @Test diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java index 54ffc597f4..43b362cbaf 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java @@ -84,7 +84,7 @@ public class AuditCreateStackService extends AbstractAuditService { externalTaskId, getRetrySequence().length); externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); - } else if (retryCount != null && retryCount - 1 == 0) { + } else if (retryCount == 1) { externalTaskService.complete(externalTask, variables); mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java index 9a4f154347..da5e8bb3a2 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java @@ -97,7 +97,7 @@ public class AuditDeleteStackService extends AbstractAuditService { externalTaskId, getRetrySequence().length); externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); - } else if (retryCount != null && retryCount - 1 == 0) { + } else if (retryCount == 1) { externalTaskService.complete(externalTask, variables); mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java index dc672ff017..8699f8b953 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java @@ -60,7 +60,7 @@ public class AuditQueryStackService extends AbstractAuditService { externalTaskId, getRetrySequence().length); externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, getRetrySequence().length, 10000); - } else if (retryCount != null && retryCount - 1 == 0) { + } else if (retryCount == 1) { externalTaskService.complete(externalTask, variables); mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); logger.debug("The External Task {} Failed. All Retries Exhausted", externalTaskId); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/SecurityFilters.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/SecurityFilters.java new file mode 100644 index 0000000000..cbe619e8a0 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.openstack; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/SoCadiFilter.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/SoCadiFilter.java new file mode 100644 index 0000000000..d9901b75ed --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.adapters.openstack; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java index 97e43d9828..ddae887103 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/WebSecurityConfigImpl.java @@ -24,27 +24,57 @@ package org.onap.so.adapters.openstack; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() + .httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/adapters/mso-openstack-adapters/src/main/resources/application-aaf.yaml b/adapters/mso-openstack-adapters/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/resources/application-aaf.yaml diff --git a/adapters/mso-openstack-adapters/src/main/resources/application-basic.yaml b/adapters/mso-openstack-adapters/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/resources/application-basic.yaml diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index 9406bc445d..6b791e789c 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -735,6 +735,8 @@ CREATE TABLE `orchestration_flow_reference` ( `SEQ_NO` int(11) NOT NULL, `FLOW_NAME` varchar(200) NOT NULL, `FLOW_VERSION` double NOT NULL, + `SCOPE` varchar(200) DEFAULT NULL, + `ACTION` varchar(200) DEFAULT NULL, `NB_REQ_REF_LOOKUP_ID` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UK_orchestration_flow_reference` (`COMPOSITE_ACTION`,`FLOW_NAME`,`SEQ_NO`,`NB_REQ_REF_LOOKUP_ID`), @@ -806,6 +808,10 @@ CREATE TABLE `service` ( `OVERALL_DISTRIBUTION_STATUS` varchar(45), `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, `NAMING_POLICY` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -960,6 +966,7 @@ CREATE TABLE `vf_module_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`ID`), KEY `fk_vf_module_customization__vf_module1_idx` (`VF_MODULE_MODEL_UUID`), KEY `fk_vf_module_customization__heat_env__heat_environment1_idx` (`HEAT_ENVIRONMENT_ARTIFACT_UUID`), @@ -1111,6 +1118,7 @@ CREATE TABLE `vnf_resource_customization` ( `SERVICE_MODEL_UUID` varchar(200) NOT NULL, `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1192,6 +1200,7 @@ CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE 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 07d88c9abe..3deabb3ce1 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 @@ -107,7 +107,7 @@ public class ArchiveInfraRequestsScheduler { for (InfraActiveRequests iar : requests) { ArchivedInfraRequests archivedInfra = new ArchivedInfraRequests(); try { - archivedInfra.setAicCloudRegion(iar.getAicCloudRegion()); + archivedInfra.setCloudRegion(iar.getCloudRegion()); archivedInfra.setCallBackUrl(iar.getCallBackUrl()); archivedInfra.setConfigurationId(iar.getConfigurationId()); archivedInfra.setConfigurationName(iar.getConfigurationName()); diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java index f4a9f711fd..110fc6c03e 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,6 +31,7 @@ import org.onap.so.db.request.beans.ResourceOperationStatus; /** * MSO Request DB Adapter Web Service */ +@Deprecated @WebService(name = "RequestsDbAdapter", targetNamespace = "http://org.onap.so/requestsdb") public interface MsoRequestsDbAdapter { diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java index 23fa040387..085a255948 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/MsoRequestsDbAdapterImpl.java @@ -10,9 +10,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -45,6 +45,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; +@Deprecated @WebService(serviceName = "RequestsDbAdapter", endpointInterface = "org.onap.so.adapters.requestsdb.MsoRequestsDbAdapter", targetNamespace = "http://org.onap.so/requestsdb") @@ -183,7 +184,7 @@ public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter { /** * update operation status <br> - * + * * @param serviceId * @param operationId * @param operationType @@ -253,7 +254,7 @@ public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter { /** * init the operation status of all the resources <br> - * + * * @param serviceId the service Id * @param operationId the operation Id * @param operationType the operationType @@ -284,7 +285,7 @@ public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter { /** * get resource operation status <br> - * + * * @param serviceId * @param operationId * @param resourceTemplateUUID @@ -304,7 +305,7 @@ public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter { /** * update resource operation status <br> - * + * * @param serviceId * @param operationId * @param resourceTemplateUUID @@ -340,7 +341,7 @@ public class MsoRequestsDbAdapterImpl implements MsoRequestsDbAdapter { /** * update service operation status when a operation resource status updated <br> - * + * * @param operStatus the resource operation status * @since ONAP Amsterdam Release */ diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java index b8bada298e..6cd7462299 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/WebSecurityConfigImpl.java @@ -24,27 +24,57 @@ package org.onap.so.adapters.requestsdb; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services") + .permitAll().antMatchers("/**") + .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java index 3a14b2ff84..0272bab1a1 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java @@ -22,7 +22,6 @@ package org.onap.so.adapters.requestsdb.application; -import java.time.Duration; import javax.sql.DataSource; import org.onap.logging.filter.base.Constants; import org.onap.logging.filter.base.ONAPComponents; @@ -34,8 +33,7 @@ import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.scheduling.annotation.EnableScheduling; import net.javacrumbs.shedlock.core.LockProvider; import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; -import net.javacrumbs.shedlock.spring.ScheduledLockConfiguration; -import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder; +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; /** * @since Version 1.0 @@ -43,6 +41,7 @@ import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder; */ @SpringBootApplication(scanBasePackages = {"org.onap.so", "org.onap.logging.filter"}) @EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "120s") @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class MSORequestDBApplication { @@ -66,10 +65,5 @@ public class MSORequestDBApplication { return new JdbcTemplateLockProvider(dataSource); } - @Bean - public ScheduledLockConfiguration taskScheduler(LockProvider lockProvider) { - return ScheduledLockConfigurationBuilder.withLockProvider(lockProvider).withPoolSize(10) - .withDefaultLockAtMostFor(Duration.ofMinutes(10)).build(); - } } diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/SecurityFilters.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/SecurityFilters.java new file mode 100644 index 0000000000..a422e6a60d --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.requestsdb.application; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/SoCadiFilter.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/SoCadiFilter.java new file mode 100644 index 0000000000..5e6ced077b --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.adapters.requestsdb.application; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/adapters/mso-requests-db-adapter/src/main/resources/application-aaf.yaml b/adapters/mso-requests-db-adapter/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/application-aaf.yaml diff --git a/adapters/mso-requests-db-adapter/src/main/resources/application-basic.yaml b/adapters/mso-requests-db-adapter/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/application-basic.yaml 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 new file mode 100644 index 0000000000..dbdc925dae --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V7.2__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_ID varchar(45); +ALTER TABLE archived_infra_requests ADD COLUMN IF NOT EXISTS PNF_ID varchar(45);
\ No newline at end of file diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java index 0698023184..a7f21334ed 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/InfraActiveRequestsRepositoryCustomControllerTest.java @@ -111,7 +111,7 @@ public class InfraActiveRequestsRepositoryCustomControllerTest extends RequestsA infraActiveRequests.setNetworkName("networkInstanceNameTest"); infraActiveRequests.setConfigurationId(UUID.randomUUID().toString()); infraActiveRequests.setConfigurationName("configurationInstanceNameTest"); - infraActiveRequests.setAicCloudRegion("1"); + infraActiveRequests.setCloudRegion("1"); infraActiveRequests.setTenantId(UUID.randomUUID().toString()); infraActiveRequests.setRequestScope("operationalEnvironment"); infraActiveRequests.setRequestorId(UUID.randomUUID().toString()); diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java index 92d3114ebe..fef9dbc22c 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java @@ -23,17 +23,14 @@ package org.onap.so.adapters.requestsdb.adapters; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; -import java.util.Map; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.requestsdb.MsoRequestsDbAdapter; import org.onap.so.adapters.requestsdb.RequestStatusType; import org.onap.so.adapters.requestsdb.RequestsAdapterBase; @@ -47,7 +44,6 @@ import org.onap.so.db.request.data.repository.ResourceOperationStatusRepository; import org.onap.so.requestsdb.RequestsDbConstant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.server.LocalServerPort; -import ch.qos.logback.classic.spi.ILoggingEvent; public class MSORequestDBImplTest extends RequestsAdapterBase { @@ -102,7 +98,7 @@ public class MSORequestDBImplTest extends RequestsAdapterBase { testRequest.setServiceInstanceId("e3b5744d-2ad1-4cdd-8390-c999a38829bc"); testRequest.setRequestAction("deleteInstance"); testRequest.setRequestScope("vfModule"); - testRequest.setAicCloudRegion("mtn6"); + testRequest.setCloudRegion("mtn6"); testRequest.setLastModifiedBy("BPMN"); testRequest.setVfModuleId("c7d527b1-7a91-49fd-b97d-1c8c0f4a7992"); testRequest.setVfModuleModelName("vSAMP10aDEV::base::module-0"); @@ -423,28 +419,5 @@ public class MSORequestDBImplTest extends RequestsAdapterBase { ResourceOperationStatus actualResource = dbAdapter.getResourceOperationStatus(serviceId, operationId, "template1"); assertThat(actualResource, sameBeanAs(expectedResource)); - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor") - && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor") - && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals(null, mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETE", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } } - - } diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java index 11b6cf4872..09fea0644e 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/client/RequestsDbClientTest.java @@ -76,7 +76,7 @@ public class RequestsDbClientTest extends RequestsAdapterBase { infraActiveRequests.setNetworkName("networkInstanceNameTest"); infraActiveRequests.setConfigurationId(UUID.randomUUID().toString()); infraActiveRequests.setConfigurationName("configurationInstanceNameTest"); - infraActiveRequests.setAicCloudRegion("1"); + infraActiveRequests.setCloudRegion("1"); infraActiveRequests.setTenantId(UUID.randomUUID().toString()); infraActiveRequests.setRequestScope("operationalEnvironment"); infraActiveRequests.setRequestorId(UUID.randomUUID().toString()); @@ -112,7 +112,7 @@ public class RequestsDbClientTest extends RequestsAdapterBase { infraActiveRequests2.setNetworkName("networkInstanceNameTest"); infraActiveRequests2.setConfigurationId(UUID.randomUUID().toString()); infraActiveRequests2.setConfigurationName("configurationInstanceNameTest"); - infraActiveRequests2.setAicCloudRegion("1"); + infraActiveRequests2.setCloudRegion("1"); infraActiveRequests2.setTenantId(UUID.randomUUID().toString()); infraActiveRequests2.setRequestScope("operationalEnvironment"); infraActiveRequests2.setRequestorId(UUID.randomUUID().toString()); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java index fc6d0a6fc9..55a05436f0 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java @@ -23,7 +23,9 @@ package org.onap.so.adapters.sdnc; import java.util.concurrent.Executor; +import org.onap.logging.filter.base.Constants; import org.onap.logging.filter.spring.MDCTaskDecorator; +import org.onap.so.utils.Components; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -52,6 +54,7 @@ public class SDNCAdapterApplication { } public static void main(String[] args) { + System.setProperty(Constants.Property.PARTNER_NAME, Components.SDNC_ADAPTER.toString()); SpringApplication.run(SDNCAdapterApplication.class, args); System.getProperties().setProperty("server.name", "Springboot"); setLogsDir(); diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SecurityFilters.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SecurityFilters.java new file mode 100644 index 0000000000..c615440ff6 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.sdnc; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SoCadiFilter.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SoCadiFilter.java new file mode 100644 index 0000000000..1e5647097c --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.adapters.sdnc; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java index 232381385f..4d922a4cd0 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/WebSecurityConfigImpl.java @@ -24,27 +24,57 @@ package org.onap.so.adapters.sdnc; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services") + .permitAll().antMatchers("/**") + .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java index 8a1a7559b5..631be2f9ff 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallback.java @@ -24,27 +24,30 @@ package org.onap.so.adapters.sdnc.sdncrest; +import java.net.URI; import javax.xml.bind.DatatypeConverter; -import org.onap.so.logger.LoggingAnchor; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; -import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.adapters.sdnc.impl.Constants; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; +import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.onap.so.utils.CryptoUtils; -import org.slf4j.MDC; import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; /** * Sends asynchronous messages to the BPMN WorkflowMessage service. @@ -95,81 +98,72 @@ public class BPRestCallback { logger.info(LoggingAnchor.THREE, MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message, CAMUNDA); - - HttpPost method = null; - HttpResponse httpResponse = null; - try { int timeout = 60 * 1000; + RestTemplate restTemplate = setRestTemplate(timeout); - RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) - .setConnectionRequestTimeout(timeout).build(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); - HttpClient client = HttpClientBuilder.create().build(); - method = new HttpPost(url); - method.setConfig(requestConfig); - - if (message != null) { - method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON)); - } - - boolean error = false; - - try { - String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP), - env.getProperty(Constants.ENCRYPTION_KEY_PROP)); - String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); - method.setHeader("Authorization", authorization); - method.setHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); - method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME, "SO-SDNCAdapter"); - } catch (Exception e) { - logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, - ErrorCode.BusinessProcessError.getValue(), "Unable to set authorization in callback request", - e); - error = true; - } + boolean error = setAuthorizationHeader(headers); + HttpEntity<String> requestEntity = new HttpEntity<>(message, headers); if (!error) { - httpResponse = client.execute(method); - - @SuppressWarnings("unused") - String responseContent = null; - - if (httpResponse.getEntity() != null) { - responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); - } - - if (httpResponse.getStatusLine().getStatusCode() >= 300) { - String msg = "Received error response to callback request: " + httpResponse.getStatusLine(); - logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, - ErrorCode.BusinessProcessError.getValue(), msg); - - } + postRequest(restTemplate, url, requestEntity); } + logger.info(LoggingAnchor.TWO, MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); return true; } catch (Exception e) { logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, ErrorCode.BusinessProcessError.getValue(), "Error sending callback request", e); return false; - } finally { - if (httpResponse != null) { - try { - EntityUtils.consume(httpResponse.getEntity()); - httpResponse = null; - } catch (Exception e) { - logger.debug("Exception:", e); - } - } + } + } - if (method != null) { - try { - method.reset(); - } catch (Exception e) { - logger.debug("Exception:", e); - } - } - logger.info(LoggingAnchor.TWO, MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA); + protected boolean setAuthorizationHeader(HttpHeaders headers) { + boolean error = false; + try { + String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP), + env.getProperty(Constants.ENCRYPTION_KEY_PROP)); + String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + headers.set("Authorization", authorization); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA, + ErrorCode.BusinessProcessError.getValue(), "Unable to set authorization in callback request", e); + error = true; + } + return error; + } + + private void postRequest(RestTemplate restTemplate, String url, HttpEntity<String> requestEntity) { + ResponseEntity<String> response = null; + try { + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url); + URI uri = builder.build(true).toUri(); + response = restTemplate.postForEntity(uri, requestEntity, String.class); + } catch (HttpStatusCodeException e) { + logResponseError(e.getStatusCode()); + } + if (response != null && response.getStatusCode().is3xxRedirection()) { + logResponseError(response.getStatusCode()); } } + + private void logResponseError(HttpStatus statusCode) { + String msg = "Received error response to callback request: " + statusCode; + logger.error(LoggingAnchor.FOUR, MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, + ErrorCode.BusinessProcessError.getValue(), msg); + } + + protected RestTemplate setRestTemplate(int timeout) { + RestTemplate restTemplate = new RestTemplate(); + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); + factory.setConnectionRequestTimeout(timeout); + factory.setReadTimeout(timeout); + factory.setConnectTimeout(timeout); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; + } } diff --git a/adapters/mso-sdnc-adapter/src/main/resources/application-aaf.yaml b/adapters/mso-sdnc-adapter/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/resources/application-aaf.yaml diff --git a/adapters/mso-sdnc-adapter/src/main/resources/application-basic.yaml b/adapters/mso-sdnc-adapter/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/main/resources/application-basic.yaml diff --git a/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackUnitTest.java b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackUnitTest.java new file mode 100644 index 0000000000..09089890ab --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/test/java/org/onap/so/adapters/sdnc/sdncrest/BPRestCallbackUnitTest.java @@ -0,0 +1,142 @@ +package org.onap.so.adapters.sdnc.sdncrest; + + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.sdnc.impl.Constants; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +@RunWith(MockitoJUnitRunner.class) +public class BPRestCallbackUnitTest { + @Mock + private Environment env; + + @Mock + private RestTemplate restTemplate; + + @Spy + @InjectMocks + private BPRestCallback bpRestCallback; + + private HttpEntity<String> requestEntity; + private String message; + private HttpHeaders headers; + private URI uri; + + @Before + public void setUp() throws IOException { + headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + message = input("BPRestCallbackRequest.json"); + requestEntity = new HttpEntity<>(message, headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http://localhost:8000/sdnc"); + uri = builder.build(true).toUri(); + } + + public String input(String JsonInput) throws IOException { + JsonInput = "src/test/resources/" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + @Test + public void sendTest() throws IOException { + ResponseEntity<String> postResponse = new ResponseEntity<String>("response", HttpStatus.OK); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + when(restTemplate.postForEntity(uri, requestEntity, String.class)).thenReturn(postResponse); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendNoAuthHeaderTest() throws IOException { + doReturn(true).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendErrorTest() throws IOException { + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntity, String.class)) + .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, null, null, null)); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendResponse3xxTest() throws IOException { + ResponseEntity<String> postResponse = new ResponseEntity<String>("response", HttpStatus.MULTIPLE_CHOICES); + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntity, String.class)).thenReturn(postResponse); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertTrue(response); + } + + @Test + public void sendResponseNullMessageTest() throws IOException { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + HttpEntity<String> requestEntityNoMessage = new HttpEntity<>(null, httpHeaders); + ResponseEntity<String> postResponse = new ResponseEntity<String>("response", HttpStatus.OK); + doReturn(false).when(bpRestCallback).setAuthorizationHeader(httpHeaders); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntityNoMessage, String.class)).thenReturn(postResponse); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", null); + assertTrue(response); + } + + @Test + public void postThrowsExceptionTest() throws IOException { + doReturn(false).when(bpRestCallback).setAuthorizationHeader(headers); + doReturn(restTemplate).when(bpRestCallback).setRestTemplate(60000); + when(restTemplate.postForEntity(uri, requestEntity, String.class)) + .thenThrow(new ResourceAccessException("ResourceAccessException")); + boolean response = bpRestCallback.send("http://localhost:8000/sdnc", message); + assertFalse(response); + } + + @Test + public void setAuthorizationHeaderTest() { + HttpHeaders authHeaders = new HttpHeaders(); + when(env.getProperty(Constants.BPEL_AUTH_PROP)) + .thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C"); + when(env.getProperty(Constants.ENCRYPTION_KEY_PROP)).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); + boolean result = bpRestCallback.setAuthorizationHeader(authHeaders); + assertFalse(result); + } + + @Test + public void setAuthorizationHeaderErrorTest() { + HttpHeaders authHeaders = new HttpHeaders(); + when(env.getProperty(Constants.BPEL_AUTH_PROP)).thenReturn("test"); + when(env.getProperty(Constants.ENCRYPTION_KEY_PROP)).thenReturn("test"); + boolean result = bpRestCallback.setAuthorizationHeader(authHeaders); + assertTrue(result); + } +} diff --git a/adapters/mso-sdnc-adapter/src/test/resources/BPRestCallbackRequest.json b/adapters/mso-sdnc-adapter/src/test/resources/BPRestCallbackRequest.json new file mode 100644 index 0000000000..21f3dab7e0 --- /dev/null +++ b/adapters/mso-sdnc-adapter/src/test/resources/BPRestCallbackRequest.json @@ -0,0 +1 @@ +{"SDNCServiceResponse":{"sdncRequestId":"b5b763aa-0d8a-4438-b900-83af45d21d10","responseCode":"200","ackFinalIndicator":"N"}}
\ No newline at end of file diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/SecurityFilters.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/SecurityFilters.java new file mode 100644 index 0000000000..319d79e0fb --- /dev/null +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vfc; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/SoCadiFilter.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/SoCadiFilter.java new file mode 100644 index 0000000000..89526d4cda --- /dev/null +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.adapters.vfc; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java index e94e34d87c..28ac311b4e 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/WebSecurityConfigImpl.java @@ -24,27 +24,57 @@ package org.onap.so.adapters.vfc; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info", "/services") + .permitAll().antMatchers("/**") + .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/adapters/mso-vfc-adapter/src/main/resources/application-aaf.yaml b/adapters/mso-vfc-adapter/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-vfc-adapter/src/main/resources/application-aaf.yaml diff --git a/adapters/mso-vfc-adapter/src/main/resources/application-basic.yaml b/adapters/mso-vfc-adapter/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-vfc-adapter/src/main/resources/application-basic.yaml 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 9d9e33a524..e874c4b8b3 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml @@ -15,6 +15,8 @@ <threetenbp-version>1.3.5</threetenbp-version> <oltu-version>1.0.1</oltu-version> <swagger-core-version>1.5.15</swagger-core-version> + <okhttp3-version>3.14.0</okhttp3-version> + <okhttp-version>2.7.5</okhttp-version> </properties> <name>mso-vnfm-adapter-api</name> <description>MSO VNFM adapter API</description> @@ -47,6 +49,27 @@ </configOptions> </configuration> </execution> + + <execution> + <id>etsicatalog-notification-api</id> + <goals> + <goal>generate</goal> + </goals> + <configuration> + <inputSpec>${basedir}/src/main/resources/ETSI-Catalog-Notification-API.json</inputSpec> + <language>java</language> + <library>okhttp-gson</library> + <output>${project.build.directory}/generated-sources/etsicatalog/notification</output> + <apiPackage>org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.api</apiPackage> + <modelPackage>org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.notification.model</modelPackage> + <configOptions> + <sourceFolder>src/gen/java/main</sourceFolder> + <withXml>true</withXml> + <useRxJava2>true</useRxJava2> + <serializableModel>true</serializableModel> + </configOptions> + </configuration> + </execution> </executions> </plugin> </plugins> @@ -105,5 +128,34 @@ <artifactId>okio</artifactId> <version>1.13.0</version> </dependency> + <dependency> + <groupId>com.squareup.okhttp3</groupId> + <artifactId>okhttp</artifactId> + <version>${okhttp3-version}</version> + </dependency> + <dependency> + <groupId>com.squareup.okhttp3</groupId> + <artifactId>logging-interceptor</artifactId> + <version>${okhttp3-version}</version> + </dependency> + <dependency> + <groupId>com.squareup.okhttp</groupId> + <artifactId>logging-interceptor</artifactId> + <version>${okhttp-version}</version> + </dependency> + <dependency> + <groupId>com.squareup.okhttp</groupId> + <artifactId>okhttp</artifactId> + <version>${okhttp-version}</version> + </dependency> + <dependency> + <groupId>com.squareup.okhttp</groupId> + <artifactId>logging-interceptor</artifactId> + <version>${okhttp-version}</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> </dependencies> </project> 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 new file mode 100644 index 0000000000..6f9b2c3bbe --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/src/main/resources/ETSI-Catalog-Notification-API.json @@ -0,0 +1,230 @@ +{ + "swagger": "2.0", + "info": { + "title": "Modeling etsicatalog API", + "description": "\n\nThe `swagger-ui` view can be found [here](/api/catalog/v1/swagger).\nThe `ReDoc` view can be found [here](/api/catalog/v1/redoc).\nThe swagger YAML document can be found [here](/api/catalog/v1/swagger.yaml).\nThe swagger JSON document can be found [here](/api/catalog/v1/swagger.json).", + "version": "v1" + }, + "host": "127.0.0.1:8000", + "schemes": ["http"], + "basePath": "/", + "consumes": ["application/json"], + "produces": ["application/json"], + "securityDefinitions": { + "Basic": { + "type": "basic" + } + }, + "security": [{ + "Basic": [] + }], + "paths": { + "/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification": { + "get": { + "operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageChangeNotification_list", + "description": "", + "parameters": [], + "responses": { + "204": { + "description": "" + }, + "500": { + "description": "error message", + "schema": { + "type": "string" + } + } + }, + "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" + } + }], + "responses": { + "204": { + "description": "" + } + }, + "tags": ["VNF Package Management interface"] + }, + "parameters": [] + }, + "/URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification": { + "get": { + "operationId": "URI-is-provided-by-the-client-when-creating-the-subscription-VnfPackageOnboardingNotification_list", + "description": "", + "parameters": [], + "responses": { + "204": { + "description": "" + }, + "500": { + "description": "error message", + "schema": { + "type": "string" + } + } + }, + "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" + } + }], + "responses": { + "204": { + "description": "" + } + }, + "tags": ["VNF Package Management interface"] + }, + "parameters": [] + } + }, + "definitions": { + "NOTIFICATION_LINKSERIALIZER": { + "title": "Vnfpackage", + "description": "Link to the resource representing the VNF package to which the notified change applies.", + "required": ["href"], + "type": "object", + "properties": { + "href": { + "title": "Href", + "description": "URI of the referenced resource.", + "type": "string", + "minLength": 1 + } + } + }, + "PkgmLinks": { + "title": " links", + "description": "Links to resources related to this resource.", + "type": "object", + "properties": { + "vnfPackage": { + "$ref": "#/definitions/NOTIFICATION_LINKSERIALIZER" + }, + "subscription": { + "$ref": "#/definitions/NOTIFICATION_LINKSERIALIZER" + } + } + }, + "PkgChangeNotification": { + "required": ["id", "notificationType", "timeStamp", "subscriptionId", "vnfPkgId", "changeType", "vnfdId", "_links"], + "type": "object", + "properties": { + "id": { + "title": "Id", + "description": "Identifier of this notification.", + "type": "string", + "minLength": 1 + }, + "notificationType": { + "title": "Notificationtype", + "description": "Discriminator for the different notification types.", + "type": "string", + "enum": ["VnfPackageChangeNotification"] + }, + "timeStamp": { + "title": "Timestamp", + "description": "Date-time of the generation of the notification.", + "type": "string", + "format": "date-time" + }, + "subscriptionId": { + "title": "Subscriptionid", + "description": "Identifier of the subscription that this notification relates to.", + "type": "string", + "minLength": 1 + }, + "vnfPkgId": { + "title": "Vnfpkgid", + "description": "Identifier of the VNF package.", + "type": "string", + "format": "uuid" + }, + "changeType": { + "title": "Changetype", + "description": "The type of change of the VNF package.", + "type": "string", + "enum": ["OP_STATE_CHANGE", "PKG_DELETE"] + }, + "operationalState": { + "title": "Operationalstate", + "description": "New operational state of the VNF package.", + "type": "string", + "enum": ["ENABLED", "DISABLED"] + }, + "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", + "minLength": 1 + }, + "_links": { + "$ref": "#/definitions/PkgmLinks" + } + } + }, + "PkgOnboardingNotification": { + "required": ["id", "notificationType", "subscriptionId", "timeStamp", "vnfPkgId", "vnfdId", "_links"], + "type": "object", + "properties": { + "id": { + "title": "Id", + "description": "Identifier of this notification.", + "type": "string", + "minLength": 1 + }, + "notificationType": { + "title": "Notificationtype", + "description": "Discriminator for the different notification types.", + "type": "string", + "enum": ["VnfPackageOnboardingNotification"] + }, + "subscriptionId": { + "title": "Subscriptionid", + "description": "Identifier of the subscription that this notification relates to.", + "type": "string", + "minLength": 1 + }, + "timeStamp": { + "title": "Timestamp", + "description": "Date-time of the generation of the notification.", + "type": "string", + "format": "date-time" + }, + "vnfPkgId": { + "title": "Vnfpkgid", + "description": "Identifier of the VNF package.", + "type": "string", + "format": "uuid" + }, + "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" + }, + "_links": { + "$ref": "#/definitions/PkgmLinks" + } + } + } + } +}
\ No newline at end of file diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json index 514029bab8..efd427009d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-ext-clients/src/main/resources/ETSI-Catalog-API.json @@ -764,6 +764,7 @@ } } }, + "produces": ["application/octet-stream", "application/json"], "tags": ["NSD Management interface"] }, "put": { @@ -1129,8 +1130,17 @@ "$ref": "#/definitions/PkgmSubscription" } }, + "400": { + "description": "", + "schema": { + "$ref": "#/definitions/SUBSCRIPTION_ProblemDetailsSerializer" + } + }, "500": { - "description": "Internal error" + "description": "", + "schema": { + "$ref": "#/definitions/SUBSCRIPTION_ProblemDetailsSerializer" + } } }, "tags": ["VNF Package Management interface"] @@ -1330,6 +1340,7 @@ } } }, + "produces": ["application/octet-stream", "application/json"], "tags": ["VNF Package Management interface"] }, "parameters": [{ @@ -1370,6 +1381,7 @@ } } }, + "produces": ["application/octet-stream", "application/json"], "tags": ["VNF Package Management interface"] }, "put": { @@ -1460,6 +1472,7 @@ } } }, + "produces": ["application/octet-stream", "application/json"], "tags": ["VNF Package Management interface"] }, "parameters": [{ @@ -2710,8 +2723,6 @@ } }, "vnfProductsProviders": { - "title": "Vnfproductsfromproviders", - "description": "Match VNF packages that contain VNF products from certain providers.", "required": ["vnfProvider"], "type": "object", "properties": { @@ -2741,7 +2752,11 @@ } }, "vnfProductsFromProviders": { - "$ref": "#/definitions/vnfProductsProviders" + "description": "Match VNF packages that contain VNF products from certain providers.", + "type": "array", + "items": { + "$ref": "#/definitions/vnfProductsProviders" + } }, "vnfdId": { "description": "Match VNF packages with a VNFD identifierlisted in the attribute", 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 32c22356b3..84282e0c7f 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,10 +23,13 @@ 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.Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter; import org.onap.so.adapters.vnfmadapter.oauth.OAuth2AccessTokenAdapter; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.GsonHttpMessageConverter; import org.springframework.security.oauth2.common.OAuth2AccessToken; @@ -38,6 +41,13 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken; public class MessageConverterConfiguration { @Bean + public ConversionService conversionService() { + final DefaultConversionService service = new DefaultConversionService(); + service.addConverter(new Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter()); + return service; + } + + @Bean public HttpMessageConverters customConverters() { final Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); final Gson gson = new GsonBuilder() diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/SecurityFilters.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/SecurityFilters.java new file mode 100644 index 0000000000..3876d77a80 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/SoCadiFilter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/SoCadiFilter.java new file mode 100644 index 0000000000..aefb36c6bb --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.adapters.vnfmadapter; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java index 792002354b..e43efd014a 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java @@ -1,20 +1,22 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ @@ -23,37 +25,64 @@ package org.onap.so.adapters.vnfmadapter; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; -/** - * Configure the web security for the application. - */ +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { @Value("${server.ssl.client-auth:none}") private String clientAuth; - @Override - protected void configure(final HttpSecurity http) throws Exception { - if (("need").equalsIgnoreCase(clientAuth)) { - http.csrf().disable().authorizeRequests().anyRequest().permitAll(); - } else { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); - } + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + if (("need").equalsIgnoreCase(clientAuth)) { + http.csrf().disable().authorizeRequests().anyRequest().permitAll(); + } else { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")) + .and().httpBasic(); + } + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(final WebSecurity web) throws Exception { - super.configure(web); - final StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter.java new file mode 100644 index 0000000000..de18ecc43e --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.converters; + +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.*; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.List; + +/** + * Converter to convert from an Etsi Catalog Model {@link VnfPkgInfo} Object to a PackageManagement Model + * {@link InlineResponse2001} Object + * + * @author andrew.a.lamb@est.tech + */ +@Service +public class Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter + implements Converter<VnfPkgInfo, InlineResponse2001> { + private static final Logger logger = + LoggerFactory.getLogger(Sol003EtsiVnfPkgInfoToPkgmInlineResponse2001Converter.class); + + /** + * Convert a {@link VnfPkgInfo} Object to an {@link InlineResponse2001} Object + * + * @param vnfPkgInfo The VnfPkgInfo Object to Convert + * @return The Converted InlineResponse2001 Object + */ + @Override + public InlineResponse2001 convert(final VnfPkgInfo vnfPkgInfo) { + if (vnfPkgInfo == null) { + logger.info("No VnfPkgInfo Object Provided for Conversion. (Null object received, returning Null)"); + return null; + } + final InlineResponse2001 response = new InlineResponse2001(); + response.setId(vnfPkgInfo.getId()); + response.setVnfdId(vnfPkgInfo.getVnfdId()); + response.setVnfProvider(vnfPkgInfo.getVnfProvider()); + response.setVnfProductName(vnfPkgInfo.getVnfProductName()); + response.setVnfSoftwareVersion(vnfPkgInfo.getVnfSoftwareVersion()); + response.setVnfdVersion(vnfPkgInfo.getVnfdVersion()); + response.setChecksum(convertChecksumToVnfPackagesChecksum(vnfPkgInfo.getChecksum())); + response.setSoftwareImages( + convertVnfPackageSoftwareImageInfoListToVnfPackagesSoftwareImagesList(vnfPkgInfo.getSoftwareImages())); + response.setAdditionalArtifacts(convertVnfPackageArtifactInfoListToVnfPackagesAdditionalArtifactsList( + vnfPkgInfo.getAdditionalArtifacts())); + + if (vnfPkgInfo.getOnboardingState() != null) { + response.setOnboardingState( + InlineResponse2001.OnboardingStateEnum.fromValue(vnfPkgInfo.getOnboardingState().getValue())); + } + + if (vnfPkgInfo.getOperationalState() != null) { + response.setOperationalState( + InlineResponse2001.OperationalStateEnum.fromValue(vnfPkgInfo.getOperationalState().getValue())); + } + + response.setUserDefinedData((vnfPkgInfo.getUserDefinedData())); + + if (vnfPkgInfo.getLinks() != null) { + response.setLinks(convertVNFPKGMLinkSerializerToVnfPackagesLinks(vnfPkgInfo.getLinks())); + } + + return response; + } + + private VnfPackagesChecksum convertChecksumToVnfPackagesChecksum(final Checksum checksum) { + final VnfPackagesChecksum vnfPackagesChecksum = new VnfPackagesChecksum(); + if (checksum != null) { + vnfPackagesChecksum.setAlgorithm(checksum.getAlgorithm()); + vnfPackagesChecksum.setHash(checksum.getHash()); + } + return vnfPackagesChecksum; + } + + private List<VnfPackagesSoftwareImages> convertVnfPackageSoftwareImageInfoListToVnfPackagesSoftwareImagesList( + final List<VnfPackageSoftwareImageInfo> vnfPackageSoftwareImageInfoList) { + final List<VnfPackagesSoftwareImages> vnfPackagesSoftwareImages = new ArrayList<>(); + if (vnfPackageSoftwareImageInfoList != null) { + for (final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo : vnfPackageSoftwareImageInfoList) { + final VnfPackagesSoftwareImages softwareImage = + convertVnfPackageSoftwareImageInfoToVnfPackagesSoftwareImages(vnfPackageSoftwareImageInfo); + vnfPackagesSoftwareImages.add(softwareImage); + } + } + return vnfPackagesSoftwareImages; + } + + private VnfPackagesSoftwareImages convertVnfPackageSoftwareImageInfoToVnfPackagesSoftwareImages( + final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo) { + final VnfPackagesSoftwareImages vnfPackagesSoftwareImages = new VnfPackagesSoftwareImages(); + vnfPackagesSoftwareImages.setId(vnfPackageSoftwareImageInfo.getId()); + vnfPackagesSoftwareImages.setName(vnfPackageSoftwareImageInfo.getName()); + vnfPackagesSoftwareImages.setProvider(vnfPackageSoftwareImageInfo.getProvider()); + vnfPackagesSoftwareImages.setVersion(vnfPackageSoftwareImageInfo.getVersion()); + vnfPackagesSoftwareImages + .setChecksum(convertChecksumToVnfPackagesChecksum(vnfPackageSoftwareImageInfo.getChecksum())); + if (vnfPackageSoftwareImageInfo.getContainerFormat() != null) { + vnfPackagesSoftwareImages.setContainerFormat(VnfPackagesSoftwareImages.ContainerFormatEnum + .fromValue(vnfPackageSoftwareImageInfo.getContainerFormat().getValue())); + } + + if (vnfPackageSoftwareImageInfo.getDiskFormat() != null) { + vnfPackagesSoftwareImages.setDiskFormat(VnfPackagesSoftwareImages.DiskFormatEnum + .fromValue(vnfPackageSoftwareImageInfo.getDiskFormat().getValue())); + } + + vnfPackagesSoftwareImages.setCreatedAt(vnfPackageSoftwareImageInfo.getCreatedAt()); + vnfPackagesSoftwareImages.setMinDisk(vnfPackageSoftwareImageInfo.getMinDisk()); + vnfPackagesSoftwareImages.setMinRam(vnfPackageSoftwareImageInfo.getMinRam()); + vnfPackagesSoftwareImages.setSize(vnfPackageSoftwareImageInfo.getSize()); + vnfPackagesSoftwareImages.setUserMetadata(vnfPackageSoftwareImageInfo.getUserMetadata()); + vnfPackagesSoftwareImages.setImagePath(vnfPackageSoftwareImageInfo.getImagePath()); + return vnfPackagesSoftwareImages; + } + + private List<VnfPackagesAdditionalArtifacts> convertVnfPackageArtifactInfoListToVnfPackagesAdditionalArtifactsList( + final List<VnfPackageArtifactInfo> vnfPackageArtifactInfoList) { + if (vnfPackageArtifactInfoList != null) { + final List<VnfPackagesAdditionalArtifacts> additionalArtifacts = new ArrayList<>(); + for (final VnfPackageArtifactInfo artifactInfo : vnfPackageArtifactInfoList) { + final VnfPackagesAdditionalArtifacts artifact = + convertVnfPackageArtifactInfoToVnfPackagesAdditionalArtifacts(artifactInfo); + additionalArtifacts.add(artifact); + } + return additionalArtifacts; + } + return null; + } + + private VnfPackagesAdditionalArtifacts convertVnfPackageArtifactInfoToVnfPackagesAdditionalArtifacts( + final VnfPackageArtifactInfo vnfPackageArtifactInfo) { + final VnfPackagesAdditionalArtifacts vnfPackagesAdditionalArtifacts = new VnfPackagesAdditionalArtifacts(); + vnfPackagesAdditionalArtifacts.setArtifactPath(vnfPackageArtifactInfo.getArtifactPath()); + vnfPackagesAdditionalArtifacts + .setChecksum(convertChecksumToVnfPackagesChecksum(vnfPackageArtifactInfo.getChecksum())); + vnfPackagesAdditionalArtifacts.setMetadata(vnfPackageArtifactInfo.getMetadata()); + return vnfPackagesAdditionalArtifacts; + } + + private VnfPackagesLinks convertVNFPKGMLinkSerializerToVnfPackagesLinks( + final VNFPKGMLinkSerializer vnfpkgmLinkSerializer) { + final VnfPackagesLinks vnfPackagesLinks = new VnfPackagesLinks(); + vnfPackagesLinks.setSelf(convertUriLinkToVnfPackagesLinksSelf(vnfpkgmLinkSerializer.getSelf())); + vnfPackagesLinks.setVnfd(convertUriLinkToVnfPackagesLinksSelf(vnfpkgmLinkSerializer.getVnfd())); + vnfPackagesLinks + .setPackageContent(convertUriLinkToVnfPackagesLinksSelf(vnfpkgmLinkSerializer.getPackageContent())); + return vnfPackagesLinks; + } + + private VnfPackagesLinksSelf convertUriLinkToVnfPackagesLinksSelf(final UriLink uriLink) { + final VnfPackagesLinksSelf vnfPackagesLinksSelf = new VnfPackagesLinksSelf(); + if (uriLink != null) { + vnfPackagesLinksSelf.setHref(uriLink.getHref()); + } + return vnfPackagesLinksSelf; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/AbstractServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/AbstractServiceProviderConfiguration.java new file mode 100644 index 0000000000..8f6d853997 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/AbstractServiceProviderConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.extclients; + +import com.google.gson.Gson; +import java.util.Iterator; +import org.onap.vnfmadapter.v1.JSON; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.GsonHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +/** + * A base class that can be extended by classes for configuring HttpRestServiceProvider classes. Provides common methods + * that will be useful to some such classes. + * + * @author gareth.roper@est.tech + */ +public abstract class AbstractServiceProviderConfiguration { + + public void setGsonMessageConverter(final RestTemplate restTemplate) { + final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator(); + while (iterator.hasNext()) { + if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { + iterator.remove(); + } + } + final Gson gson = new JSON().getGson(); + restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java new file mode 100644 index 0000000000..d4063951bd --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; + +/** + * Provides methods for invoking REST calls to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +public interface EtsiCatalogServiceProvider { + + /** + * GET Package Content, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the "package_content" will be retrieved. + * @return The Package Content of a VNF Package ("vnfPkgId"). + */ + Optional<byte[]> getVnfPackageContent(final String vnfPkgId); + + /** + * GET VNF packages information from ETSI Catalog. Will return zero or more VNF package representations. + * + * @return An Array of all VNF packages retrieved from the ETSI Catalog. + */ + Optional<InlineResponse2001[]> getVnfPackages(); + + /** + * GET specific VNF package information from ETSI Catalog. + * + * @param vnfPkgId The ID of the VNF Package that you want to query. + * @return The VNF package retrieved from the ETSI Catalog + */ + Optional<InlineResponse2001> getVnfPackage(final String vnfPkgId); + + /** + * GET Package Artifact, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the artifact will be retrieved. + * @param artifactPath Sequence of one or more path segments representing the path of the artifact within the VNF + * Package, e.g., foo/bar/run.sh + * @return The Package Artifact of a VNF Package ("vnfPkgId", "artifactPath"). + */ + Optional<byte[]> getVnfPackageArtifact(final String vnfPkgId, final String artifactPath); + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java new file mode 100644 index 0000000000..6840dd388b --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; +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.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * Configures the HttpRestServiceProvider to make REST calls to the ETSI Catalog Manager + * + * @author gareth.roper@est.tech + */ + +@Configuration +public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration { + + @Bean(name = "etsiCatalogServiceProvider") + public HttpRestServiceProvider httpRestServiceProvider( + @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate) { + return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider()); + } + + private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate, + final HttpHeadersProvider httpHeadersProvider) { + setGsonMessageConverter(restTemplate); + return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java new file mode 100644 index 0000000000..11a59c2ec8 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPkgInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; +import org.onap.so.adapters.vnfmadapter.rest.exceptions.*; +import org.onap.so.rest.exceptions.HttpResouceNotFoundException; +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.core.convert.ConversionService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +/** + * Provides the implementations of the REST Requests to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +@Service +public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvider { + private static final Logger logger = LoggerFactory.getLogger(EtsiCatalogServiceProviderImpl.class); + + @Qualifier("etsiCatalogServiceProvider") + private final HttpRestServiceProvider httpServiceProvider; + private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; + private final ConversionService conversionService; + + @Autowired + public EtsiCatalogServiceProviderImpl(final EtsiCatalogUrlProvider etsiCatalogUrlProvider, + final HttpRestServiceProvider httpServiceProvider, final ConversionService conversionService) { + this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; + this.httpServiceProvider = httpServiceProvider; + this.conversionService = conversionService; + } + + @Override + public Optional<byte[]> getVnfPackageContent(final String vnfPkgId) + throws EtsiCatalogManagerRequestFailureException { + try { + final ResponseEntity<byte[]> response = httpServiceProvider + .getHttpResponse(etsiCatalogUrlProvider.getVnfPackageContentUrl(vnfPkgId), byte[].class); + logger.info("getVnfPackageContent Request to ETSI Catalog Manager Status Code: {}", + response.getStatusCodeValue()); + if (response.getStatusCode() == HttpStatus.OK) { + return Optional.ofNullable(response.getBody()); + } + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { + throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" + + "due to the attribute: onboardingState not being set to ONBOARDED."); + } + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + + @Override + public Optional<byte[]> getVnfPackageArtifact(final String vnfPkgId, final String artifactPath) { + try { + final ResponseEntity<byte[]> response = httpServiceProvider.getHttpResponse( + etsiCatalogUrlProvider.getVnfPackageArtifactUrl(vnfPkgId, artifactPath), byte[].class); + logger.info("getVnfPackageArtifact Request to ETSI Catalog Manager Status Code: {}", + response.getStatusCodeValue()); + if (response.getStatusCode() == HttpStatus.OK) { + return Optional.ofNullable(response.getBody()); + } + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package Artifact found with vnfPkgId: \"" + vnfPkgId + + "\" and artifactPath: \"" + artifactPath + "\"."); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + if (restProcessingException.getStatusCode() == HttpStatus.CONFLICT.value()) { + throw new VnfPkgConflictException("A conflict occurred with the state of the resource,\n" + + "due to the attribute: onboardingState not being set to ONBOARDED."); + } + } + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + + @Override + public Optional<InlineResponse2001[]> getVnfPackages() { + try { + final ResponseEntity<VnfPkgInfo[]> response = + httpServiceProvider.getHttpResponse(etsiCatalogUrlProvider.getVnfPackagesUrl(), VnfPkgInfo[].class); + logger.info("getVnfPackages Request to ETSI Catalog Manager Status Code: {}", + response.getStatusCodeValue()); + if (response.getStatusCode() == HttpStatus.OK) { + if (response.hasBody()) { + final VnfPkgInfo[] vnfPackages = response.getBody(); + final InlineResponse2001[] responses = new InlineResponse2001[vnfPackages.length]; + for (int index = 0; index < vnfPackages.length; index++) { + if (conversionService.canConvert(vnfPackages[index].getClass(), InlineResponse2001.class)) { + final InlineResponse2001 inlineResponse2001 = + conversionService.convert(vnfPackages[index], InlineResponse2001.class); + if (inlineResponse2001 != null) { + responses[index] = inlineResponse2001; + } + } + logger.error("Unable to find Converter for response class: {}", vnfPackages[index].getClass()); + } + return Optional.ofNullable(responses); + } + logger.error("Received response without body ..."); + } + logger.error("Unexpected status code received {}", response.getStatusCode()); + return Optional.empty(); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException", invalidRestRequestException); + throw new VnfPkgBadRequestException("Error: Bad Request Received"); + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Packages found"); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + } + + @Override + public Optional<InlineResponse2001> getVnfPackage(final String vnfPkgId) { + try { + final ResponseEntity<VnfPkgInfo> response = httpServiceProvider + .getHttpResponse(etsiCatalogUrlProvider.getVnfPackageUrl(vnfPkgId), VnfPkgInfo.class); + logger.info("getVnfPackage Request for vnfPkgId {} to ETSI Catalog Manager Status Code: {}", vnfPkgId, + response.getStatusCodeValue()); + if (response.getStatusCode() == HttpStatus.OK) { + if (response.hasBody()) { + final VnfPkgInfo vnfPkgInfo = response.getBody(); + if (conversionService.canConvert(vnfPkgInfo.getClass(), InlineResponse2001.class)) { + return Optional.ofNullable(conversionService.convert(vnfPkgInfo, InlineResponse2001.class)); + } + logger.error("Unable to find Converter for response class: {}", vnfPkgInfo.getClass()); + } + logger.error("Received response without body ...."); + } + return Optional.empty(); + } catch (final InvalidRestRequestException invalidRestRequestException) { + logger.error("Caught InvalidRestRequestException", invalidRestRequestException); + throw new VnfPkgBadRequestException("Error: Bad Request Received"); + } catch (final HttpResouceNotFoundException httpResouceNotFoundException) { + logger.error("Caught HttpResouceNotFoundException", httpResouceNotFoundException); + throw new VnfPkgNotFoundException("No Vnf Package found with vnfPkgId: " + vnfPkgId); + } catch (final RestProcessingException restProcessingException) { + logger.error("Caught RestProcessingException with Status Code: {}", restProcessingException.getStatusCode(), + restProcessingException); + throw new EtsiCatalogManagerRequestFailureException("Internal Server Error Occurred."); + } + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogUrlProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogUrlProvider.java new file mode 100644 index 0000000000..cc2c7a62a4 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogUrlProvider.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; + +import static org.slf4j.LoggerFactory.getLogger; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * Provides the URLs for the REST Requests to the ETSI Catalog Manager. + * + * @author gareth.roper@est.tech + */ +@Service +public class EtsiCatalogUrlProvider { + + private static final Logger logger = getLogger(EtsiCatalogUrlProvider.class); + + @Value("${msb.endpoint:#{\"http://msb_iag.onap:80\"}}") + private String msbEndpoint; + @Value("${msb.catalogServiceUrl:#{null}}") + private String catalogServiceUrl; + @Value("${msb.vnfpkgmServiceUrl:#{\"/api/vnfpkgm/v1\"}}") + private String vnfpkgmServiceUrl; + + public EtsiCatalogUrlProvider() {} + + /** + * Get the URL for retrieving the Package Content from the ETSI Catalog.". + * + * @param vnfPkgId The ID of the VNF Package + * @return the URL for the GET operation + */ + public String getVnfPackageContentUrl(final String vnfPkgId) { + final String url = msbEndpoint + vnfpkgmServiceUrl + "/vnf_packages/" + vnfPkgId + "/package_content"; + logger.info("getEtsiCatalogVnfPackageContentUrl: {}", url); + return url; + } + + /** + * Get the URL for retrieving VNF packages information from ETSI Catalog.". + * + * @return the URL for the GET operation + */ + public String getVnfPackagesUrl() { + final String url = msbEndpoint + vnfpkgmServiceUrl + "/vnf_packages"; + logger.info("getEtsiCatalogVnfPackagesEndpoint: {}", url); + return url; + } + + /** + * Get the URL for retrieving specific VNF package information from the ETSI Catalog.". + * + * @param vnfPkgId The ID of the VNF Package + * @return the URL for the GET operation + */ + public String getVnfPackageUrl(final String vnfPkgId) { + final String url = msbEndpoint + vnfpkgmServiceUrl + "/vnf_packages/" + vnfPkgId; + logger.info("getEtsiCatalogVnfPackageEndpoint: {}", url); + return url; + } + + /** + * Get the URL for retrieving VNF Package Artifacts + * + * @param vnfPkgId The ID of the VNF Package + * @param artifactPath The path to the Artifact + * @return the URL for the GET operation + */ + public String getVnfPackageArtifactUrl(final String vnfPkgId, final String artifactPath) { + final String url = msbEndpoint + vnfpkgmServiceUrl + "/vnf_packages/" + vnfPkgId + "/artifacts/" + artifactPath; + logger.info("getVnfPackageArtifactUrl: {}", url); + return url; + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java index ae9316cfdf..073fc93107 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java @@ -21,7 +21,6 @@ package org.onap.so.adapters.vnfmadapter.extclients.vnfm; import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import com.google.gson.Gson; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; @@ -29,7 +28,6 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; -import java.util.Iterator; import java.util.ListIterator; import java.util.Map; import java.util.UUID; @@ -43,7 +41,7 @@ import org.apache.http.ssl.SSLContextBuilder; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrVnfm; import org.onap.logging.filter.spring.SpringClientPayloadFilter; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON; +import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.rest.service.HttpRestServiceProvider; @@ -58,9 +56,6 @@ import org.springframework.core.io.Resource; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.GsonHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; import org.springframework.web.client.RestTemplate; @@ -69,7 +64,7 @@ import org.springframework.web.client.RestTemplate; * Configures the HttpRestServiceProvider for REST call to a VNFM. */ @Configuration -public class VnfmServiceProviderConfiguration { +public class VnfmServiceProviderConfiguration extends AbstractServiceProviderConfiguration { private static final Logger logger = LoggerFactory.getLogger(VnfmServiceProviderConfiguration.class); private Map<String, HttpRestServiceProvider> mapOfVnfmIdToHttpRestServiceProvider = new ConcurrentHashMap<>(); @@ -135,17 +130,6 @@ public class VnfmServiceProviderConfiguration { return new OAuth2RestTemplate(resourceDetails); } - private void setGsonMessageConverter(final RestTemplate restTemplate) { - final Iterator<HttpMessageConverter<?>> iterator = restTemplate.getMessageConverters().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof MappingJackson2HttpMessageConverter) { - iterator.remove(); - } - } - final Gson gson = new JSON().getGson(); - restTemplate.getMessageConverters().add(new GsonHttpMessageConverter(gson)); - } - private void setTrustStore(final RestTemplate restTemplate) { SSLContext sslContext; try { diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java index 1da1159be0..3f975fbc9c 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java @@ -23,10 +23,13 @@ package org.onap.so.adapters.vnfmadapter.rest; import static org.onap.so.adapters.vnfmadapter.Constants.APPLICATION_ZIP; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; import static org.slf4j.LoggerFactory.getLogger; -import java.util.List; +import java.util.Optional; import javax.ws.rs.core.MediaType; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProvider; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.ProblemDetails; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -45,74 +48,131 @@ import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping(value = PACKAGE_MANAGEMENT_BASE_URL, consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public class Sol003PackageManagementController { - private static final String LOG_REQUEST_RECEIVED = "VNF Package Management Controller: {} {} {} {} {}"; + private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; + private static final String LOG_REQUEST_RECEIVED = "VNF PackageManagement Controller: {} {} {} {}"; private static final Logger logger = getLogger(Sol003PackageManagementController.class); + @Autowired + Sol003PackageManagementController(final EtsiCatalogServiceProvider etsiCatalogServiceProvider) { + this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; + } + /** - * GET VNF packages information. Direction: VNFM -> VNFM-Adapter. Will return zero or more VNF package - * representations that match the attribute filter. These representations will be in a list. Section Number: 10.4.2 - * - * @return A List of all VNF packages. Object: List<InlineResponse2001> Response Code: 200 OK + * GET VNF packages information. Will return zero or more VNF package representations that match the attribute + * filter. These representations will be in a list. Section Number: 10.4.2 + * + * @return An Array of all VNF packages. Object: InlineResponse2001[] Response Code: 200 OK */ - @GetMapping(value = "/vnf_packages", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public ResponseEntity<List<InlineResponse2001>> getVnfPackages() { + public ResponseEntity<?> getVnfPackages() { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackages."); - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + final Optional<InlineResponse2001[]> response = etsiCatalogServiceProvider.getVnfPackages(); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackages Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" \n" + + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(buildProblemDetails(errorMessage)); } /** - * GET VNF package information. Direction: VNFM -> VNFM-Adapter. Will return a specific VNF package representation - * that match the attribute filter. Section Number: 10.4.3 + * GET VNF package information. Will return a specific VNF package representation that match the attribute filter. + * Section Number: 10.4.3 * * @param vnfPkgId The ID of the VNF Package that you want to query. * @return A VNF package based on vnfPkgId. Object: VnfPkgInfo Response Code: 200 OK */ @GetMapping(value = "/vnf_packages/{vnfPkgId}", produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public ResponseEntity<InlineResponse2001> getVnfPackage(@PathVariable("vnfPkgId") final String vnfPkgId) { + public ResponseEntity<?> getVnfPackage(@PathVariable("vnfPkgId") final String vnfPkgId) { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackage: ", vnfPkgId); - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + final Optional<InlineResponse2001> response = etsiCatalogServiceProvider.getVnfPackage(vnfPkgId); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackage Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" by vnfPkgId: \"" + + vnfPkgId + "\" \n" + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(buildProblemDetails(errorMessage)); } /** - * GET VNFD, from VNF package. Direction: VNFM -> VNFM-Adapter. Will return a copy of the file representing the VNFD - * or a ZIP file that contains the file/multiple files representing the VNFD specified. Section Number: 10.4.4 - * + * GET VNFD, from VNF package. Will return a copy of the file representing the VNFD or a ZIP file that contains the + * file/multiple files representing the VNFD specified. Section Number: 10.4.4 + * * @param vnfPkgId The ID of the VNF Package that you want to retrieve the VNFD from. * @return The VNFD of a VNF Package as a single file or within a ZIP file. Object: byte[] Response Code: 200 OK */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP}) - public ResponseEntity<byte[]> getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { + @GetMapping(value = "/vnf_packages/{vnfPkgId}/vnfd", + produces = {MediaType.TEXT_PLAIN, APPLICATION_ZIP, MediaType.APPLICATION_JSON}) + public ResponseEntity<?> getVnfPackageVnfd(@PathVariable("vnfPkgId") final String vnfPkgId) { logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageVnfd: ", vnfPkgId); return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } /** - * GET Package Content, from VNF Package. Direction: VNFM -> VNFM-Adapter. Will return a copy of the VNF package - * file that you specified. Section Number: 10.4.5 - * + * GET Package Content, from VNF Package. Will return a copy of the VNF package file that you specified. Section + * Number: 10.4.5 + * * @param vnfPkgId The ID of the VNF Package that you want to retrieve the "package_content" from. * @return The Package Content of a VNF Package. Object: byte[] Response Code: 200 OK */ - @GetMapping(value = "/vnf_packages/{vnfPkgId}/package_content", produces = {APPLICATION_ZIP}) - public ResponseEntity<byte[]> getVnfPackageContent(@PathVariable("vnfPkgId") final String vnfPkgId) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent: ", vnfPkgId); - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + @GetMapping(value = "/vnf_packages/{vnfPkgId}/package_content", + produces = {MediaType.APPLICATION_JSON, APPLICATION_ZIP, MediaType.APPLICATION_OCTET_STREAM}) + public ResponseEntity<?> getVnfPackageContent(@PathVariable("vnfPkgId") final String vnfPkgId) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Endpoint Invoked with VNF Package ID: ", vnfPkgId); + final Optional<byte[]> response = etsiCatalogServiceProvider.getVnfPackageContent(vnfPkgId); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageContent Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"package_content\" \n" + + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(buildProblemDetails(errorMessage)); } /** - * GET Artifact, from VNF Package. Direction: VNFM -> VNFM-Adapter. Will return a the content of the artifact that - * you specified. Section Number: 10.4.6 - * + * GET Artifact, from VNF Package Will return a the content of the artifact that you specified. Section Number: + * 10.4.6 + * * @param vnfPkgId The ID of the VNF Package that you want to retrieve an artifact from. * @param artifactPath The path of the artifact that you want to retrieve. * @return An Artifact from a VNF Package. Object: byte[] Response Code: 200 OK */ @GetMapping(value = "/vnf_packages/{vnfPkgId}/artifacts/{artifactPath}", - produces = {MediaType.APPLICATION_OCTET_STREAM}) - public ResponseEntity<byte[]> getVnfPackageArtifact(@PathVariable("vnfPkgId") final String vnfPkgId, + produces = {MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON}) + public ResponseEntity<?> getVnfPackageArtifact(@PathVariable("vnfPkgId") final String vnfPkgId, @PathVariable("artifactPath") final String artifactPath) { - logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact: vnfPkgId=", vnfPkgId, " artifactPath=", artifactPath); - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact: vnfPkgId= ", vnfPkgId, " artifactPath=", + artifactPath); + final Optional<byte[]> response = etsiCatalogServiceProvider.getVnfPackageArtifact(vnfPkgId, artifactPath); + if (response.isPresent()) { + logger.info(LOG_REQUEST_RECEIVED, "getVnfPackageArtifact Response: ", HttpStatus.OK); + return ResponseEntity.ok().body(response.get()); + } + final String errorMessage = "An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the\n GET \"vnf_packages\" by vnfPkgId: \"" + + vnfPkgId + "\" for artifactPath: \"" + artifactPath + "\"\n" + "endpoint."; + logger.error(errorMessage); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(buildProblemDetails(errorMessage)); + } + + /** + * Builds the ProblemDetails Object, using the provided error message. + * + * @param detail The error message retrieved from the exception thrown. + * @return ProblemDetails Object, containing error information. + */ + private ProblemDetails buildProblemDetails(final String detail) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(detail); + return problemDetails; } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java index 6fac952aa8..16650d4a3d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementController.java @@ -53,9 +53,9 @@ public class Sol003SubscriptionManagementController { private static final Logger logger = getLogger(Sol003SubscriptionManagementController.class); /** - * POST Subscribe request. Direction: VNFM -> VNFM Adapter. Will send request and respond with the subscription that - * you subscribed to, if successful. Section Number: 10.4.7 - * + * POST Subscribe request. Will send request and respond with the subscription that you subscribed to, if + * successful. Section Number: 10.4.7 + * * @param pkgmSubscriptionRequest This includes the details of the subscription to be created. * @return The subscription requested, if successful. Object: InlineRespone2002 Response Code: 201 Created Response * Code: 303 Duplicate Subscription @@ -68,9 +68,8 @@ public class Sol003SubscriptionManagementController { } /** - * GET all subscriptions. Direction: VNFM -> VNFM Adapter. Will return a list of all subscriptions currently active. - * Section Number: 10.4.7 - * + * GET all subscriptions. Will return a list of all subscriptions currently active. Section Number: 10.4.7 + * * @return All of the current active subscriptions. Object: List<InlineResponse2002> Response Code: 200 OK */ @GetMapping(value = "/subscriptions") @@ -80,8 +79,8 @@ public class Sol003SubscriptionManagementController { } /** - * GET a specific subscription, by subscriptionId. Direction: VNFM -> VNFM Adapter. Section Number: 10.4.8 - * + * GET a specific subscription, by subscriptionId. Section Number: 10.4.8 + * * @param subscriptionId The ID of the subscription that you wish to retrieve. * @return A subscription based on subscriptionId. Object: InlineResponse2002 Response Code: 200 OK */ @@ -93,8 +92,8 @@ public class Sol003SubscriptionManagementController { } /** - * DELETE a specific subscription, by subscriptionId. Direction: VNFM -> VNFM Adapter. Section Number: 10.4.7 - * + * DELETE a specific subscription, by subscriptionId. Section Number: 10.4.7 + * * @param subscriptionId The ID of the subscription that you wish to delete. * @return Empty response if successful. Object: Void Response Code: 204 No Content */ diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiCatalogManagerRequestFailureException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiCatalogManagerRequestFailureException.java new file mode 100644 index 0000000000..dbdc354f4e --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/EtsiCatalogManagerRequestFailureException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for an ETSI Catalog Manager Request Failure + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR) +public class EtsiCatalogManagerRequestFailureException extends RuntimeException { + + private static final long serialVersionUID = 66862444537194516L; + + public EtsiCatalogManagerRequestFailureException(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 new file mode 100644 index 0000000000..a49063a72f --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/Sol003PackageManagementControllerExceptionHandler.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.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; +import org.springframework.web.bind.annotation.ExceptionHandler; + +/** + * Exception Handler for the Package Management Controller {@link Sol003PackageManagementController Sol003Controller} + * + * @author gareth.roper@est.tech + */ +@ControllerAdvice(assignableTypes = Sol003PackageManagementController.class) + +public class Sol003PackageManagementControllerExceptionHandler { + + @ExceptionHandler(EtsiCatalogManagerRequestFailureException.class) + public ResponseEntity<ProblemDetails> handleEtsiCatalogManagerRequestFailureException( + final EtsiCatalogManagerRequestFailureException etsiCatalogManagerRequestFailureException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(etsiCatalogManagerRequestFailureException.getMessage()); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(problemDetails); + } + + @ExceptionHandler(VnfPkgConflictException.class) + public ResponseEntity<ProblemDetails> handleVnfPkgConflictException( + final VnfPkgConflictException vnfPkgConflictException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgConflictException.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT).body(problemDetails); + } + + @ExceptionHandler(VnfPkgNotFoundException.class) + public ResponseEntity<ProblemDetails> handleVnfPkgNotFoundException( + final VnfPkgNotFoundException vnfPkgNotFoundException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgNotFoundException.getMessage()); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(problemDetails); + } + + @ExceptionHandler(VnfPkgBadRequestException.class) + public ResponseEntity<ProblemDetails> handleVnfPkgBadRequestException( + final VnfPkgBadRequestException vnfPkgBadRequestException) { + final ProblemDetails problemDetails = new ProblemDetails(); + problemDetails.setDetail(vnfPkgBadRequestException.getMessage()); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(problemDetails); + } +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgBadRequestException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgBadRequestException.java new file mode 100644 index 0000000000..211131c2a4 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgBadRequestException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for a Vnfpkg Bad Request failure, due to state of resource. + * + * @author andrew.a.lamb@est.tech + */ +@ResponseStatus(code = HttpStatus.BAD_REQUEST) +public class VnfPkgBadRequestException extends RuntimeException { + + private static final long serialVersionUID = 3301317418914258411L; + + public VnfPkgBadRequestException(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/VnfPkgConflictException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgConflictException.java new file mode 100644 index 0000000000..f9aa2a0e21 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgConflictException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for a VnfPkg Conflict failures, due to state of resource. + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.CONFLICT) +public class VnfPkgConflictException extends RuntimeException { + + private static final long serialVersionUID = 26862444537198441L; + + public VnfPkgConflictException(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/VnfPkgNotFoundException.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgNotFoundException.java new file mode 100644 index 0000000000..c15e7052ab --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/exceptions/VnfPkgNotFoundException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest.exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +/** + * Exception for VnfPkg Not Found Failures + * + * @author gareth.roper@est.tech + */ +@ResponseStatus(code = HttpStatus.NOT_FOUND) +public class VnfPkgNotFoundException extends RuntimeException { + + private static final long serialVersionUID = 26862444537198441L; + + public VnfPkgNotFoundException(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/resources/application-aaf.yaml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application-aaf.yaml diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application-basic.yaml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application-basic.yaml diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java index 801c468018..dbc8ef251d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java @@ -1,74 +1,549 @@ -package org.onap.so.adapters.vnfmadapter.rest; +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.rest; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.*; +import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import java.net.URISyntaxException; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import java.util.ArrayList; import java.util.List; +import java.util.Random; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.*; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +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.boot.test.context.SpringBootTest; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.*; 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 com.google.gson.Gson; +/** + * @author gareth.roper@est.tech + */ @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class Sol003PackageManagementControllerTest { - private static final String vnfPackageId = "myVnfPackageId"; - private static final String artifactPath = "myArtifactPath"; + private static final Logger logger = LoggerFactory.getLogger(Sol003PackageManagementControllerTest.class); + + @LocalServerPort + private int port; @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) private RestTemplate testRestTemplate; - private MockRestServiceServer mockRestServer; @Autowired private Sol003PackageManagementController controller; + @Autowired + private TestRestTemplate restTemplate; + + private static final String VNF_PACKAGE_ID = "myVnfPackageId"; + private static final String ARTIFACT_PATH = "myArtifactPath"; + private static final String MSB_BASE_URL = "http://msb_iag.onap:80/api/vnfpkgm/v1/vnf_packages"; + private static final String VNFPKGM_BASE_URL = PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages"; + private static final String localhostUrl = "http://localhost:"; + private static final String GET_VNF_PACKAGES_URL = ""; + private static final String GET_VNF_PACKAGE_BY_ID_URL = "/" + VNF_PACKAGE_ID; + private static final String VNFD_ID = "vnfdId"; + private static final String VNF_PROVIDER = "vnfProvider"; + private static final String VNF_PRODUCT_NAME = "vnfProductName"; + private static final String VNF_SOFTWARE_VERSION = "vnfSoftwareVersion"; + private static final String VNFD_VERSION = "vnfdVersion"; + private static final String ALGORITHM = "algorithm"; + private static final String HASH = "hash"; + private static final String URI_HREF = "uriHref"; + + private MockRestServiceServer mockRestServer; + private BasicHttpHeadersProvider basicHttpHeadersProvider; + private final Gson gson = new Gson(); + + public Sol003PackageManagementControllerTest() {} + @Before - public void setUp() throws Exception { - mockRestServer = MockRestServiceServer.bindTo(testRestTemplate).build(); + public void setUp() { + final MockRestServiceServer.MockRestServiceServerBuilder builder = + MockRestServiceServer.bindTo(testRestTemplate); + builder.ignoreExpectOrder(true); + mockRestServer = builder.build(); + basicHttpHeadersProvider = new BasicHttpHeadersProvider(); + } + + @Test + public void testGetPackageContent_ValidArray_Success() { + final byte[] responseArray = buildByteArrayWithRandomData(10); + + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); + + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/package_content"; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity<byte[]> responseEntity = + restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + + assertEquals(byte[].class, responseEntity.getBody().getClass()); + assertArrayEquals(responseEntity.getBody(), responseArray); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_Conflict_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_NotFound_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_UnauthorizedClient_Fail() { + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/package_content"; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity<ProblemDetails> responseEntity = + restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_InternalServerError_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_BadRequest_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageContent_UnauthorizedServer_InternalError_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertTrue(responseEntity.getBody() instanceof ProblemDetails); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageContent_SuccessResponseFromServerWithNullPackage_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/package_content")) + .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/package_content"); + + assertEquals(ProblemDetails.class, responseEntity.getBody().getClass()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + } + + @Test + public void testGetPackageArtifact_ValidArray_Success() { + final byte[] responseArray = buildByteArrayWithRandomData(10); + + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(responseArray, MediaType.APPLICATION_OCTET_STREAM)); + + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity<byte[]> responseEntity = + restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + + assertEquals(byte[].class, responseEntity.getBody().getClass()); + assertArrayEquals(responseEntity.getBody(), responseArray); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_Conflict_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.CONFLICT)); + + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.CONFLICT, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_NotFound_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_UnauthorizedClient_Fail() { + final String testURL = "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity<ProblemDetails> responseEntity = + restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode()); + } + + @Test + public void testOnGetPackageArtifact_InternalServerError_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); } @Test - public void getVnfPackages() throws URISyntaxException, InterruptedException { - final ResponseEntity<List<InlineResponse2001>> response = controller.getVnfPackages(); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageArtifact_BadRequest_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); } @Test - public void getVnfPackage() throws URISyntaxException, InterruptedException { - final ResponseEntity<InlineResponse2001> response = controller.getVnfPackage(vnfPackageId); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testOnGetPackageArtifact_UnauthorizedServer_InternalError_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.UNAUTHORIZED)); + + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); } @Test - public void getVnfPackageVnfd() throws URISyntaxException, InterruptedException { - final ResponseEntity<byte[]> response = controller.getVnfPackageVnfd(vnfPackageId); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testGetPackageArtifact_SuccessResponseFromServerWithNullPackage_Fail() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH)) + .andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity<ProblemDetails> responseEntity = + sendHttpRequest(VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH); + + assertNotNull(responseEntity.getBody()); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); } @Test - public void getVnfPackageContents() throws URISyntaxException, InterruptedException { - final ResponseEntity<byte[]> response = controller.getVnfPackageContent(vnfPackageId); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void testVnfPackagesReceivedAsInlineResponse2001ListIfGetVnfPackagesSuccessful() { + final VnfPkgInfo[] responses = createVnfPkgArray(); + + mockRestServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(responses), MediaType.APPLICATION_JSON)); + + final String testURL = localhostUrl + port + VNFPKGM_BASE_URL; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + + final ResponseEntity<InlineResponse2001[]> responseEntity = restTemplate.withBasicAuth("test", "test") + .exchange(testURL, HttpMethod.GET, request, InlineResponse2001[].class); + + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final InlineResponse2001[] inlineResponse2001array = responseEntity.getBody(); + final InlineResponse2001 inlineResponse2001 = inlineResponse2001array[0]; + assertEquals(VNF_PACKAGE_ID, inlineResponse2001.getId()); + assertEquals(VNFD_ID, inlineResponse2001.getVnfdId()); + assertEquals(VNFD_ID, inlineResponse2001.getSoftwareImages().get(0).getId()); + assertEquals(VNF_PRODUCT_NAME, inlineResponse2001.getSoftwareImages().get(0).getName()); + assertEquals(ALGORITHM, inlineResponse2001.getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getChecksum().getHash()); + assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); + assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); + assertEquals(URI_HREF, inlineResponse2001.getLinks().getSelf().getHref()); } @Test - public void getVnfPackageArtifact() throws URISyntaxException, InterruptedException { - final ResponseEntity<byte[]> response = controller.getVnfPackageArtifact(vnfPackageId, artifactPath); - assertEquals(HttpStatus.NOT_IMPLEMENTED, response.getStatusCode()); + public void test400BadRequestInfoReceivedAsProblemDetailsIfGetVnfPackagesIs400BadRequest() { + mockRestServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Error: Bad Request Received", problemDetails.getDetail()); + } + + @Test + public void test404NotFoundInfoReceivedAsProblemDetailsIfGetVnfPackagesIs404NotFound() { + mockRestServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("No Vnf Packages found", problemDetails.getDetail()); } + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackagesReturns500InternalServerError() { + mockRestServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Internal Server Error Occurred.", problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackagesReturnsANullPackage() { + mockRestServer.expect(requestTo(MSB_BASE_URL)).andExpect(method(HttpMethod.GET)).andRespond(withSuccess()); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGES_URL); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" \n" + + "endpoint.", problemDetails.getDetail()); + } + + @Test + public void testVnfPackageReceivedAsInlineResponse2001IfGetVnfPackageByIdSuccessful() { + final VnfPkgInfo response = createVnfPkgInfo(VNF_PACKAGE_ID); + + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess(gson.toJson(response), MediaType.APPLICATION_JSON)); + + final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + VNF_PACKAGE_ID; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + final ResponseEntity<InlineResponse2001> responseEntity = restTemplate.withBasicAuth("test", "test") + .exchange(testURL, HttpMethod.GET, request, InlineResponse2001.class); + + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final InlineResponse2001 inlineResponse2001 = responseEntity.getBody(); + assertEquals(VNF_PACKAGE_ID, inlineResponse2001.getId()); + assertEquals(VNFD_ID, inlineResponse2001.getVnfdId()); + assertEquals(VNFD_ID, inlineResponse2001.getSoftwareImages().get(0).getId()); + assertEquals(VNF_PRODUCT_NAME, inlineResponse2001.getSoftwareImages().get(0).getName()); + assertEquals(ALGORITHM, inlineResponse2001.getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getChecksum().getHash()); + assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); + assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); + assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); + assertEquals(URI_HREF, inlineResponse2001.getLinks().getSelf().getHref()); + } + + @Test + public void test400BadRequestInfoReceivedAsProblemDetailsIfGetVnfPackageByIdIs400BadRequest() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.BAD_REQUEST)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Error: Bad Request Received", problemDetails.getDetail()); + } + + @Test + public void test404NotFoundInfoReceivedAsProblemDetailsIfGetVnfPackageByIdIs404NotFound() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("No Vnf Package found with vnfPkgId: " + VNF_PACKAGE_ID, problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackageByIdReturns500InternalServerError() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR)); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("Internal Server Error Occurred.", problemDetails.getDetail()); + } + + @Test + public void test500InternalServerErrorProblemDetailsReceivedIfGetVnfPackageByIdReturnsANullPackage() { + mockRestServer.expect(requestTo(MSB_BASE_URL + "/" + VNF_PACKAGE_ID)).andExpect(method(HttpMethod.GET)) + .andRespond(withSuccess()); + + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(GET_VNF_PACKAGE_BY_ID_URL); + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); + + assertNotNull(responseEntity.getBody()); + final ProblemDetails problemDetails = responseEntity.getBody(); + assertEquals("An error occurred, a null response was received by the\n" + + " Sol003PackageManagementController from the EtsiCatalogManager using the GET \"vnf_packages\" by vnfPkgId: \"" + + VNF_PACKAGE_ID + "\" \n" + "endpoint.", problemDetails.getDetail()); + } + + // The below test method is here to improve code coverage and provide a foundation for writing future tests + @Test + public void testGetVnfd_Not_Implemented() { + final ResponseEntity<ProblemDetails> responseEntity = sendHttpRequest(VNF_PACKAGE_ID + "/vnfd"); + assertEquals(HttpStatus.NOT_IMPLEMENTED, responseEntity.getStatusCode()); + } + + // Simply returns a byte array filled with random data, for use in the tests. + private byte[] buildByteArrayWithRandomData(final int sizeInKb) { + final Random rnd = new Random(); + final byte[] b = new byte[sizeInKb * 1024]; // converting kb to byte + rnd.nextBytes(b); + return b; + } + + private ResponseEntity<ProblemDetails> sendHttpRequest(final String url) { + final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + url; + final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); + return restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, + ProblemDetails.class); + } + + private VnfPkgInfo[] createVnfPkgArray() { + final VnfPkgInfo[] vnfPkgInfoArray = new VnfPkgInfo[1]; + final VnfPkgInfo vnfPkgInfo = createVnfPkgInfo(VNF_PACKAGE_ID); + vnfPkgInfoArray[0] = vnfPkgInfo; + return vnfPkgInfoArray; + } + + private VnfPkgInfo createVnfPkgInfo(final String vnfPackageId) { + final VnfPkgInfo vnfPkgInfo = new VnfPkgInfo(); + vnfPkgInfo.setId(vnfPackageId); + vnfPkgInfo.setVnfdId(VNFD_ID); + vnfPkgInfo.setVnfProvider(VNF_PROVIDER); + vnfPkgInfo.setVnfProductName(VNF_PRODUCT_NAME); + vnfPkgInfo.setVnfSoftwareVersion(VNF_SOFTWARE_VERSION); + vnfPkgInfo.setVnfdVersion(VNFD_VERSION); + vnfPkgInfo.setChecksum(createVnfPkgChecksum()); + vnfPkgInfo.setSoftwareImages(createSoftwareImages()); + vnfPkgInfo.setAdditionalArtifacts(createAdditionalArtifacts()); + vnfPkgInfo.setLinks(createVNFPKGMLinkSerializerLinks()); + return vnfPkgInfo; + } + + private Checksum createVnfPkgChecksum() { + final Checksum checksum = new Checksum(); + checksum.setAlgorithm(ALGORITHM); + checksum.setHash(HASH); + return checksum; + } + + private List<VnfPackageSoftwareImageInfo> createSoftwareImages() { + final List<VnfPackageSoftwareImageInfo> softwareImages = new ArrayList<>(); + final VnfPackageSoftwareImageInfo vnfPackageSoftwareImageInfo = new VnfPackageSoftwareImageInfo(); + vnfPackageSoftwareImageInfo.setId(VNFD_ID); + vnfPackageSoftwareImageInfo.setName(VNF_PRODUCT_NAME); + vnfPackageSoftwareImageInfo.setProvider(""); + vnfPackageSoftwareImageInfo.setVersion(""); + vnfPackageSoftwareImageInfo.setChecksum(createVnfPkgChecksum()); + vnfPackageSoftwareImageInfo + .setContainerFormat(VnfPackageSoftwareImageInfo.ContainerFormatEnum.fromValue("AKI")); + softwareImages.add(vnfPackageSoftwareImageInfo); + return softwareImages; + } + + private List<VnfPackageArtifactInfo> createAdditionalArtifacts() { + final List<VnfPackageArtifactInfo> vnfPackageArtifactInfos = new ArrayList<>(); + final VnfPackageArtifactInfo vnfPackageArtifactInfo = + new VnfPackageArtifactInfo().artifactPath(ARTIFACT_PATH).checksum(createVnfPkgChecksum()); + vnfPackageArtifactInfos.add(vnfPackageArtifactInfo); + return vnfPackageArtifactInfos; + } + + private VNFPKGMLinkSerializer createVNFPKGMLinkSerializerLinks() { + final UriLink uriLink = new UriLink().href(URI_HREF); + final VNFPKGMLinkSerializer vnfpkgmLinkSerializer = new VNFPKGMLinkSerializer().self(uriLink); + return vnfpkgmLinkSerializer; + } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java index 999dd02f0f..8fc27c5943 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003SubscriptionManagementControllerTest.java @@ -20,6 +20,10 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; +/** + * @author gareth.roper@est.tech + */ + @RunWith(SpringRunner.class) @SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/SecurityFilters.java b/asdc-controller/src/main/java/org/onap/so/asdc/SecurityFilters.java new file mode 100644 index 0000000000..29c9d8f952 --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.asdc; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("!test & aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/SoCadiFilter.java b/asdc-controller/src/main/java/org/onap/so/asdc/SoCadiFilter.java new file mode 100644 index 0000000000..52144e264e --- /dev/null +++ b/asdc-controller/src/main/java/org/onap/so/asdc/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.asdc; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("!test & aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java b/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java index b45b4f0749..8722d193fe 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/WebSecurityConfigImpl.java @@ -22,27 +22,57 @@ package org.onap.so.asdc; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() + .httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; } } diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java index 3f1b080ec1..dcb49478f4 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/ToscaResourceStructure.java @@ -25,7 +25,6 @@ package org.onap.so.asdc.installer; import java.io.File; import java.nio.file.Paths; import java.util.List; -import org.onap.so.logger.LoggingAnchor; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; @@ -52,10 +51,10 @@ import org.onap.so.db.catalog.beans.VfModule; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResourceCustomization; 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; -import org.springframework.beans.factory.annotation.Value; public class ToscaResourceStructure { 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 8d51d5b894..240bb83862 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 @@ -182,6 +182,12 @@ public class ToscaResourceInstaller { protected static final String SKIP_POST_INST_CONF = "skip_post_instantiation_configuration"; + private static final String CONTROLLER_ACTOR = "controller_actor"; + + private static final String CDS_MODEL_NAME = "cds_model_name"; + + private static final String CDS_MODEL_VERSION = "cds_model_version"; + @Autowired protected ServiceRepository serviceRepo; @@ -577,7 +583,7 @@ public class ToscaResourceInstaller { String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(",")); service.setResourceOrder(resourceSeqStr); - logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr); + logger.debug(" resourceSeq for service uuid {}: {}", service.getModelUUID(), resourceSeqStr); } @@ -638,8 +644,7 @@ public class ToscaResourceInstaller { String jsonStr = objectMapper.writeValueAsString(resouceRequest); jsonStr = jsonStr.replace("\"", "\\\""); - logger.debug( - "resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr); + logger.debug("resource request for resource customization id {}: {}", resourceCustomizationUuid, jsonStr); return jsonStr; } catch (JsonProcessingException e) { logger.error("resource input could not be deserialized for resource customization id (" @@ -682,8 +687,8 @@ public class ToscaResourceInstaller { networkCustomization.setResourceInput( getResourceInput(toscaResourceStruct, networkCustomization.getModelCustomizationUUID())); service.getNetworkCustomizations().add(networkCustomization); - logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for " - + networkResourceModelName); + logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for {}", + networkResourceModelName); } } @@ -975,8 +980,8 @@ public class ToscaResourceInstaller { pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME))); pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION))); pnfResourceCustomization.setSkipPostInstConf(getBooleanValue(properties.get(SKIP_POST_INST_CONF))); + pnfResourceCustomization.setControllerActor(getStringValue(properties.get(CONTROLLER_ACTOR))); pnfResourceCustomization.setPnfResources(pnfResource); - return pnfResourceCustomization; } @@ -1008,25 +1013,25 @@ public class ToscaResourceInstaller { String vfCustomizationCategory = vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY); - logger.debug("VF Category is : " + vfCustomizationCategory); + logger.debug("VF Category is: {} ", vfCustomizationCategory); String vfCustomizationUUID = vfEntityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - logger.debug("VFCustomizationUUID=" + vfCustomizationUUID); + logger.debug("VFCustomizationUUID= {}", vfCustomizationUUID); IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance(); // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before // comparing their VF Modules UUID's - logger.debug("Checking if Notification VF ResourceCustomizationUUID: " - + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: " - + vfCustomizationUUID); + logger.debug( + "Checking if Notification VF ResourceCustomizationUUID: {} matches Tosca VF Customization UUID: {}", + vfNotificationResource.getResourceCustomizationUUID(), vfCustomizationUUID); if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) { - logger.debug("vfCustomizationUUID: " + vfCustomizationUUID - + " matches vfNotificationResource CustomizationUUID"); + logger.debug("vfCustomizationUUID: {} matches vfNotificationResource CustomizationUUID ", + vfCustomizationUUID); VnfResourceCustomization vnfResource = createVnfResource(vfEntityDetails, toscaResourceStruct, service); @@ -1038,7 +1043,7 @@ public class ToscaResourceInstaller { for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { - logger.debug("vfModuleStructure:" + vfModuleStructure.toString()); + logger.debug("vfModuleStructure: {}", vfModuleStructure); List<IEntityDetails> vfModuleEntityList = getEntityDetails(toscaResourceStruct, @@ -1087,7 +1092,7 @@ public class ToscaResourceInstaller { if (!CollectionUtils.isEmpty(seqResult)) { String resultStr = seqResult.stream().collect(Collectors.joining(",")); vnfResource.setVnfcInstanceGroupOrder(resultStr); - logger.debug("vnfcGroupOrder result for service uuid(" + service.getModelUUID() + ") : " + resultStr); + logger.debug("vnfcGroupOrder result for service uuid {}: {}", service.getModelUUID(), resultStr); } // add this vnfResource with existing vnfResource for this service addVnfCustomization(service, vnfResource); @@ -1197,7 +1202,7 @@ public class ToscaResourceInstaller { watchdogDistributionStatusRepository.saveAndFlush(distributionStatus); } catch (ObjectOptimisticLockingFailureException e) { - logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString()); + logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : {} ", e); throw e; } } @@ -1401,7 +1406,6 @@ public class ToscaResourceInstaller { ResourceStructure resourceStructure) { Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata(); - List<Service> services = serviceRepo.findByModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); Service service; @@ -1438,6 +1442,10 @@ public class ToscaResourceInstaller { generateNamingValue = "true".equalsIgnoreCase(generateNaming); } service.setOnapGeneratedNaming(generateNamingValue); + service.setBlueprintName(serviceMetadata.getValue(CDS_MODEL_NAME)); + service.setBlueprintVersion(serviceMetadata.getValue(CDS_MODEL_VERSION)); + service.setSkipPostInstConf(Boolean.valueOf(serviceMetadata.getValue(SKIP_POST_INST_CONF))); + service.setControllerActor(serviceMetadata.getValue(CONTROLLER_ACTOR)); } @@ -2028,8 +2036,8 @@ public class ToscaResourceInstaller { ObjectMapper objectMapper = new ObjectMapper(); jsonStr = objectMapper.writeValueAsString(resouceRequest); jsonStr = jsonStr.replace("\"", "\\\""); - logger.debug("vfcResource request for resource customization id (" + resourceCustomizationUuid + ") : " - + jsonStr); + logger.debug("vfcResource request for resource customization id {}: {}", resourceCustomizationUuid, + jsonStr); } catch (JsonProcessingException e) { logger.debug("Json Exception: {}", e.getMessage()); logger.error("Exception occurred", e); @@ -2382,6 +2390,14 @@ public class ToscaResourceInstaller { if (minInstances != null && minInstances.length() > 0) { vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances)); } + + String skipPostInstConfText = getLeafPropertyValue(vfModuleEntityDetails, SKIP_POST_INST_CONF); + + if (skipPostInstConfText != null) { + vfModuleCustomization.setSkipPostInstConf( + Boolean.parseBoolean(getLeafPropertyValue(vfModuleEntityDetails, SKIP_POST_INST_CONF))); + } + return vfModuleCustomization; } @@ -2576,7 +2592,7 @@ public class ToscaResourceInstaller { Boolean.parseBoolean(getLeafPropertyValue(entityDetails, SKIP_POST_INST_CONF))); } - + vnfResourceCustomization.setControllerActor(getLeafPropertyValue(entityDetails, CONTROLLER_ACTOR)); vnfResourceCustomization.setVnfResources(vnfResource); vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger( entityDetails.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT))); diff --git a/asdc-controller/src/main/resources/application-aaf.yaml b/asdc-controller/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/asdc-controller/src/main/resources/application-aaf.yaml diff --git a/asdc-controller/src/main/resources/application-basic.yaml b/asdc-controller/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/asdc-controller/src/main/resources/application-basic.yaml diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java index 0c7f97759b..3db017cac5 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java @@ -1,15 +1,20 @@ -/* - * ============LICENSE_START======================================================= Copyright (C) 2019 Nordix - * Foundation. ================================================================================ Licensed under the - * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may - * obtain a copy of the License at +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix + * ================================================================================ + * 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. + * 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========================================================= + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= */ package org.onap.so.asdc.client; @@ -20,6 +25,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collections; @@ -29,7 +35,6 @@ import java.util.UUID; import javax.persistence.EntityNotFoundException; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; @@ -64,7 +69,10 @@ import org.springframework.transaction.annotation.Transactional; * This is used to run some basic integration test(BIT) for ASDC controller. It will test the csar install and all the * testing csar files are located underneath src/main/resources/download folder, * - * PNF csar: service-Testservice140-csar.csar VNF csar: service-Svc140-VF-csar.csar + * PNF csar: service-pnfservice.csar VNF csar: service-Svc140-VF-csar.csar + * + * All the csar files are cleaned, i.e, removing the comments and most of the description to avoid violation of + * security. */ @Transactional public class ASDCControllerITTest extends BaseTest { @@ -141,13 +149,149 @@ public class ASDCControllerITTest extends BaseTest { * Mock the AAI using wireshark. */ private void initMockAaiServer(final String serviceUuid, final String serviceInvariantUuid) { - String modelEndpoint = "/aai/v15/service-design-and-creation/models/model/" + serviceInvariantUuid + String modelEndpoint = "/aai/v17/service-design-and-creation/models/model/" + serviceInvariantUuid + "/model-vers/model-ver/" + serviceUuid + "?depth=0"; wireMockServer.stubFor(post(urlEqualTo(modelEndpoint)).willReturn(ok())); } /** + * Test with service-pnfservice.csar. + */ + @Test + public void treatNotification_ValidPnfResource_ExpectedOutput() { + + /** + * service UUID/invariantUUID from global metadata in service-PnfServiceTestCds-template.yml. + */ + String serviceUuid = "77cf276e-905c-43f6-8d54-dda474be2f2e"; + String serviceInvariantUuid = "913e6776-4bc3-49b9-b399-b5bb4690f0c7"; + + initMockAaiServer(serviceUuid, serviceInvariantUuid); + + NotificationDataImpl notificationData = new NotificationDataImpl(); + notificationData.setServiceUUID(serviceUuid); + notificationData.setDistributionID(distributionId); + notificationData.setServiceInvariantUUID(serviceInvariantUuid); + notificationData.setServiceVersion("1.0"); + + ResourceInfoImpl resourceInfo = constructPnfResourceInfo(); + List<ResourceInfoImpl> resourceInfoList = new ArrayList<>(); + resourceInfoList.add(resourceInfo); + notificationData.setResources(resourceInfoList); + + ArtifactInfoImpl artifactInfo = constructPnfServiceArtifact(); + List<ArtifactInfoImpl> artifactInfoList = new ArrayList<>(); + artifactInfoList.add(artifactInfo); + notificationData.setServiceArtifacts(artifactInfoList); + + try { + asdcController.treatNotification(notificationData); + + logger.info("Checking the database for PNF ingestion"); + + /** + * Check the tosca csar entity, it should be the same as provided from NotficationData. + */ + ToscaCsar toscaCsar = toscaCsarRepository.findById(artifactUuid) + .orElseThrow(() -> new EntityNotFoundException("Tosca csar: " + artifactUuid + " not found")); + assertEquals("tosca csar UUID", artifactUuid, toscaCsar.getArtifactUUID()); + assertEquals("tosca csar name", "service-pnfservice.csar", toscaCsar.getName()); + assertEquals("tosca csar version", "1.0", toscaCsar.getVersion()); + assertNull("tosca csar descrption", toscaCsar.getDescription()); + assertEquals("tosca csar checksum", "MANUAL_RECORD", toscaCsar.getArtifactChecksum()); + assertEquals("toscar csar URL", "/download/service-pnfservice.csar", toscaCsar.getUrl()); + + /** + * Check the service entity, it should be the same as global metadata information in + * service-Testservice140-template.yml inside csar. + */ + Service service = serviceRepository.findById(serviceUuid) + .orElseThrow(() -> new EntityNotFoundException("Service: " + serviceUuid + " not found")); + assertEquals("model UUID", serviceUuid, service.getModelUUID()); + assertEquals("model name", "PNF Service Test CDS", service.getModelName()); + assertEquals("model invariantUUID", serviceInvariantUuid, service.getModelInvariantUUID()); + assertEquals("model version", "1.0", service.getModelVersion()); + assertEquals("description", "123123", service.getDescription().trim()); + assertEquals("tosca csar artifact UUID", artifactUuid, service.getCsar().getArtifactUUID()); + assertEquals("service type", "", service.getServiceType()); + assertEquals("service role", "", service.getServiceRole()); + assertEquals("environment context", "General_Revenue-Bearing", service.getEnvironmentContext()); + assertEquals("service category", "Network L1-3", service.getCategory()); + assertNull("workload context", service.getWorkloadContext()); + assertEquals("resource order", "PNF CDS Test", service.getResourceOrder()); + assertEquals("CDS blueprint name", "Blueprint140", service.getBlueprintName()); + assertEquals("CDS blueprint version", "v1.4.0", service.getBlueprintVersion()); + assertEquals("controller actor", "SO-REF-DATA", service.getControllerActor()); + + /** + * Check PNF resource, it should be the same as metadata in the topology template in + * service-PnfServiceTestCds-template.yml OR global metadata in the resource-PnfServiceTestCds-template.yml + */ + String pnfResourceKey = "aa5d0562-80e7-43e9-af74-3085e57ab09f"; + PnfResource pnfResource = pnfResourceRepository.findById(pnfResourceKey) + .orElseThrow(() -> new EntityNotFoundException("PNF resource:" + pnfResourceKey + " not found")); + assertNull("orchestration mode", pnfResource.getOrchestrationMode()); + assertEquals("Description", "123123", pnfResource.getDescription().trim()); + assertEquals("model UUID", pnfResourceKey, pnfResource.getModelUUID()); + assertEquals("model invariant UUID", "17d9d183-cee5-4a46-b5c4-6d5203f7d2e8", + pnfResource.getModelInvariantUUID()); + assertEquals("model version", "1.0", pnfResource.getModelVersion()); + assertEquals("model name", "PNF CDS Test", pnfResource.getModelName()); + assertEquals("tosca node type", "org.openecomp.resource.pnf.PnfCdsTest", pnfResource.getToscaNodeType()); + assertEquals("resource category", "Application L4+", pnfResource.getCategory()); + assertEquals("resource sub category", "Firewall", pnfResource.getSubCategory()); + + /** + * Check PNF resource customization, it should be the same as metadata in the topology template in + * service-PnfServiceTestCds-template.yml OR global metadata in the resource-PnfServiceTestCds-template.yml + */ + String pnfCustomizationKey = "9f01263a-eaf7-4d98-a37b-3785f751903e"; + PnfResourceCustomization pnfCustomization = pnfCustomizationRepository.findById(pnfCustomizationKey) + .orElseThrow(() -> new EntityNotFoundException( + "PNF resource customization: " + pnfCustomizationKey + " not found")); + assertEquals("model customizationUUID", pnfCustomizationKey, pnfCustomization.getModelCustomizationUUID()); + assertEquals("model instance name", "PNF CDS Test 0", pnfCustomization.getModelInstanceName()); + assertEquals("NF type", "", pnfCustomization.getNfType()); + assertEquals("NF Role", "nf", pnfCustomization.getNfRole()); + assertEquals("NF function", "nf", pnfCustomization.getNfFunction()); + assertEquals("NF naming code", "", pnfCustomization.getNfNamingCode()); + assertEquals("PNF resource model UUID", pnfResourceKey, pnfCustomization.getPnfResources().getModelUUID()); + assertEquals("Multi stage design", "", pnfCustomization.getMultiStageDesign()); + assertNull("resource input", pnfCustomization.getResourceInput()); + assertEquals("cds blueprint name(sdnc_model_name property)", "Blueprint140", + pnfCustomization.getBlueprintName()); + assertEquals("cds blueprint version(sdnc_model_version property)", "v1.4.0", + pnfCustomization.getBlueprintVersion()); + assertTrue("skip post instantiation configuration", pnfCustomization.isSkipPostInstConf()); + assertEquals("controller actor", "SO-REF-DATA", pnfCustomization.getControllerActor()); + + /** + * Check the pnf resource customization with service mapping + */ + List<PnfResourceCustomization> pnfCustList = service.getPnfCustomizations(); + assertEquals("PNF resource customization entity", 1, pnfCustList.size()); + assertEquals(pnfCustomizationKey, pnfCustList.get(0).getModelCustomizationUUID()); + + /** + * Check the watchdog for component distribution status + */ + List<WatchdogComponentDistributionStatus> distributionList = + watchdogCDStatusRepository.findByDistributionId(this.distributionId); + assertNotNull(distributionList); + assertEquals(1, distributionList.size()); + WatchdogComponentDistributionStatus distributionStatus = distributionList.get(0); + assertEquals("COMPONENT_DONE_OK", distributionStatus.getComponentDistributionStatus()); + assertEquals("SO", distributionStatus.getComponentName()); + + + } catch (Exception e) { + logger.info(e.getMessage(), e); + fail(e.getMessage()); + } + } + + /** * Test to check RequestId is being set using the DistributionID. */ @Test @@ -179,8 +323,8 @@ public class ASDCControllerITTest extends BaseTest { private ArtifactInfoImpl constructPnfServiceArtifact() { ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); artifactInfo.setArtifactType(ASDCConfiguration.TOSCA_CSAR); - artifactInfo.setArtifactURL("/download/service-Testservice140-csar.csar"); - artifactInfo.setArtifactName("service-Testservice140-csar.csar"); + artifactInfo.setArtifactURL("/download/service-pnfservice.csar"); + artifactInfo.setArtifactName("service-pnfservice.csar"); artifactInfo.setArtifactVersion("1.0"); artifactInfo.setArtifactUUID(artifactUuid); return artifactInfo; @@ -192,13 +336,13 @@ public class ASDCControllerITTest extends BaseTest { */ private ResourceInfoImpl constructPnfResourceInfo() { ResourceInfoImpl resourceInfo = new ResourceInfoImpl(); - resourceInfo.setResourceInstanceName("Test140PNF"); - resourceInfo.setResourceInvariantUUID("d832a027-75f3-455d-9de4-f02fcdee7e7e"); + resourceInfo.setResourceInstanceName("PNF CDS Test"); + resourceInfo.setResourceInvariantUUID("17d9d183-cee5-4a46-b5c4-6d5203f7d2e8"); resourceInfo.setResoucreType("PNF"); resourceInfo.setCategory("Application L4+"); - resourceInfo.setSubcategory("Call Control"); - resourceInfo.setResourceUUID("9c54e269-122b-4e8a-8b2a-6eac849b441a"); - resourceInfo.setResourceCustomizationUUID("428a3d73-f962-4cc2-ba62-2483c45d6b12"); + resourceInfo.setSubcategory("Firewall"); + resourceInfo.setResourceUUID("aa5d0562-80e7-43e9-af74-3085e57ab09f"); + resourceInfo.setResourceCustomizationUUID("9f01263a-eaf7-4d98-a37b-3785f751903e"); resourceInfo.setResourceVersion("1.0"); return resourceInfo; } @@ -207,7 +351,6 @@ public class ASDCControllerITTest extends BaseTest { * Testing with the service-Svc140-VF-csar.csar. */ @Test - @Ignore public void treatNotification_ValidVnfResource_ExpectedOutput() { /** @@ -244,11 +387,11 @@ public class ASDCControllerITTest extends BaseTest { ToscaCsar toscaCsar = toscaCsarRepository.findById(artifactUuid) .orElseThrow(() -> new EntityNotFoundException("Tosca csar: " + artifactUuid + " not found")); assertEquals("tosca csar UUID", artifactUuid, toscaCsar.getArtifactUUID()); - assertEquals("tosca csar name", "service-Svc140-VF-csar.csar", toscaCsar.getName()); + assertEquals("tosca csar name", "service-vnfservice.csar", toscaCsar.getName()); assertEquals("tosca csar version", "1.0", toscaCsar.getVersion()); assertNull("tosca csar descrption", toscaCsar.getDescription()); assertEquals("tosca csar checksum", "MANUAL_RECORD", toscaCsar.getArtifactChecksum()); - assertEquals("toscar csar URL", "/download/service-Svc140-VF-csar.csar", toscaCsar.getUrl()); + assertEquals("toscar csar URL", "/download/service-vnfservice.csar", toscaCsar.getUrl()); /** * Check the service entity, it should be the same as global metadata information in @@ -268,6 +411,9 @@ public class ASDCControllerITTest extends BaseTest { assertEquals("service category", "Network Service", service.getCategory()); assertNull("workload context", service.getWorkloadContext()); assertEquals("resource order", "TestVF140", service.getResourceOrder()); + assertEquals("CDS blueprint name", "BP140", service.getBlueprintName()); + assertEquals("CDS blueprint version", "v1.4.0", service.getBlueprintVersion()); + assertEquals("controller actor", "SO-REF-DATA", service.getControllerActor()); /** * Check VNF resource, it should be the same as metadata in the topology template in @@ -304,11 +450,12 @@ public class ASDCControllerITTest extends BaseTest { assertNull("NF naming code", vnfCustomization.getNfNamingCode()); assertEquals("VNF resource model UUID", vnfResourceKey, vnfCustomization.getVnfResources().getModelUUID()); assertEquals("Multi stage design", "false", vnfCustomization.getMultiStageDesign()); - assertNull("resource input", vnfCustomization.getResourceInput()); - assertEquals("cds blueprint name(sdnc_model_name property)", vnfCustomization.getBlueprintName(), - vnfCustomization.getBlueprintName()); - assertEquals("cds blueprint version(sdnc_model_version property)", vnfCustomization.getBlueprintVersion(), + assertNotNull("resource input", vnfCustomization.getResourceInput()); + assertEquals("cds blueprint name(sdnc_model_name property)", "BP140", vnfCustomization.getBlueprintName()); + assertEquals("cds blueprint version(sdnc_model_version property)", "v1.4.0", vnfCustomization.getBlueprintVersion()); + assertEquals("controller actor", "SO-REF-DATA", vnfCustomization.getControllerActor()); + /** * Check the vnf resource customization with service mapping */ @@ -335,8 +482,8 @@ public class ASDCControllerITTest extends BaseTest { private ArtifactInfoImpl constructVnfServiceArtifact() { ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); artifactInfo.setArtifactType(ASDCConfiguration.TOSCA_CSAR); - artifactInfo.setArtifactURL("/download/service-Svc140-VF-csar.csar"); - artifactInfo.setArtifactName("service-Svc140-VF-csar.csar"); + artifactInfo.setArtifactURL("/download/service-vnfservice.csar"); + artifactInfo.setArtifactName("service-vnfservice.csar"); artifactInfo.setArtifactVersion("1.0"); artifactInfo.setArtifactUUID(artifactUuid); return artifactInfo; diff --git a/asdc-controller/src/test/resources/download/service-pnfservice.csar b/asdc-controller/src/test/resources/download/service-pnfservice.csar Binary files differnew file mode 100644 index 0000000000..89d24a18ee --- /dev/null +++ b/asdc-controller/src/test/resources/download/service-pnfservice.csar diff --git a/asdc-controller/src/test/resources/download/service-vnfservice.csar b/asdc-controller/src/test/resources/download/service-vnfservice.csar Binary files differnew file mode 100644 index 0000000000..25d2ebd6c6 --- /dev/null +++ b/asdc-controller/src/test/resources/download/service-vnfservice.csar diff --git a/asdc-controller/src/test/resources/schema.sql b/asdc-controller/src/test/resources/schema.sql index d138d9e236..0821ebc97c 100644 --- a/asdc-controller/src/test/resources/schema.sql +++ b/asdc-controller/src/test/resources/schema.sql @@ -738,6 +738,8 @@ CREATE TABLE `orchestration_flow_reference` ( `SEQ_NO` int(11) NOT NULL, `FLOW_NAME` varchar(200) NOT NULL, `FLOW_VERSION` double NOT NULL, + `SCOPE` varchar(200) DEFAULT NULL, + `ACTION` varchar(200) DEFAULT NULL, `NB_REQ_REF_LOOKUP_ID` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UK_orchestration_flow_reference` (`COMPOSITE_ACTION`,`FLOW_NAME`,`SEQ_NO`,`NB_REQ_REF_LOOKUP_ID`), @@ -809,6 +811,10 @@ CREATE TABLE `service` ( `OVERALL_DISTRIBUTION_STATUS` varchar(45), `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, `NAMING_POLICY` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -963,6 +969,7 @@ CREATE TABLE `vf_module_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`ID`), KEY `fk_vf_module_customization__vf_module1_idx` (`VF_MODULE_MODEL_UUID`), KEY `fk_vf_module_customization__heat_env__heat_environment1_idx` (`HEAT_ENVIRONMENT_ARTIFACT_UUID`), @@ -1113,7 +1120,8 @@ CREATE TABLE `vnf_resource_customization` ( `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, `SERVICE_MODEL_UUID` varchar(200) NOT NULL, `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, - `NF_DATA_VALID` tinyint(1) DEFAULT '0', + `NF_DATA_VALID` tinyint(1) DEFAULT '0', + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1195,6 +1203,7 @@ CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy index 7e1280729c..841fe9f50e 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcess.groovy @@ -9,9 +9,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,295 +25,98 @@ package org.onap.so.bpmn.common.scripts import org.onap.so.logger.LoggingAnchor import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.db.request.beans.InfraActiveRequests +import org.onap.so.db.request.client.RequestsDbClient import org.onap.so.logger.ErrorCode import org.onap.so.logger.MessageEnum import org.slf4j.Logger import org.slf4j.LoggerFactory +import org.onap.so.bpmn.core.UrnPropertiesReader; public class CompleteMsoProcess extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( CompleteMsoProcess.class); - - String Prefix="CMSO_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - // Complete MSO Request processing - public initializeProcessVariables(DelegateExecution execution){ - - def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - try { - - /* Initialize all the process request variables in this block */ - execution.setVariable("prefix",Prefix) - execution.setVariable("CMSO_request_id","") - execution.setVariable("CMSO_notification-url","") - execution.setVariable("CMSO_mso-bpel-name","") - execution.setVariable("CMSO_request_action","") - execution.setVariable("CMSO_notification-url-Ok", false) - execution.setVariable("CMSO_request_id-Ok", false) - - //updateRequest Adapter process variables - execution.setVariable("CMSO_updateRequestResponse", "") - execution.setVariable("CMSO_updateRequestResponseCode", "") - execution.setVariable("CMSO_updateFinalNotifyAckStatusFailedPayload", "") - - //Set DB adapter variables here - execution.setVariable("CMSO_updateDBStatusToSuccessPayload", "") - execution.setVariable("CMSO_updateInfraRequestDBPayload", "") - execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", "") - - //Auth variables - execution.setVariable("BasicAuthHeaderValue","") - - //Response variables - execution.setVariable("CompletionHandlerResponse","") - execution.setVariable("CMSO_ErrorResponse", null) - execution.setVariable("CMSO_ResponseCode", "") - - setSuccessIndicator(execution, false) - - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), 'Caught exception in' + - ' ' + method, "BPMN", ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - - } - - public void preProcessRequest (DelegateExecution execution) { - - initializeProcessVariables(execution) - def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' - // logger.trace("Started CompleteMsoProcess preProcessRequest Method "); - logger.trace('Entered ' + method) - - setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled')) - - try { - def xml = execution.getVariable("CompleteMsoProcessRequest") - - logger.debug("CompleteMsoProcess Request: " + xml) - logger.debug("Incoming Request is: "+ xml) - - //mso-bpel-name from the incoming request - def msoBpelName = utils.getNodeText(xml,"mso-bpel-name") - execution.setVariable("CMSO_mso-bpel-name",msoBpelName) - - //Check the incoming request type - //Incoming request can be ACTIVE_REQUESTS (request-information node) or INFRA_ACTIVE_REQUESTS (request-info node) - if (utils.nodeExists(xml, "request-information")) { - execution.setVariable("CMSO_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS - } - - //Check for rehome indicator - def rehomeIndicator = utils.getNodeText(xml,"rehomeDone") - execution.setVariable("rehomeDone", rehomeIndicator) - - //Check notification-url for the incoming request type - //ACTIVE_REQUESTS may have notificationurl node - //INFRA_ACTIVE_REQUESTS notificationurl node does not exist - def notificationurl = "" - if (utils.nodeExists(xml, "notification-url")) { - notificationurl = utils.getNodeText(xml,"notification-url") - if(notificationurl != null && !notificationurl.isEmpty()) { - execution.setVariable("CMSO_notification-url-Ok", true) - execution.setVariable("CMSO_notification-url",notificationurl) - } - } - - //Check request_id for the incoming request type - //For INFRA_ACTIVE_REQUESTS payload request-id IS optional (Not sure why this is option since req id is primary key ... also tried exe through SOAP UI to check if MSO code handles null like auto generated seq not it does not) - //For ACTIVE_REQUESTS payload request-id is NOT optional - def request_id = "" - if (utils.nodeExists(xml, "request-id")) { - execution.setVariable("CMSO_request_id",utils.getNodeText(xml,"request-id")) - } - - - // INFRA_ACTIVE_REQUESTS have "action" element ... mandatory - // ACTIVE_REQUEST have "request-action" ... mandatory - if (utils.nodeExists(xml, "request-action")) { - execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"request-action")) - } else if (utils.nodeExists(xml, "action")) { - execution.setVariable("CMSO_request_action",utils.getNodeText(xml,"action")) - } - - //Check source for the incoming request type - //For INFRA_ACTIVE_REQUESTS payload source IS optional - //For ACTIVE_REQUESTS payload source is NOT optional - def source = "" - if (utils.nodeExists(xml, "source")) { - execution.setVariable("CMSO_source",utils.getNodeText(xml,"source")) - } - - logger.trace("--> " + execution.getVariable("")) - logger.trace("--> " + execution.getVariable("")) - - // set the DHV/Service Instantiation values if specified in the request - execution.setVariable("CMSO_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText(xml, "is-srv-inst-req")))) - logger.trace("--> " + execution.getVariable("")) - execution.setVariable("CMSO_is_json_content", String.valueOf("JSON".equals(utils.getNodeText(xml, "resp-content-type")))) - logger.trace("--> " + execution.getVariable("")) - execution.setVariable("CMSO_service_inst_id", utils.getNodeText(xml, "service-instance-id")) - logger.trace("--> " + execution.getVariable("")) - execution.setVariable("CMSO_start_time", utils.getNodeText(xml, "start-time")) - logger.trace("--> " + execution.getVariable("")) - // this variable is used by the camunda flow to set the Content-Type for the async response - if (execution.getVariable("CMSO_is_srv_inst_req").equals("true") && - execution.getVariable("CMSO_is_json_content").equals("true")) { - execution.setVariable("CMSO_content_type", "application/json") - } else { - execution.setVariable("CMSO_content_type", "text/xml") - } - - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.debug("Exception Occured During PreProcessRequest: " + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public void setUpdateDBstatustoSuccessPayload (DelegateExecution execution){ - - def method = getClass().getSimpleName() + '.setUpdateDBstatustoSuccessPayload(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - - def xml = execution.getVariable("CompleteMsoProcessRequest") - - //Get statusMessage if exists - def statusMessage - if(utils.nodeExists(xml, "status-message")){ - statusMessage = utils.getNodeText(xml, "status-message") - }else{ - statusMessage = "Resource Completed Successfully" - } - - //Get instance Id if exist - String idXml = "" - if(utils.nodeExists(xml, "vnfId")){ - idXml = utils.getNodeXml(xml, "vnfId") - }else if(utils.nodeExists(xml, "networkId")){ - idXml = utils.getNodeXml(xml, "networkId") - }else if(utils.nodeExists(xml, "configurationId")){ - idXml = utils.getNodeXml(xml, "configurationId") - }else if(utils.nodeExists(xml, "serviceInstanceId")){ - idXml = utils.getNodeXml(xml, "serviceInstanceId") - }else if(utils.nodeExists(xml, "vfModuleId")){ - idXml = utils.getNodeXml(xml, "vfModuleId") - }else if(utils.nodeExists(xml, "volumeGroupId")){ - idXml = utils.getNodeXml(xml, "volumeGroupId") - }else{ - idXml = "" - } - idXml = utils.removeXmlPreamble(idXml) - idXml = utils.removeXmlNamespaces(idXml) - logger.debug("Incoming Instance Id Xml: " + idXml) - - String payload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateInfraRequest> - <requestId>${MsoUtils.xmlEscape(execution.getVariable("CMSO_request_id"))}</requestId> - <lastModifiedBy>${MsoUtils.xmlEscape(execution.getVariable("CMSO_mso-bpel-name"))}</lastModifiedBy> - <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> - <requestStatus>COMPLETE</requestStatus> - <progress>100</progress> - ${idXml} - </req:updateInfraRequest> - </soapenv:Body> - </soapenv:Envelope>""" - - execution.setVariable("CMSO_setUpdateDBstatustoSuccessPayload", payload) - logger.debug("Outgoing Update Mso Request Payload is: " + payload) - logger.debug("setUpdateDBstatustoSuccessPayload: " + payload) - - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - logger.trace('Exited ' + method) - } - - public void buildDataError (DelegateExecution execution, String message) { - - def method = getClass().getSimpleName() + '.buildDataError(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - try { - - String msoCompletionResponse = """ - <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> - <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} FAILED</sdncadapterworkflow:out> - </sdncadapterworkflow:MsoCompletionResponse> - """.trim() - - // Format Response - def xmlMsoCompletionResponse = utils.formatXml(msoCompletionResponse) - String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim() - logger.debug("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString) - execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString) - logger.debug("@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompletionHandlerResponse")) - - exceptionUtil.buildAndThrowWorkflowException(execution, 500, message) - - } catch (BpmnError e) { - logger.debug("Rethrowing MSOWorkflowException") - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - - } - - public void postProcessResponse (DelegateExecution execution) { - - def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - // logger.trace("Started CompleteMsoProcess PostProcessRequest Method "); - try { - - String msoCompletionResponse = """ - <sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow="http://ecomp.com/mso/workflow/schema/v1"> - <sdncadapterworkflow:out>BPEL ${execution.getVariable("CMSO_mso-bpel-name")} completed</sdncadapterworkflow:out> - </sdncadapterworkflow:MsoCompletionResponse> - """.trim() - - // Format Response - def xmlMsoCompletionResponse = utils.formatXML(msoCompletionResponse) - String buildMsoCompletionResponseAsString = xmlMsoCompletionResponse.drop(38).trim() - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead - execution.setVariable("WorkflowResponse", buildMsoCompletionResponseAsString) - logger.debug("CompleteMsoProcess Response: " + buildMsoCompletionResponseAsString) - execution.setVariable("CompleteMsoProcessResponse", buildMsoCompletionResponseAsString) - execution.setVariable("CMSO_ResponseCode", "200") - - setSuccessIndicator(execution, true) - - logger.debug("@@ CompleteMsoProcess Response @@ " + "\n" + execution.getVariable("CompleteMsoProcessResponse")) - - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - } - + private static final Logger logger = LoggerFactory.getLogger(CompleteMsoProcess.class); + + String Prefix="CMSO_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest (DelegateExecution execution) { + try { + def xml = execution.getVariable("CompleteMsoProcessRequest") + + logger.debug("CompleteMsoProcess Request: " + xml) + logger.debug("Incoming Request is: "+ xml) + + //mso-bpel-name from the incoming request + def msoBpelName = utils.getNodeText(xml,"mso-bpel-name") + execution.setVariable("CMSO_mso-bpel-name",msoBpelName) + + if (utils.nodeExists(xml, "request-information")) { + throw new BpmnError("500", "FalloutHandler subflow does not support this request type.") + } + + def request_id = "" + if (utils.nodeExists(xml, "request-id")) { + execution.setVariable("CMSO_request_id",utils.getNodeText(xml,"request-id")) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logger.debug("Exception Occured During PreProcessRequest: " + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in preprocess") + } + } + + public void updateInfraRequestDB (DelegateExecution execution){ + try { + + def xml = execution.getVariable("CompleteMsoProcessRequest") + + //Get statusMessage if exists + def statusMessage + if(utils.nodeExists(xml, "status-message")){ + statusMessage = utils.getNodeText(xml, "status-message") + }else{ + statusMessage = "Resource Completed Successfully" + } + + RequestsDbClient dbClient = getDbClient() + + InfraActiveRequests infraRequest = dbClient.getInfraActiveRequests(execution.getVariable("CMSO_request_id"), UrnPropertiesReader.getVariable("mso.adapters.requestDb.auth"), UrnPropertiesReader.getVariable("mso.adapters.requestDb.endpoint")) + if(infraRequest == null){ + infraRequest = new InfraActiveRequests(); + infraRequest.setRequestId(execution.getVariable("CMSO_request_id")) + } + infraRequest.setLastModifiedBy("BPMN") + infraRequest.setStatusMessage(statusMessage) + infraRequest.setRequestStatus("COMPLETED") + infraRequest.setProgress(100) + + if(utils.nodeExists(xml, "vnfId")){ + infraRequest.setVnfId(utils.getNodeText(xml, "vnfId")) + }else if(utils.nodeExists(xml, "networkId")){ + infraRequest.setNetworkId(utils.getNodeText(xml, "networkId")) + }else if(utils.nodeExists(xml, "configurationId")){ + infraRequest.setConfigurationId(utils.getNodeText(xml, "configurationId")) + }else if(utils.nodeExists(xml, "serviceInstanceId")){ + infraRequest.setServiceInstanceId(utils.getNodeText(xml, "serviceInstanceId")) + }else if(utils.nodeExists(xml, "vfModuleId")){ + infraRequest.setVfModuleId(utils.getNodeText(xml, "vfModuleId")) + }else if(utils.nodeExists(xml, "volumeGroupId")){ + infraRequest.setVolumeGroupId(utils.getNodeText(xml, "volumeGroupId")) + + } + + dbClient.updateInfraActiveRequests(infraRequest, UrnPropertiesReader.getVariable("mso.adapters.requestDb.auth"), UrnPropertiesReader.getVariable("mso.adapters.requestDb.endpoint")) + + } catch (Exception e) { + logger.error("Internal error while updating request db", e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in update infra request db") + } + } + + protected RequestsDbClient getDbClient(){ + return new RequestsDbClient() + } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy index ed849755b7..8306f33592 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/FalloutHandler.groovy @@ -9,9 +9,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,376 +24,134 @@ package org.onap.so.bpmn.common.scripts import org.onap.so.logger.LoggingAnchor import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.db.request.beans.InfraActiveRequests +import org.onap.so.db.request.client.RequestsDbClient import org.onap.so.logger.ErrorCode - +import org.onap.so.bpmn.core.UrnPropertiesReader; import java.text.SimpleDateFormat import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.logger.MessageEnum import org.slf4j.Logger import org.slf4j.LoggerFactory public class FalloutHandler extends AbstractServiceTaskProcessor { - private static final Logger logger = LoggerFactory.getLogger( FalloutHandler.class); - - String Prefix="FH_" - ExceptionUtil exceptionUtil = new ExceptionUtil() - - public initializeProcessVariables(DelegateExecution execution){ - def method = getClass().getSimpleName() + '.initializeProcessVariables(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - execution.setVariable("prefix",Prefix) - - //These variables are form the input Message to the BPMN - execution.setVariable("FH_request_id","") - execution.setVariable("FH_request_action","") - execution.setVariable("FH_notification-url","") - execution.setVariable("FH_mso-bpel-name","") - execution.setVariable("FH_ErrorCode", "") - execution.setVariable("FH_ErrorMessage", "") - - execution.setVariable("FH_notification-url-Ok", false) - execution.setVariable("FH_request_id-Ok", false) - - //These variables are for Get Mso Aai Password Adapter - execution.setVariable("FH_deliveryStatus", true) - - //update Response Status to pending ...Adapter variables - execution.setVariable("FH_updateResponseStatusPayload", null) - execution.setVariable("FH_updateResponseStatusResponse", null) - - //update Request Gamma ...Adapter variables - execution.setVariable("FH_updateRequestGammaPayload", "") - execution.setVariable("FH_updateRequestGammaResponse", null) - execution.setVariable("FH_updateRequestGammaResponseCode", null) - - //update Request Infra ...Adapter variables - execution.setVariable("FH_updateRequestInfraPayload", "") - execution.setVariable("FH_updateRequestInfraResponse", null) - execution.setVariable("FH_updateRequestInfraResponseCode", null) - - //assign True to success variable - execution.setVariable("FH_success", true) - - //Set notify status to Failed variable - execution.setVariable("FH_NOTIFY_STATUS", "SUCCESS") - - //Set DB update variable - execution.setVariable("FH_updateRequestPayload", "") - execution.setVariable("FH_updateRequestResponse", null) - execution.setVariable("FH_updateRequestResponseCode", null) - - //Auth variables - execution.setVariable("BasicAuthHeaderValue","") - - //Parameter list - execution.setVariable("FH_parameterList", "") - - //Response variables - execution.setVariable("FalloutHandlerResponse","") - execution.setVariable("FH_ErrorResponse", null) - execution.setVariable("FH_ResponseCode", "") - - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public void preProcessRequest (DelegateExecution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - // Initialize flow variables - initializeProcessVariables(execution) - setSuccessIndicator(execution, false) - - setBasicDBAuthHeader(execution, execution.getVariable('isDebugLogEnabled')) - - try { - def xml = execution.getVariable("FalloutHandlerRequest") - logger.debug(" XML --> " + xml) - logger.debug("FalloutHandler request: " + xml) - - //Check the incoming request type - //Incoming request can be ACTIVE_REQUESTS (request-information node) or INFRA_ACTIVE_REQUESTS (request-info node) - if (utils.nodeExists(xml, "request-information")) { - execution.setVariable("FH_request_id-Ok", true) // Incoming request is for ACTIVE_REQUESTS - } - - //Check notification-url for the incoming request type - //ACTIVE_REQUESTS may have notificationurl node - //INFRA_ACTIVE_REQUESTS notificationurl node does not exist - def notificationurl = "" - if (utils.nodeExists(xml, "notification-url")) { - notificationurl = utils.getNodeText(xml,"notification-url") - if(notificationurl != null && !notificationurl.isEmpty()) { - logger.debug("********** Incoming notification Url is: " + notificationurl); - execution.setVariable("FH_notification-url-Ok", true) - execution.setVariable("FH_notification-url",notificationurl) - } - } - - //Check request_id for the incoming request type - //For INFRA_ACTIVE_REQUESTS payload request-id IS optional (Not sure why this is option since req id is primary key ... also tried exe through SOAP UI to check if MSO code handles null like auto generated seq not it does not) - //For ACTIVE_REQUESTS payload request-id is NOT optional - def request_id = "" - if (utils.nodeExists(xml, "request-id")) { - execution.setVariable("FH_request_id",utils.getNodeText(xml,"request-id")) - } - logger.debug("FH_request_id: " + execution.getVariable("FH_request_id")) - - // INFRA_ACTIVE_REQUESTS have "action" element ... mandatory - // ACTIVE_REQUEST have "request-action" ... mandatory - if (utils.nodeExists(xml, "request-action")) { - execution.setVariable("FH_request_action",utils.getNodeText(xml,"request-action")) - } else if (utils.nodeExists(xml, "action")) { - execution.setVariable("FH_request_action",utils.getNodeText(xml,"action")) - } - - - //Check source for the incoming request type - //For INFRA_ACTIVE_REQUESTS payload source IS optional - //For ACTIVE_REQUESTS payload source is NOT optional - def source = "" - if (utils.nodeExists(xml, "source")) { - execution.setVariable("FH_source",utils.getNodeText(xml,"source")) - } - - //Check if ErrorCode node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above. - def errorCode = "" - if (utils.nodeExists(xml, "ErrorCode")) { - errorCode = utils.getNodeText(xml,"ErrorCode") - if(errorCode != null && !errorCode.isEmpty()) { - execution.setVariable("FH_ErrorCode", errorCode) - } - } - logger.debug("FH_ErrorCode: " + errorCode) - - //Check if ErrorMessage node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above. - def errorMessage = "" - if (utils.nodeExists(xml, "ErrorMessage")) { - errorCode = utils.getNodeText(xml,"ErrorMessage") - if(errorCode != null && !errorCode.isEmpty()) { - errorCode = errorCode - execution.setVariable("FH_ErrorMessage", errorCode) - } - } - - //Check for Parameter List - if (utils.nodeExists(xml, "parameter-list")) { - def parameterList = utils.getNodeXml(xml, "parameter-list", false) - execution.setVariable("FH_parameterList", parameterList) - } - - logger.trace("--> " + execution.getVariable("")) - logger.debug("FH_request_id-OK --> " + execution.getVariable("FH_request_id-Ok")) - - // set the DHV/Service Instantiation values if specified in the request - execution.setVariable("FH_is_srv_inst_req", String.valueOf("true".equals(utils.getNodeText(xml, "is-srv-inst-req")))) - logger.trace("--> " + execution.getVariable("")) - execution.setVariable("FH_is_json_content", String.valueOf("JSON".equals(utils.getNodeText(xml, "resp-content-type")))) - logger.trace("--> " + execution.getVariable("")) - execution.setVariable("FH_service_inst_id", utils.getNodeText(xml, "service-instance-id")) - logger.trace("--> " + execution.getVariable("")) - execution.setVariable("FH_start_time", utils.getNodeText(xml, "start-time")) - logger.trace("--> " + execution.getVariable("")) - // this variable is used by the camunda flow to set the Content-Type for the async response - if (execution.getVariable("FH_is_srv_inst_req").equals("true") && - execution.getVariable("FH_is_json_content").equals("true")) { - execution.setVariable("FH_content_type", "application/json") - } else { - execution.setVariable("FH_content_type", "text/xml") - } - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method) - } - - logger.debug("OUTOF --> Initialize Variables Fallout Handler #########"); - } - - public String updateRequestPayload (DelegateExecution execution){ - def method = getClass().getSimpleName() + '.updateRequestPayload(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - String payload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateRequest> - <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <finalErrorMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</finalErrorMessage> - <finalErrorCode>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorCode"))}</finalErrorCode> - <status>FAILED</status> - <responseStatus>${MsoUtils.xmlEscape(execution.getVariable("FH_NOTIFY_STATUS"))}</responseStatus> - </req:updateRequest> - </soapenv:Body> - </soapenv:Envelope> - """ - - logger.debug("updateRequestPayload: " + payload) - execution.setVariable("FH_updateRequestPayload", payload) - return execution.getVariable("FH_updateRequestPayload") - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public String updateRequestInfraPayload (DelegateExecution execution){ - def method = getClass().getSimpleName() + '.updateRequestInfraPayload(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - String payload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateInfraRequest> - <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <statusMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</statusMessage> - <requestStatus>FAILED</requestStatus> - <progress>100</progress> - </req:updateInfraRequest> - </soapenv:Body> - </soapenv:Envelope> - """ - - execution.setVariable("FH_updateRequestInfraPayload", payload) - logger.debug("updateRequestInfraPayload: " + payload) - return execution.getVariable("FH_updateRequestInfraPayload") - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public String updateRequestGammaPayload (DelegateExecution execution){ - def method = getClass().getSimpleName() + '.updateRequestGammaPayload(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - String payload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="${UrnPropertiesReader.getVariable("mso.default.adapter.namespace", execution)}/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateRequest> - <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <finalErrorMessage>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))}</finalErrorMessage> - <finalErrorCode>${MsoUtils.xmlEscape(execution.getVariable("FH_ErrorCode"))}</finalErrorCode> - <status>FAILED</status> - </req:updateRequest> - </soapenv:Body> - </soapenv:Envelope> - """ - - execution.setVariable("FH_updateRequestGammaPayload", payload) - logger.debug("updateRequestGammaPayload: " + payload) - return execution.getVariable("FH_updateRequestGammaPayload") - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public String updateResponseStatusPayload (DelegateExecution execution){ - def method = getClass().getSimpleName() + '.updateResponseStatusPayload(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - String payload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateResponseStatus> - <requestId>${MsoUtils.xmlEscape(execution.getVariable("FH_request_id"))}</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <responseStatus>SENDING_FINAL_NOTIFY</responseStatus> - </req:updateResponseStatus> - </soapenv:Body> - </soapenv:Envelope> - """ - - execution.setVariable("FH_updateResponseStatusPayload", payload) - logger.debug("updateResponseStatusPayload: " + payload) - return execution.getVariable("FH_updateResponseStatusPayload") - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - public void buildDBWorkflowException(DelegateExecution execution, String responseCodeVariable) { - def method = getClass().getSimpleName() + '.buildDBWorkflowException(' + - 'execution=' + execution.getId() + - ', responseCodeVariable=' + responseCodeVariable + ')' - logger.trace('Entered ' + method) - - try { - def responseCode = execution.getVariable(responseCodeVariable) - // If the HTTP response code was null, it means a connection fault occurred (a java exception) - def errorMessage = responseCode == null ? "Could not connect to DB Adapter" : "DB Adapter returned ${responseCode} response" - def errorCode = responseCode == null ? 7000 : 7020 - // exceptionUtil.buildWorkflowException(execution, errorCode, errorMessage) - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in " + method) - } - } - - /** - * Used to create a workflow response in success and failure cases. - */ - public void postProcessResponse (DelegateExecution execution) { - def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' - logger.trace('Entered ' + method) - - try { - Boolean success = (Boolean) execution.getVariable("FH_success") - String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed"; - - String falloutHandlerResponse = """ + private static final Logger logger = LoggerFactory.getLogger(FalloutHandler.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + + public void preProcessRequest (DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' + logger.trace('Entered ' + method) + + execution.setVariable("FH_success", true) + + try { + def xml = execution.getVariable("FalloutHandlerRequest") + logger.debug("FalloutHandler request: " + xml) + + if (utils.nodeExists(xml, "request-information")) { + throw new BpmnError("500", "FalloutHandler subflow does not support this request type.") + } + + //Check request_id for the incoming request type + //For INFRA_ACTIVE_REQUESTS payload request-id IS optional (Not sure why this is option since req id is primary key ... also tried exe through SOAP UI to check if MSO code handles null like auto generated seq not it does not) + //For ACTIVE_REQUESTS payload request-id is NOT optional + def request_id = "" + if (utils.nodeExists(xml, "request-id")) { + execution.setVariable("FH_request_id",utils.getNodeText(xml,"request-id")) + } + logger.debug("FH_request_id: " + execution.getVariable("FH_request_id")) + + //Check if ErrorCode node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above. + def errorCode = "500" + if (utils.nodeExists(xml, "ErrorCode")) { + if(errorCode != null && !errorCode.isEmpty()) { + errorCode = utils.getNodeText(xml,"ErrorCode") + } + } + execution.setVariable("FH_ErrorCode", errorCode) + + //Check if ErrorMessage node exists. If yes, initialize it from request xml, if no, it will stay with defaulf value already set in initializeProcessVariables() method above. + String errorMessage = "Internal Error occured in MSO, unable to determine error message" + if (utils.nodeExists(xml, "ErrorMessage")) { + if(errorCode != null && !errorCode.isEmpty()) { + errorMessage = utils.getNodeText(xml,"ErrorMessage") + } + } + execution.setVariable("FH_ErrorMessage", errorMessage) + + //Check for Parameter List + if (utils.nodeExists(xml, "parameter-list")) { + def parameterList = utils.getNodeXml(xml, "parameter-list", false) + execution.setVariable("FH_parameterList", parameterList) + } + + + } catch (Exception e) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + 'Caught exception in ' + method, "BPMN", + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + // exceptionUtil.buildWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + + } + + public String updateInfraRequestDB(DelegateExecution execution){ + try { + RequestsDbClient client = getDbClient() + InfraActiveRequests infraRequest = client.getInfraActiveRequests(execution.getVariable("FH_request_id"), UrnPropertiesReader.getVariable("mso.adapters.requestDb.auth"), UrnPropertiesReader.getVariable("mso.adapters.requestDb.endpoint")) + if(infraRequest == null){ + infraRequest = new InfraActiveRequests(); + infraRequest.setRequestId(execution.getVariable("CMSO_request_id")) + } + infraRequest.setLastModifiedBy("BPMN") + infraRequest.setStatusMessage(MsoUtils.xmlEscape(execution.getVariable("FH_ErrorMessage"))) + infraRequest.setRequestStatus("FAILED") + infraRequest.setProgress(100) + client.updateInfraActiveRequests(infraRequest, UrnPropertiesReader.getVariable("mso.adapters.requestDb.auth"), UrnPropertiesReader.getVariable("mso.adapters.requestDb.endpoint")) + } catch (Exception e) { + execution.setVariable("FH_success", false) + logger.error("Exception Occured while updating infra request db", e) + } + } + + /** + * Used to create a workflow response in success and failure cases. + */ + public void postProcessResponse (DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessResponse(' +'execution=' + execution.getId() +')' + logger.trace('Entered ' + method) + + try { + Boolean success = (Boolean) execution.getVariable("FH_success") + String out = success ? "Fallout Handler Succeeded" : "Fallout Handler Failed"; + + String falloutHandlerResponse = """ <workflow:FalloutHandlerResponse xmlns:workflow="http://org.onap/so/workflow/schema/v1"> <workflow:out>${MsoUtils.xmlEscape(out)}</workflow:out> </workflow:FalloutHandlerResponse> """ - falloutHandlerResponse = utils.formatXml(falloutHandlerResponse) - logger.debug("FalloutHandler Response: " + falloutHandlerResponse); + falloutHandlerResponse = utils.formatXml(falloutHandlerResponse) + + execution.setVariable("FalloutHandlerResponse", falloutHandlerResponse) + execution.setVariable("WorkflowResponse", falloutHandlerResponse) + execution.setVariable("FH_ResponseCode", success ? "200" : "500") + setSuccessIndicator(execution, success) - execution.setVariable("FalloutHandlerResponse", falloutHandlerResponse) - execution.setVariable("WorkflowResponse", falloutHandlerResponse) - execution.setVariable("FH_ResponseCode", success ? "200" : "500") - setSuccessIndicator(execution, success) + logger.debug("FalloutHandlerResponse =\n" + falloutHandlerResponse) + } catch (Exception e) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + 'Caught exception in ' + method, "BPMN", + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + } + } - logger.debug("FalloutHandlerResponse =\n" + falloutHandlerResponse) - } catch (Exception e) { - // Do NOT throw WorkflowException! - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - } - } + protected RequestsDbClient getDbClient(){ + return new RequestsDbClient() + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java index ebf722ef74..0bce305f1d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java @@ -144,6 +144,8 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> { private String blueprintName; @JsonProperty("CDS_BLUEPRINT_VERSION") private String blueprintVersion; + @JsonProperty("application-id") + private String applicationId; public String getBlueprintName() { @@ -530,6 +532,15 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> { this.callHoming = callHoming; } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + @Override public boolean equals(final Object other) { if (!(other instanceof GenericVnf)) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java index 1f689e97e3..c1591ad984 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/BuildingBlock.java @@ -39,6 +39,10 @@ public class BuildingBlock implements Serializable { private Boolean isVirtualLink; @JsonProperty("virtual-link-key") private String virtualLinkKey; + @JsonProperty("scope") + private String bpmnScope; + @JsonProperty("action") + private String bpmnAction; public String getBpmnFlowName() { return bpmnFlowName; @@ -79,4 +83,21 @@ public class BuildingBlock implements Serializable { public void setVirtualLinkKey(String virtualLinkKey) { this.virtualLinkKey = virtualLinkKey; } + + public String getBpmnScope() { + return bpmnScope; + } + + public void setBpmnScope(String scope) { + this.bpmnScope = scope; + } + + public String getBpmnAction() { + return bpmnAction; + } + + public void setBpmnAction(String action) { + this.bpmnAction = action; + } + } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java index 8608fee244..30a6e1fe35 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/ResourceKey.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -31,5 +33,6 @@ public enum ResourceKey { NETWORK_COLLECTION_ID, VPN_ID, VPN_BONDING_LINK_ID, - INSTANCE_GROUP_ID; + INSTANCE_GROUP_ID, + PNF } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java index dc07d13acb..e8be2734cc 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/entities/WorkflowResourceIds.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -30,6 +32,7 @@ public class WorkflowResourceIds implements Serializable { */ private static final long serialVersionUID = 8591599114353940105L; private String serviceInstanceId; + private String pnfId; private String vnfId; private String networkId; private String volumeGroupId; @@ -40,10 +43,10 @@ public class WorkflowResourceIds implements Serializable { @Override public String toString() { - return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId).append("vnfId", vnfId) - .append("networkId", networkId).append("volumeGroupId", volumeGroupId).append("vfModuleId", vfModuleId) - .append("networkCollectionId", networkCollectionId).append("configurationId", configurationId) - .toString(); + return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId).append("pnfId", pnfId) + .append("vnfId", vnfId).append("networkId", networkId).append("volumeGroupId", volumeGroupId) + .append("vfModuleId", vfModuleId).append("networkCollectionId", networkCollectionId) + .append("configurationId", configurationId).toString(); } public String getServiceInstanceId() { @@ -54,6 +57,14 @@ public class WorkflowResourceIds implements Serializable { this.serviceInstanceId = serviceInstanceId; } + public String getPnfId() { + return pnfId; + } + + public void setPnfId(String pnfId) { + this.pnfId = pnfId; + } + public String getVnfId() { return vnfId; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java index 632e61b85c..0193469d93 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/RequestContext.java @@ -55,6 +55,8 @@ public class RequestContext implements Serializable { private RequestParameters requestParameters; @JsonProperty("configurationParameters") private List<Map<String, String>> configurationParameters = new ArrayList<>(); + @JsonProperty("application-id") + private String applicationId; public String getServiceURI() { return serviceURI; @@ -143,4 +145,12 @@ public class RequestContext implements Serializable { public void setConfigurationParameters(List<Map<String, String>> configurationParameters) { this.configurationParameters = configurationParameters; } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java index 763f163a2b..6b96bc384a 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetup.java @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2019 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -26,6 +28,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.UUID; import org.camunda.bpm.engine.delegate.DelegateExecution; @@ -33,27 +36,12 @@ import org.camunda.bpm.engine.delegate.JavaDelegate; import org.javatuples.Pair; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.common.DelegateExecutionImpl; -import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; +import org.onap.so.bpmn.servicedecomposition.bbobjects.*; import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; -import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; -import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup; -import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network; import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness; -import org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy; import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity; import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform; import org.onap.so.bpmn.servicedecomposition.bbobjects.Project; -import org.onap.so.bpmn.servicedecomposition.bbobjects.RouteTableReference; -import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; -import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; -import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceSubscription; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Tenant; -import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Vnfc; -import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup; -import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBinding; import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; @@ -62,6 +50,7 @@ import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; import org.onap.so.bpmn.servicedecomposition.generalobjects.OrchestrationContext; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.NoServiceInstanceFoundException; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.ServiceModelNotFoundException; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -88,6 +77,7 @@ import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.Networks; +import org.onap.so.serviceinstancebeans.Pnfs; import org.onap.so.serviceinstancebeans.RelatedInstance; import org.onap.so.serviceinstancebeans.RelatedInstanceList; import org.onap.so.serviceinstancebeans.RequestDetails; @@ -114,8 +104,10 @@ public class BBInputSetup implements JavaDelegate { private static final String VF_MODULE = "VfModule"; private static final String NETWORK = "Network"; private static final String VNF = "Vnf"; + private static final String PNF = "Pnf"; private static final String NETWORK_COLLECTION = "NetworkCollection"; private static final String PREPROV = "PREPROV"; + private static final String CREATEVOLUME = "CreateVolume"; @Autowired private BBInputSetupUtils bbInputSetupUtils; @@ -241,6 +233,7 @@ public class BBInputSetup implements JavaDelegate { lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, workflowResourceIds.getServiceInstanceId()); lookupKeyMap.put(ResourceKey.NETWORK_ID, workflowResourceIds.getNetworkId()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, workflowResourceIds.getVnfId()); + lookupKeyMap.put(ResourceKey.PNF, workflowResourceIds.getPnfId()); lookupKeyMap.put(ResourceKey.VF_MODULE_ID, workflowResourceIds.getVfModuleId()); lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, workflowResourceIds.getVolumeGroupId()); lookupKeyMap.put(ResourceKey.CONFIGURATION_ID, workflowResourceIds.getConfigurationId()); @@ -253,26 +246,46 @@ public class BBInputSetup implements JavaDelegate { String bbName = executeBB.getBuildingBlock().getBpmnFlowName(); String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID); org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = null; + Service service = null; + boolean isReplace = false; if (serviceInstanceId != null) { aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId); + if (aaiServiceInstance != null) { + if (requestAction.equalsIgnoreCase("replaceInstance")) { + RelatedInstanceList[] relatedInstanceList = requestDetails.getRelatedInstanceList(); + if (relatedInstanceList != null) { + for (RelatedInstanceList relatedInstList : relatedInstanceList) { + RelatedInstance relatedInstance = relatedInstList.getRelatedInstance(); + if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) { + service = bbInputSetupUtils.getCatalogServiceByModelUUID( + relatedInstance.getModelInfo().getModelVersionId()); + isReplace = true; + } + } + } + } else { + service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + } + if (service == null) { + String message = String.format( + "Related service instance model not found in MSO CatalogDB: model-version-id=%s", + aaiServiceInstance.getModelVersionId()); + throw new ServiceModelNotFoundException(message); + } + } else { + String message = String.format("Related service instance from AAI not found: service-instance-id=%s", + serviceInstanceId); + throw new NoServiceInstanceFoundException(message); + } } - Service service = null; - if (aaiServiceInstance != null) { - service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); - } - if (aaiServiceInstance != null && service != null) { - ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); - serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); - this.populateObjectsOnAssignAndCreateFlows(executeBB.getRequestId(), requestDetails, service, bbName, - serviceInstance, lookupKeyMap, resourceId, vnfType, executeBB.getBuildingBlock().getKey(), - executeBB.getConfigurationResourceKeys()); - return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, - null); - } else { - logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance); - logger.debug("Related Service Instance Model Info from AAI: {}", service); - throw new Exception("Could not find relevant information for related Service Instance"); - } + + ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); + serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); + this.populateObjectsOnAssignAndCreateFlows(executeBB.getRequestId(), requestDetails, service, bbName, + serviceInstance, lookupKeyMap, resourceId, vnfType, executeBB.getBuildingBlock().getKey(), + executeBB.getConfigurationResourceKeys(), isReplace); + return this.populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); + } protected GeneralBuildingBlock getGBBCM(ExecuteBuildingBlock executeBB, RequestDetails requestDetails, @@ -337,7 +350,7 @@ public class BBInputSetup implements JavaDelegate { protected void populateObjectsOnAssignAndCreateFlows(String requestId, RequestDetails requestDetails, Service service, String bbName, ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, String vnfType, String configurationKey, - ConfigurationResourceKeys configurationResourceKeys) throws Exception { + ConfigurationResourceKeys configurationResourceKeys, boolean isReplace) throws Exception { ModelInfo modelInfo = requestDetails.getModelInfo(); String instanceName = requestDetails.getRequestInfo().getInstanceName(); String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId(); @@ -346,6 +359,10 @@ public class BBInputSetup implements JavaDelegate { org.onap.so.serviceinstancebeans.Platform platform = requestDetails.getPlatform(); org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness = requestDetails.getLineOfBusiness(); + String applicationId = ""; + if (requestDetails.getRequestInfo().getApplicationId() != null) { + applicationId = requestDetails.getRequestInfo().getApplicationId(); + } if (modelType.equals(ModelType.network)) { lookupKeyMap.put(ResourceKey.NETWORK_ID, resourceId); @@ -354,8 +371,10 @@ public class BBInputSetup implements JavaDelegate { } else if (modelType.equals(ModelType.vnf)) { lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, resourceId); this.populateGenericVnf(requestId, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, - serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId); - } else if (modelType.equals(ModelType.volumeGroup)) { + serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, vnfType, null, productFamilyId, + applicationId); + } else if (modelType.equals(ModelType.volumeGroup) || (modelType.equals(ModelType.vfModule) + && (bbName.equalsIgnoreCase(AssignFlows.VOLUME_GROUP.toString()) || bbName.startsWith(CREATEVOLUME)))) { lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, resourceId); this.populateVolumeGroup(requestId, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); @@ -369,7 +388,7 @@ public class BBInputSetup implements JavaDelegate { } else { lookupKeyMap.put(ResourceKey.VF_MODULE_ID, resourceId); this.populateVfModule(requestId, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, - relatedInstanceList, instanceName, null, requestDetails.getCloudConfiguration()); + relatedInstanceList, instanceName, null, requestDetails.getCloudConfiguration(), isReplace); } } else if (modelType.equals(ModelType.instanceGroup)) { lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, resourceId); @@ -501,13 +520,18 @@ public class BBInputSetup implements JavaDelegate { protected void populateVfModule(String requestId, ModelInfo modelInfo, Service service, String bbName, ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, String resourceId, RelatedInstanceList[] relatedInstanceList, String instanceName, List<Map<String, String>> instanceParams, - CloudConfiguration cloudConfiguration) throws Exception { + CloudConfiguration cloudConfiguration, boolean isReplace) throws Exception { + String replaceVnfModelCustomizationUUID = null; String vnfModelCustomizationUUID = null; if (relatedInstanceList != null) { for (RelatedInstanceList relatedInstList : relatedInstanceList) { RelatedInstance relatedInstance = relatedInstList.getRelatedInstance(); if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) { - vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId(); + if (isReplace) { + replaceVnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId(); + } else { + vnfModelCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId(); + } } if (relatedInstance.getModelInfo().getModelType().equals(ModelType.volumeGroup)) { lookupKeyMap.put(ResourceKey.VOLUME_GROUP_ID, relatedInstance.getInstanceId()); @@ -542,12 +566,20 @@ public class BBInputSetup implements JavaDelegate { .getModelCustomizationId(); ModelInfo modelInfoVfModule = new ModelInfo(); modelInfoVfModule.setModelCustomizationId(vfModuleCustId); - mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, service, vnfModelCustomizationUUID); + if (isReplace) { + mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, service, replaceVnfModelCustomizationUUID); + } else { + mapCatalogVfModule(vfModuleTemp, modelInfoVfModule, service, vnfModelCustomizationUUID); + } } if (vfModule == null && bbName.equalsIgnoreCase(AssignFlows.VF_MODULE.toString())) { vfModule = createVfModule(lookupKeyMap, resourceId, instanceName, instanceParams); vnf.getVfModules().add(vfModule); - mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID); + if (isReplace) { + mapCatalogVfModule(vfModule, modelInfo, service, replaceVnfModelCustomizationUUID); + } else { + mapCatalogVfModule(vfModule, modelInfo, service, vnfModelCustomizationUUID); + } } if (vfModule != null) { updateInstanceName(requestId, ModelType.vfModule, vfModule.getVfModuleName()); @@ -566,6 +598,7 @@ public class BBInputSetup implements JavaDelegate { bbInputSetupUtils.getAAIVolumeGroup(cloudOwner, cloudRegionId, volumeGroup.getVolumeGroupId()) .getModelCustomizationId(); if (modelInfo.getModelCustomizationId().equalsIgnoreCase(volumeGroupCustId)) { + logger.debug("Found volume group for vfModule: " + volumeGroup.getVolumeGroupId()); return Optional.of(volumeGroup.getVolumeGroupId()); } } @@ -720,7 +753,7 @@ public class BBInputSetup implements JavaDelegate { org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, Service service, String bbName, ServiceInstance serviceInstance, Map<ResourceKey, String> lookupKeyMap, RelatedInstanceList[] relatedInstanceList, String resourceId, String vnfType, - List<Map<String, String>> instanceParams, String productFamilyId) { + List<Map<String, String>> instanceParams, String productFamilyId, String applicationId) { GenericVnf vnf = null; ModelInfo instanceGroupModelInfo = null; String instanceGroupId = null; @@ -749,7 +782,7 @@ public class BBInputSetup implements JavaDelegate { } if (vnf == null && bbName.equalsIgnoreCase(AssignFlows.VNF.toString())) { vnf = createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, resourceId, generatedVnfType, - instanceParams, productFamilyId); + instanceParams, productFamilyId, applicationId); serviceInstance.getVnfs().add(vnf); mapVnfcCollectionInstanceGroup(vnf, modelInfo, service); } @@ -764,6 +797,13 @@ public class BBInputSetup implements JavaDelegate { } } + private void populatePnf(Pnfs pnf, String pnfId, ServiceInstance serviceInstance) { + Pnf genericPnf = new Pnf(); + genericPnf.setPnfId(pnfId); + genericPnf.setPnfName(pnf.getInstanceName()); + serviceInstance.getPnfs().add(genericPnf); + } + protected boolean instanceGroupInList(GenericVnf vnf, String instanceGroupId) { for (InstanceGroup instanceGroup : vnf.getInstanceGroups()) { if (instanceGroup.getId() != null && instanceGroup.getId().equalsIgnoreCase(instanceGroupId)) { @@ -803,7 +843,7 @@ public class BBInputSetup implements JavaDelegate { protected GenericVnf createGenericVnf(Map<ResourceKey, String> lookupKeyMap, String instanceName, org.onap.so.serviceinstancebeans.Platform platform, org.onap.so.serviceinstancebeans.LineOfBusiness lineOfBusiness, String vnfId, String vnfType, - List<Map<String, String>> instanceParams, String productFamilyId) { + List<Map<String, String>> instanceParams, String productFamilyId, String applicationId) { lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId); GenericVnf genericVnf = new GenericVnf(); genericVnf.setVnfId(vnfId); @@ -812,6 +852,7 @@ public class BBInputSetup implements JavaDelegate { genericVnf.setVnfType(vnfType); genericVnf.setProvStatus(PREPROV); genericVnf.setServiceId(productFamilyId); + genericVnf.setApplicationId(applicationId); if (platform != null) { genericVnf.setPlatform(this.mapperLayer.mapRequestPlatform(platform)); } @@ -1251,24 +1292,30 @@ public class BBInputSetup implements JavaDelegate { String serviceInstanceId = lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID); RequestDetails requestDetails = executeBB.getRequestDetails(); GeneralBuildingBlock gBB = null; + Service service = null; if (serviceInstanceId != null) { aaiServiceInstance = bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId); + if (aaiServiceInstance != null) { + service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + if (service == null) { + String message = String.format( + "Related service instance model not found in MSO CatalogDB: model-version-id=%s", + aaiServiceInstance.getModelVersionId()); + throw new ServiceModelNotFoundException(message); + } + } else { + String message = String.format("Related service instance from AAI not found: service-instance-id=%s", + serviceInstanceId); + throw new NoServiceInstanceFoundException(message); + } } - Service service = null; - if (aaiServiceInstance != null) { - service = bbInputSetupUtils.getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); - } - if (aaiServiceInstance != null && service != null) { - ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); - serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); - updateInstanceName(executeBB.getRequestId(), ModelType.service, serviceInstance.getServiceInstanceName()); - gBB = populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); - } else { - logger.debug("Related Service Instance from AAI: {}", aaiServiceInstance); - logger.debug("Related Service Instance Model Info from AAI: {}", service); - throw new Exception("Could not find relevant information for related Service Instance"); - } - ServiceInstance serviceInstance = gBB.getServiceInstance(); + + ServiceInstance serviceInstance = this.getExistingServiceInstance(aaiServiceInstance); + serviceInstance.setModelInfoServiceInstance(this.mapperLayer.mapCatalogServiceIntoServiceInstance(service)); + updateInstanceName(executeBB.getRequestId(), ModelType.service, serviceInstance.getServiceInstanceName()); + gBB = populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); + + serviceInstance = gBB.getServiceInstance(); CloudRegion cloudRegion = null; if (cloudConfiguration == null) { Optional<CloudRegion> cloudRegionOp = cloudInfoFromAAI.getCloudInfoFromAAI(serviceInstance); @@ -1403,9 +1450,15 @@ public class BBInputSetup implements JavaDelegate { this.bbInputSetupUtils.updateInfraActiveRequestVnfId(request, vnfId); } String productFamilyId = requestDetails.getRequestInfo().getProductFamilyId(); + String applicationId = ""; this.populateGenericVnf(executeBB.getRequestId(), vnfs.getModelInfo(), vnfs.getInstanceName(), vnfs.getPlatform(), vnfs.getLineOfBusiness(), service, bbName, serviceInstance, lookupKeyMap, null, - vnfId, vnfType, vnfs.getInstanceParams(), productFamilyId); + vnfId, vnfType, vnfs.getInstanceParams(), productFamilyId, applicationId); + } else if (bbName.contains(PNF)) { + String pnfId = lookupKeyMap.get(ResourceKey.PNF); + resources.getPnfs().stream() + .filter(pnf -> Objects.equals(key, pnf.getModelInfo().getModelCustomizationId())).findFirst() + .ifPresent(pnf -> this.populatePnf(pnf, pnfId, serviceInstance)); } else if (bbName.contains(VF_MODULE) || bbName.contains(VOLUME_GROUP)) { Pair<Vnfs, VfModules> vnfsAndVfModules = getVfModulesAndItsVnfsByKey(key, resources); if (vnfsAndVfModules != null) { @@ -1429,7 +1482,7 @@ public class BBInputSetup implements JavaDelegate { cloudConfig.setCloudOwner(cloudRegion.getCloudOwner()); this.populateVfModule(executeBB.getRequestId(), modelInfo, service, bbName, serviceInstance, lookupKeyMap, vfModuleId, null, vfModules.getInstanceName(), vfModules.getInstanceParams(), - cloudConfig); + cloudConfig, false); } } else if (bbName.contains(NETWORK)) { networks = findNetworksByKey(key, resources); 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 fcac86b251..994abda083 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 @@ -359,7 +359,7 @@ public class BBInputSetupUtils { } public Optional<ServiceInstance> getAAIServiceInstanceByName(String globalCustomerId, String serviceType, - String serviceInstanceName) throws Exception { + String serviceInstanceName) throws MultipleObjectsFoundException { ServiceInstance aaiServiceInstance = null; ServiceInstances aaiServiceInstances = null; aaiServiceInstances = getAAIServiceInstancesByName(globalCustomerId, serviceType, serviceInstanceName); @@ -367,7 +367,10 @@ public class BBInputSetupUtils { if (aaiServiceInstances == null) { return Optional.empty(); } else if (aaiServiceInstances.getServiceInstance().size() > 1) { - throw new Exception("Multiple Service Instances Returned"); + String message = String.format( + "Multiple service instances found for customer-id: %s, service-type: %s and service-instance-name: %s.", + globalCustomerId, serviceType, serviceInstanceName); + throw new MultipleObjectsFoundException(message); } else { aaiServiceInstance = aaiServiceInstances.getServiceInstance().get(0); } @@ -472,7 +475,9 @@ public class BBInputSetupUtils { if (serviceInstances.get().getServiceInstance().isEmpty()) { throw new NoServiceInstanceFoundException("No ServiceInstances Returned"); } else if (serviceInstances.get().getServiceInstance().size() > 1) { - throw new MultipleObjectsFoundException("Multiple ServiceInstances Returned"); + String message = String.format("Mulitple service instances were found for instance-group-id: %s.", + instanceGroupId); + throw new MultipleObjectsFoundException(message); } else { serviceInstance = serviceInstances.get().getServiceInstance().get(0); } @@ -481,7 +486,7 @@ public class BBInputSetupUtils { } public Optional<L3Network> getRelatedNetworkByNameFromServiceInstance(String serviceInstanceId, String networkName) - throws Exception { + throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId); uri.relatedTo(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName); Optional<L3Networks> networks = injectionHelper.getAaiClient().get(L3Networks.class, uri); @@ -491,7 +496,10 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (networks.get().getL3Network().size() > 1) { - throw new Exception("Multiple Networks Returned"); + String message = + String.format("Multiple networks found for service-instance-id: %s and network-name: %s.", + serviceInstanceId, networkName); + throw new MultipleObjectsFoundException(message); } else { network = networks.get().getL3Network().get(0); } @@ -500,7 +508,7 @@ public class BBInputSetupUtils { } public Optional<GenericVnf> getRelatedVnfByNameFromServiceInstance(String serviceInstanceId, String vnfName) - throws Exception { + throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId); uri.relatedTo(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName); Optional<GenericVnfs> vnfs = injectionHelper.getAaiClient().get(GenericVnfs.class, uri); @@ -510,7 +518,9 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (vnfs.get().getGenericVnf().size() > 1) { - throw new Exception("Multiple Vnfs Returned"); + String message = String.format("Multiple vnfs found for service-instance-id: %s and vnf-name: %s.", + serviceInstanceId, vnfName); + throw new MultipleObjectsFoundException(message); } else { vnf = vnfs.get().getGenericVnf().get(0); } @@ -519,7 +529,7 @@ public class BBInputSetupUtils { } public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVnf(String vnfId, String volumeGroupName) - throws Exception { + throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId); uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName); Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri); @@ -529,7 +539,9 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (volumeGroups.get().getVolumeGroup().size() > 1) { - throw new Exception("Multiple VolumeGroups Returned"); + String message = String.format("Multiple volume-groups found for vnf-id: %s and volume-group-name: %s.", + vnfId, volumeGroupName); + throw new MultipleObjectsFoundException(message); } else { volumeGroup = volumeGroups.get().getVolumeGroup().get(0); } @@ -538,7 +550,7 @@ public class BBInputSetupUtils { } public Optional<VolumeGroup> getRelatedVolumeGroupByNameFromVfModule(String vnfId, String vfModuleId, - String volumeGroupName) throws Exception { + String volumeGroupName) throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP).queryParam("volume-group-name", volumeGroupName); Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri); @@ -548,6 +560,27 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (volumeGroups.get().getVolumeGroup().size() > 1) { + String message = String.format( + "Multiple voulme-groups found for vnf-id: %s, vf-module-id: %s and volume-group-name: %s.", + vnfId, vfModuleId, volumeGroupName); + throw new MultipleObjectsFoundException(message); + } else { + volumeGroup = volumeGroups.get().getVolumeGroup().get(0); + } + return Optional.of(volumeGroup); + } + } + + public Optional<VolumeGroup> getRelatedVolumeGroupFromVfModule(String vnfId, String vfModuleId) throws Exception { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId); + uri.relatedTo(AAIObjectPlurals.VOLUME_GROUP); + Optional<VolumeGroups> volumeGroups = injectionHelper.getAaiClient().get(VolumeGroups.class, uri); + VolumeGroup volumeGroup = null; + if (!volumeGroups.isPresent()) { + logger.debug("VfModule does not have a volume group attached"); + return Optional.empty(); + } else { + if (volumeGroups.get().getVolumeGroup().size() > 1) { throw new Exception("Multiple VolumeGroups Returned"); } else { volumeGroup = volumeGroups.get().getVolumeGroup().get(0); @@ -587,6 +620,24 @@ public class BBInputSetupUtils { return aaiRC.exists(l3networkUri); } + public boolean existsAAIVfModuleGloballyByName(String vfModuleName) { + AAIResourceUri vfModuleUri = + AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE).queryParam("vf-module-name", vfModuleName); + return injectionHelper.getAaiClient().exists(vfModuleUri); + } + + public boolean existsAAIConfigurationGloballyByName(String configurationName) { + AAIResourceUri configUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", configurationName); + return injectionHelper.getAaiClient().exists(configUri); + } + + public boolean existsAAIVolumeGroupGloballyByName(String volumeGroupName) { + AAIResourceUri volumeGroupUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", volumeGroupName); + return injectionHelper.getAaiClient().exists(volumeGroupUri); + } + public GenericVnfs getAAIVnfsGloballyByName(String vnfName) { return injectionHelper.getAaiClient() @@ -599,7 +650,7 @@ public class BBInputSetupUtils { } public Optional<Configuration> getRelatedConfigurationByNameFromServiceInstance(String serviceInstanceId, - String configurationName) throws Exception { + String configurationName) throws MultipleObjectsFoundException { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId); uri.relatedTo(AAIObjectPlurals.CONFIGURATION).queryParam("configuration-name", configurationName); Optional<Configurations> configurations = injectionHelper.getAaiClient().get(Configurations.class, uri); @@ -609,7 +660,10 @@ public class BBInputSetupUtils { return Optional.empty(); } else { if (configurations.get().getConfiguration().size() > 1) { - throw new Exception("Multiple Configurations Returned"); + String message = String.format( + "Multiple configurations found for service-instance-d: %s and configuration-name: %s.", + serviceInstanceId, configurationName); + throw new MultipleObjectsFoundException(message); } else { configuration = configurations.get().getConfiguration().get(0); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java index aa71ee540f..bb70853bbb 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java @@ -59,6 +59,10 @@ public class ExtractPojosForBB { serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getVnfs(), value); break; + case PNF: + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + result = lookupObjectInList(serviceInstance.getPnfs(), value); + break; case NETWORK_ID: serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getNetworks(), value); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundException.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundException.java new file mode 100644 index 0000000000..b9daad6626 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundException.java @@ -0,0 +1,15 @@ +package org.onap.so.bpmn.servicedecomposition.tasks.exceptions; + +public class ServiceModelNotFoundException extends Exception { + + private static final long serialVersionUID = -5551887892983898061L; + + public ServiceModelNotFoundException() { + super(); + } + + public ServiceModelNotFoundException(String message) { + super(message); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn index 63c867f3c7..72bed98a5f 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/CompleteMsoProcess.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_EsMs0HcuEeW2U_kkOHX1ZQ" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.7.1" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> +<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_EsMs0HcuEeW2U_kkOHX1ZQ" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <bpmn2:process id="CompleteMsoProcess" name="CompleteMsoProcess" isExecutable="true"> <bpmn2:scriptTask id="preProcessRequest" name="Pre-Process Request" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_18</bpmn2:incoming> @@ -10,8 +10,8 @@ preProcessRequestData.preProcessRequest(execution) ]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_2" name="" sourceRef="preProcessRequest" targetRef="ExclusiveGateway_1r258d4" /> - <bpmn2:startEvent id="StartEvent_1" name="Start With message"> + <bpmn2:sequenceFlow id="SequenceFlow_2" name="" sourceRef="preProcessRequest" targetRef="ScriptTask_3" /> + <bpmn2:startEvent id="StartEvent_1"> <bpmn2:outgoing>SequenceFlow_18</bpmn2:outgoing> <bpmn2:messageEventDefinition id="MessageEventDefinition_1" messageRef="Message_2" /> </bpmn2:startEvent> @@ -34,136 +34,18 @@ preProcessRequestData.preProcessRequest(execution) </bpmn2:startEvent> <bpmn2:sequenceFlow id="SequenceFlow_1i1h3il" sourceRef="startEventExceptionCompleteMSO" targetRef="endEventExceptionCompleteMSO" /> </bpmn2:subProcess> - <bpmn2:endEvent id="EndEvent_4"> - <bpmn2:incoming>SequenceFlow_9</bpmn2:incoming> - <bpmn2:errorEventDefinition id="ErrorEventDefinition_5" errorRef="Error_3" /> - </bpmn2:endEvent> - <bpmn2:scriptTask id="ScriptTask_3" name="Prepare Infra Update DB Request" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_127i45q</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_10</bpmn2:outgoing> + <bpmn2:scriptTask id="ScriptTask_3" name=" MSO Update (infra active req) " scriptFormat="groovy"> + <bpmn2:incoming>SequenceFlow_2</bpmn2:incoming> + <bpmn2:outgoing>SequenceFlow_1oes9qv</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* def completeMsoProcess = new CompleteMsoProcess() -completeMsoProcess.setUpdateDBstatustoSuccessPayload(execution)]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_10" name="" sourceRef="ScriptTask_3" targetRef="updateInfraRequest" /> - <bpmn2:serviceTask id="updateInfraRequest" name="Update Infra DB status to SUCCESS"> - <bpmn2:extensionElements> - <camunda:connector> - <camunda:inputOutput> - <camunda:inputParameter name="url"><![CDATA[${UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)}]]></camunda:inputParameter> - <camunda:inputParameter name="payload"><![CDATA[${execution.getVariable("CMSO_setUpdateDBstatustoSuccessPayload")}]]></camunda:inputParameter> - <camunda:inputParameter name="headers"> - <camunda:map> - <camunda:entry key="content-type">application/soap+xml</camunda:entry> - <camunda:entry key="Authorization">#{BasicAuthHeaderValueDB}</camunda:entry> - <camunda:entry key="X-ONAP-RequestID">#{CMSO_request_id}</camunda:entry> - </camunda:map> - </camunda:inputParameter> - <camunda:inputParameter name="method">POST</camunda:inputParameter> - <camunda:outputParameter name="CMSO_updateRequestResponse"><![CDATA[${statusCode == null || statusCode == 204 ? "" : response}]]></camunda:outputParameter> - <camunda:outputParameter name="CMSO_updateRequestResponseCode">${statusCode}</camunda:outputParameter> - </camunda:inputOutput> - <camunda:connectorId>soap-http-connector</camunda:connectorId> - </camunda:connector> - </bpmn2:extensionElements> - <bpmn2:incoming>SequenceFlow_10</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_6</bpmn2:outgoing> - </bpmn2:serviceTask> - <bpmn2:sequenceFlow id="SequenceFlow_6" name="" sourceRef="updateInfraRequest" targetRef="ExclusiveGateway_7" /> - <bpmn2:scriptTask id="BuildErrorMessage" name="Build Error Message" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_1</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_0mipf25</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_9</bpmn2:outgoing> - <bpmn2:script><![CDATA[//println "INSIDE --> Build Error Message @@@@" -//println "CMSO_updateRequestResponse IS --> " + execution.getVariable("CMSO_updateRequestResponse") -import org.onap.so.bpmn.common.scripts.* -def buildDataErrorMessage = new CompleteMsoProcess() -buildDataErrorMessage.buildDataError(execution, "Complete MSO -- Update DB status to SUCCESS -- Failed")]]></bpmn2:script> +completeMsoProcess.updateInfraRequestDB(execution)]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_9" name="" sourceRef="BuildErrorMessage" targetRef="EndEvent_4" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_7" default="SequenceFlow_1"> - <bpmn2:incoming>SequenceFlow_6</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_1</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_03z8rch</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_1" name="" sourceRef="ExclusiveGateway_7" targetRef="BuildErrorMessage" /> - <bpmn2:boundaryEvent id="BoundaryEvent_7" name="" attachedToRef="updateInfraRequest"> - <bpmn2:outgoing>SequenceFlow_0mipf25</bpmn2:outgoing> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_84" errorRef="Error_1" camunda:errorCodeVariable="gJavaErrorCode" camunda:errorMessageVariable="gJavaErrorMessage" /> - </bpmn2:boundaryEvent> <bpmn2:endEvent id="EndEvent_1"> - <bpmn2:incoming>SequenceFlow_1pzb94j</bpmn2:incoming> + <bpmn2:incoming>SequenceFlow_1oes9qv</bpmn2:incoming> <bpmn2:terminateEventDefinition id="_TerminateEventDefinition_2" /> </bpmn2:endEvent> - <bpmn2:sequenceFlow id="SequenceFlow_0mipf25" name="Connect Fault" sourceRef="BoundaryEvent_7" targetRef="BuildErrorMessage" /> - <bpmn2:callActivity id="CallActivity_101qf6x" name="Call Notification Service" calledElement="${UrnPropertiesReader.getVariable("mso.workflow.notification.name", execution)}"> - <bpmn2:extensionElements> - <camunda:in source="mso-request-id" target="mso-request-id" /> - <camunda:in source="mso-service-instance-id" target="mso-service-instance-id" /> - <camunda:in variables="all" /> - <camunda:out variables="all" /> - <camunda:in businessKey="#{execution.processBusinessKey}" /> - </bpmn2:extensionElements> - <bpmn2:incoming>SequenceFlow_81</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_13qdn1s</bpmn2:outgoing> - </bpmn2:callActivity> - <bpmn2:sequenceFlow id="SequenceFlow_13qdn1s" sourceRef="CallActivity_101qf6x" targetRef="ParallelGateway_7" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_3" name="Active Request?" default="SequenceFlow_1dptl35"> - <bpmn2:incoming>SequenceFlow_067veaf</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_81</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_1dptl35</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:exclusiveGateway id="ParallelGateway_7"> - <bpmn2:incoming>SequenceFlow_1dptl35</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_13qdn1s</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_1hpvwyt</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_81" name="Yes" sourceRef="ExclusiveGateway_3" targetRef="CallActivity_101qf6x"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("CMSO_notification-url-Ok") ==true || execution.getVariable("CMSO_request_id-Ok") ==true}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_1dptl35" sourceRef="ExclusiveGateway_3" targetRef="ParallelGateway_7" /> - <bpmn2:parallelGateway id="ExclusiveGateway_1r258d4"> - <bpmn2:incoming>SequenceFlow_2</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_067veaf</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_0xe5zck</bpmn2:outgoing> - </bpmn2:parallelGateway> - <bpmn2:parallelGateway id="ExclusiveGateway_019d74x"> - <bpmn2:incoming>SequenceFlow_12he9a1</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_1hpvwyt</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_1g8ig3h</bpmn2:outgoing> - </bpmn2:parallelGateway> - <bpmn2:sequenceFlow id="SequenceFlow_1g8ig3h" sourceRef="ExclusiveGateway_019d74x" targetRef="ScriptTask_0vyk0lo" /> - <bpmn2:sequenceFlow id="SequenceFlow_067veaf" sourceRef="ExclusiveGateway_1r258d4" targetRef="ExclusiveGateway_3" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_08yqzk9" name="Infra Check Check" default="SequenceFlow_1ffkc0n"> - <bpmn2:incoming>SequenceFlow_0xe5zck</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_127i45q</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_1ffkc0n</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_0xe5zck" sourceRef="ExclusiveGateway_1r258d4" targetRef="ExclusiveGateway_08yqzk9" /> - <bpmn2:sequenceFlow id="SequenceFlow_127i45q" sourceRef="ExclusiveGateway_08yqzk9" targetRef="ScriptTask_3"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("CMSO_request_id-Ok") ==false}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:exclusiveGateway id="ExclusiveGateway_1utv1g8"> - <bpmn2:incoming>SequenceFlow_03z8rch</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_1ffkc0n</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_12he9a1</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_03z8rch" sourceRef="ExclusiveGateway_7" targetRef="ExclusiveGateway_1utv1g8"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("CMSO_updateRequestResponseCode")==200}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_1ffkc0n" sourceRef="ExclusiveGateway_08yqzk9" targetRef="ExclusiveGateway_1utv1g8" /> - <bpmn2:sequenceFlow id="SequenceFlow_12he9a1" sourceRef="ExclusiveGateway_1utv1g8" targetRef="ExclusiveGateway_019d74x" /> - <bpmn2:sequenceFlow id="SequenceFlow_1hpvwyt" sourceRef="ParallelGateway_7" targetRef="ExclusiveGateway_019d74x" /> - <bpmn2:scriptTask id="ScriptTask_0vyk0lo" name="Prepare Response" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_1g8ig3h</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_1pzb94j</bpmn2:outgoing> - <bpmn2:script><![CDATA[println "INSIDE --> Complete MSO Process Done SUCCESSFULLY" -import org.onap.so.bpmn.common.scripts.* -def postProcessResponseData = new CompleteMsoProcess() -postProcessResponseData.postProcessResponse(execution) -println "CompleteMsoProcess Response -->" + "\n" + execution.getVariable("CompletionHandlerResponse")]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_1pzb94j" sourceRef="ScriptTask_0vyk0lo" targetRef="EndEvent_1" /> + <bpmn2:sequenceFlow id="SequenceFlow_1oes9qv" sourceRef="ScriptTask_3" targetRef="EndEvent_1" /> </bpmn2:process> <bpmn2:message id="Message_2" name="CompleteMsoProcessRequest" /> <bpmn2:error id="Error_3" name="MSOWorkflowException" errorCode="MSOWorkflowException" /> @@ -171,254 +53,64 @@ println "CompleteMsoProcess Response -->" + "\n" + execution.getVariable("Comple <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="CompleteMsoProcess"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_41" bpmnElement="StartEvent_1"> - <dc:Bounds x="67" y="297" width="36" height="36" /> + <dc:Bounds x="103" y="156" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="94" y="338" width="49" height="25" /> + <dc:Bounds x="131" y="197" width="47" height="24" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_34" bpmnElement="preProcessRequest"> - <dc:Bounds x="167" y="275" width="100" height="80" /> + <dc:Bounds x="293" y="134" width="100" height="80" /> </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_2" bpmnElement="SequenceFlow_2" sourceElement="_BPMNShape_ScriptTask_34" targetElement="ParallelGateway_1domt5l_di"> - <di:waypoint xsi:type="dc:Point" x="267" y="316" /> - <di:waypoint xsi:type="dc:Point" x="322" y="316" /> + <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_2" bpmnElement="SequenceFlow_2" sourceElement="_BPMNShape_ScriptTask_34" targetElement="_BPMNShape_ScriptTask_88"> + <di:waypoint xsi:type="dc:Point" x="393" y="174" /> + <di:waypoint xsi:type="dc:Point" x="440" y="174" /> <bpmndi:BPMNLabel> - <dc:Bounds x="295" y="301" width="0" height="0" /> + <dc:Bounds x="371.5" y="159" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_20" bpmnElement="SequenceFlow_18" sourceElement="_BPMNShape_StartEvent_41" targetElement="_BPMNShape_ScriptTask_34"> - <di:waypoint xsi:type="dc:Point" x="103" y="315" /> - <di:waypoint xsi:type="dc:Point" x="167" y="315" /> + <di:waypoint xsi:type="dc:Point" x="139" y="174" /> + <di:waypoint xsi:type="dc:Point" x="293" y="174" /> <bpmndi:BPMNLabel> - <dc:Bounds x="135" y="300" width="0" height="0" /> + <dc:Bounds x="171" y="159" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_51" bpmnElement="updateInfraRequest"> - <dc:Bounds x="657" y="451" width="100" height="80" /> - </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_SubProcess_13" bpmnElement="subProcessExceptionCompleteMSO" isExpanded="true"> - <dc:Bounds x="171" y="709" width="427" height="169" /> + <dc:Bounds x="208" y="407" width="427" height="169" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_EndEvent_110" bpmnElement="endEventExceptionCompleteMSO"> - <dc:Bounds x="471" y="776" width="36" height="36" /> + <dc:Bounds x="508" y="474" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="489" y="817" width="0" height="0" /> + <dc:Bounds x="481" y="515" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_51" bpmnElement="startEventExceptionCompleteMSO"> - <dc:Bounds x="219" y="776" width="36" height="36" /> + <dc:Bounds x="256" y="474" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="237" y="817" width="0" height="0" /> + <dc:Bounds x="229" y="515" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_63" bpmnElement="ExclusiveGateway_7" isMarkerVisible="true"> - <dc:Bounds x="816" y="465" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="841" y="520" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_6" bpmnElement="SequenceFlow_6" sourceElement="_BPMNShape_ScriptTask_51" targetElement="_BPMNShape_ExclusiveGateway_63"> - <di:waypoint xsi:type="dc:Point" x="757" y="491" /> - <di:waypoint xsi:type="dc:Point" x="816" y="490" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="942" y="534" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_EndEvent_111" bpmnElement="EndEvent_4"> - <dc:Bounds x="953" y="578" width="36" height="36" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="971" y="619" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_76" bpmnElement="BuildErrorMessage"> - <dc:Bounds x="792" y="556" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_1" bpmnElement="SequenceFlow_1" sourceElement="_BPMNShape_ExclusiveGateway_63" targetElement="_BPMNShape_ScriptTask_76"> - <di:waypoint xsi:type="dc:Point" x="841" y="515" /> - <di:waypoint xsi:type="dc:Point" x="842" y="556" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="886" y="342" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_9" bpmnElement="SequenceFlow_9" sourceElement="_BPMNShape_ScriptTask_76" targetElement="_BPMNShape_EndEvent_111"> - <di:waypoint xsi:type="dc:Point" x="892" y="596" /> - <di:waypoint xsi:type="dc:Point" x="953" y="596" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="923" y="596" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_EndEvent_128" bpmnElement="EndEvent_1"> - <dc:Bounds x="1270" y="297" width="36" height="36" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1288" y="338" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_BoundaryEvent_29" bpmnElement="BoundaryEvent_7"> - <dc:Bounds x="686" y="513" width="36" height="36" /> + <dc:Bounds x="699" y="156" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="979" y="395" width="0" height="0" /> + <dc:Bounds x="672" y="197" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_88" bpmnElement="ScriptTask_3"> - <dc:Bounds x="506" y="451" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_11" bpmnElement="SequenceFlow_10" sourceElement="_BPMNShape_ScriptTask_88" targetElement="_BPMNShape_ScriptTask_51"> - <di:waypoint xsi:type="dc:Point" x="606" y="491" /> - <di:waypoint xsi:type="dc:Point" x="657" y="491" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="626" y="515" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_0mipf25_di" bpmnElement="SequenceFlow_0mipf25"> - <di:waypoint xsi:type="dc:Point" x="704" y="549" /> - <di:waypoint xsi:type="dc:Point" x="704" y="596" /> - <di:waypoint xsi:type="dc:Point" x="792" y="596" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="623" y="563" width="68" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="CallActivity_101qf6x_di" bpmnElement="CallActivity_101qf6x"> - <dc:Bounds x="633" y="186" width="100" height="80" /> + <dc:Bounds x="440" y="134" width="100" height="80" /> </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_13qdn1s_di" bpmnElement="SequenceFlow_13qdn1s"> - <di:waypoint xsi:type="dc:Point" x="733" y="226" /> - <di:waypoint xsi:type="dc:Point" x="888" y="226" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="811" y="211" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="SequenceFlow_1i1h3il_di" bpmnElement="SequenceFlow_1i1h3il"> - <di:waypoint xsi:type="dc:Point" x="255" y="794" /> - <di:waypoint xsi:type="dc:Point" x="471" y="794" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="363" y="779" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_60" bpmnElement="ExclusiveGateway_3" isMarkerVisible="true"> - <dc:Bounds x="394" y="201" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="326" y="196" width="80" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ParallelGateway_9" bpmnElement="ParallelGateway_7" isMarkerVisible="true"> - <dc:Bounds x="888" y="201" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="913" y="256" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_82" bpmnElement="SequenceFlow_81"> - <di:waypoint xsi:type="dc:Point" x="444" y="226" /> - <di:waypoint xsi:type="dc:Point" x="633" y="226" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="552" y="234" width="18" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_1dptl35_di" bpmnElement="SequenceFlow_1dptl35"> - <di:waypoint xsi:type="dc:Point" x="419" y="251" /> - <di:waypoint xsi:type="dc:Point" x="419" y="333" /> - <di:waypoint xsi:type="dc:Point" x="913" y="333" /> - <di:waypoint xsi:type="dc:Point" x="913" y="251" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="448" y="273" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="ParallelGateway_1domt5l_di" bpmnElement="ExclusiveGateway_1r258d4"> - <dc:Bounds x="322" y="291" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="347" y="341" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="ParallelGateway_04tefv6_di" bpmnElement="ExclusiveGateway_019d74x"> - <dc:Bounds x="999" y="290" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1024" y="340" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_1g8ig3h_di" bpmnElement="SequenceFlow_1g8ig3h"> - <di:waypoint xsi:type="dc:Point" x="1049" y="315" /> - <di:waypoint xsi:type="dc:Point" x="1104" y="315" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1077" y="300" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_067veaf_di" bpmnElement="SequenceFlow_067veaf"> - <di:waypoint xsi:type="dc:Point" x="347" y="291" /> - <di:waypoint xsi:type="dc:Point" x="347" y="226" /> - <di:waypoint xsi:type="dc:Point" x="394" y="226" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="362" y="258.5" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="ExclusiveGateway_08yqzk9_di" bpmnElement="ExclusiveGateway_08yqzk9" isMarkerVisible="true"> - <dc:Bounds x="394" y="466" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="390" y="516" width="57" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_0xe5zck_di" bpmnElement="SequenceFlow_0xe5zck"> - <di:waypoint xsi:type="dc:Point" x="347" y="341" /> - <di:waypoint xsi:type="dc:Point" x="347" y="491" /> - <di:waypoint xsi:type="dc:Point" x="394" y="491" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="362" y="416" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_127i45q_di" bpmnElement="SequenceFlow_127i45q"> - <di:waypoint xsi:type="dc:Point" x="444" y="491" /> - <di:waypoint xsi:type="dc:Point" x="473" y="491" /> - <di:waypoint xsi:type="dc:Point" x="473" y="491" /> - <di:waypoint xsi:type="dc:Point" x="506" y="491" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="488" y="491" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="ExclusiveGateway_1utv1g8_di" bpmnElement="ExclusiveGateway_1utv1g8" isMarkerVisible="true"> - <dc:Bounds x="999" y="391" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1024" y="441" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_03z8rch_di" bpmnElement="SequenceFlow_03z8rch"> - <di:waypoint xsi:type="dc:Point" x="866" y="490" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="490" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="441" /> + <di:waypoint xsi:type="dc:Point" x="292" y="492" /> + <di:waypoint xsi:type="dc:Point" x="508" y="492" /> <bpmndi:BPMNLabel> - <dc:Bounds x="945" y="475" width="0" height="0" /> + <dc:Bounds x="355" y="477" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_1ffkc0n_di" bpmnElement="SequenceFlow_1ffkc0n"> - <di:waypoint xsi:type="dc:Point" x="419" y="466" /> - <di:waypoint xsi:type="dc:Point" x="419" y="416" /> - <di:waypoint xsi:type="dc:Point" x="999" y="416" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="434" y="441" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_12he9a1_di" bpmnElement="SequenceFlow_12he9a1"> - <di:waypoint xsi:type="dc:Point" x="1024" y="391" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="367" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="367" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="340" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1039" y="367" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_1hpvwyt_di" bpmnElement="SequenceFlow_1hpvwyt"> - <di:waypoint xsi:type="dc:Point" x="938" y="226" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="226" /> - <di:waypoint xsi:type="dc:Point" x="1024" y="290" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="981" y="211" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="ScriptTask_0vyk0lo_di" bpmnElement="ScriptTask_0vyk0lo"> - <dc:Bounds x="1104" y="275" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_1pzb94j_di" bpmnElement="SequenceFlow_1pzb94j"> - <di:waypoint xsi:type="dc:Point" x="1204" y="315" /> - <di:waypoint xsi:type="dc:Point" x="1270" y="315" /> + <bpmndi:BPMNEdge id="SequenceFlow_1oes9qv_di" bpmnElement="SequenceFlow_1oes9qv"> + <di:waypoint xsi:type="dc:Point" x="540" y="174" /> + <di:waypoint xsi:type="dc:Point" x="699" y="174" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1237" y="290" width="0" height="0" /> + <dc:Bounds x="619.5" y="153" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn index 6914e7575f..0c7a8ac063 100644 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/FalloutHandler.bpmn @@ -1,178 +1,37 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="_3SPHsLr9EeWak-hhutJWuQ" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.7.1" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> +<bpmn2:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn2="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" id="_3SPHsLr9EeWak-hhutJWuQ" targetNamespace="http://camunda.org/schema/1.0/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0" xsi:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"> <bpmn2:process id="FalloutHandler" name="Fallout Handler" isExecutable="true"> - <bpmn2:parallelGateway id="ParallelGateway_1"> - <bpmn2:incoming>SequenceFlow_12</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_2</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_24</bpmn2:outgoing> - </bpmn2:parallelGateway> - <bpmn2:sequenceFlow id="SequenceFlow_2" name="" sourceRef="ParallelGateway_1" targetRef="ExclusiveGateway_1" /> - <bpmn2:sequenceFlow id="SequenceFlow_24" name="" sourceRef="ParallelGateway_1" targetRef="ExclusiveGateway_6" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_1" name="Notification URL exists?" default="SequenceFlow_23"> - <bpmn2:incoming>SequenceFlow_2</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_3</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_23</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_3" name="yes" sourceRef="ExclusiveGateway_1" targetRef="Task_0ixuwt5"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("FH_notification-url-Ok") ==true}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_23" name="no" sourceRef="ExclusiveGateway_1" targetRef="ParallelGateway_4" /> <bpmn2:scriptTask id="ScriptTask_8" name="Pre-Process Request" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_10</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_12</bpmn2:outgoing> + <bpmn2:outgoing>SequenceFlow_1kx7ea5</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* def preProcessRequestData = new FalloutHandler() preProcessRequestData.preProcessRequest(execution) ]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_12" name="" sourceRef="ScriptTask_8" targetRef="ParallelGateway_1" /> - <bpmn2:startEvent id="StartEvent_1" name="Start"> + <bpmn2:startEvent id="StartEvent_1"> <bpmn2:outgoing>SequenceFlow_10</bpmn2:outgoing> </bpmn2:startEvent> <bpmn2:sequenceFlow id="SequenceFlow_10" name="" sourceRef="StartEvent_1" targetRef="ScriptTask_8" /> - <bpmn2:parallelGateway id="ParallelGateway_6"> - <bpmn2:incoming>SequenceFlow_37</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_38</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_8</bpmn2:outgoing> - </bpmn2:parallelGateway> - <bpmn2:sequenceFlow id="SequenceFlow_8" name="" sourceRef="ParallelGateway_6" targetRef="ScriptTask_2" /> <bpmn2:scriptTask id="ScriptTask_2" name="Post Process Response" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_8</bpmn2:incoming> + <bpmn2:incoming>SequenceFlow_1u8shdz</bpmn2:incoming> <bpmn2:outgoing>SequenceFlow_9</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* def falloutHandler = new FalloutHandler() falloutHandler.postProcessResponse(execution)]]></bpmn2:script> </bpmn2:scriptTask> <bpmn2:sequenceFlow id="SequenceFlow_9" name="" sourceRef="ScriptTask_2" targetRef="EndEvent_6" /> - <bpmn2:exclusiveGateway id="ParallelGateway_4"> - <bpmn2:incoming>SequenceFlow_23</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_0m7gwor</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_38</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_38" name="" sourceRef="ParallelGateway_4" targetRef="ParallelGateway_6" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_6" default="SequenceFlow_26"> - <bpmn2:incoming>SequenceFlow_24</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_25</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_26</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_25" name="" sourceRef="ExclusiveGateway_6" targetRef="ServiceTask_3"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("FH_request_id-Ok") ==true}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:sequenceFlow id="SequenceFlow_26" name="" sourceRef="ExclusiveGateway_6" targetRef="ServiceTask_2" /> - <bpmn2:serviceTask id="ServiceTask_3" name="Update Request Gamma"> - <bpmn2:extensionElements> - <camunda:connector> - <camunda:inputOutput> - <camunda:inputParameter name="url"><![CDATA[${UrnPropertiesReader.getVariable("mso.adapters.db.att-endpoint", execution)}]]></camunda:inputParameter> - <camunda:inputParameter name="method">POST</camunda:inputParameter> - <camunda:inputParameter name="headers"> - <camunda:map> - <camunda:entry key="content-type">application/soap+xml</camunda:entry> - <camunda:entry key="Authorization">#{BasicAuthHeaderValueDB}</camunda:entry> - <camunda:entry key="X-ONAP-RequestID">#{FH_request_id}</camunda:entry> - </camunda:map> - </camunda:inputParameter> - <camunda:inputParameter name="payload"> - <camunda:script scriptFormat="groovy"><![CDATA[//println"INSIDE --> update Request Gamma" -import org.onap.so.bpmn.common.scripts.* -def updateRequestGamma= new FalloutHandler() -return updateRequestGamma.updateRequestGammaPayload(execution)]]></camunda:script> - </camunda:inputParameter> - <camunda:outputParameter name="FH_updateRequestGammaResponse"><![CDATA[${statusCode == null || statusCode == 204 ? "" : response}]]></camunda:outputParameter> - <camunda:outputParameter name="FH_updateRequestGammaResponseCode">${statusCode}</camunda:outputParameter> - </camunda:inputOutput> - <camunda:connectorId>soap-http-connector</camunda:connectorId> - </camunda:connector> - </bpmn2:extensionElements> - <bpmn2:incoming>SequenceFlow_25</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_29</bpmn2:outgoing> - </bpmn2:serviceTask> - <bpmn2:sequenceFlow id="SequenceFlow_29" name="" sourceRef="ServiceTask_3" targetRef="ExclusiveGateway_7" /> - <bpmn2:boundaryEvent id="BoundaryEvent_2" name="Connect Fault" attachedToRef="ServiceTask_3"> - <bpmn2:outgoing>SequenceFlow_72</bpmn2:outgoing> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_89" errorRef="Error_2" /> - </bpmn2:boundaryEvent> - <bpmn2:exclusiveGateway id="ParallelGateway_5"> - <bpmn2:incoming>SequenceFlow_35</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_36</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_37</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_37" name="" sourceRef="ParallelGateway_5" targetRef="ParallelGateway_6" /> - <bpmn2:endEvent id="EndEvent_6" name="Normal End"> + <bpmn2:endEvent id="EndEvent_6"> <bpmn2:incoming>SequenceFlow_9</bpmn2:incoming> </bpmn2:endEvent> - <bpmn2:sequenceFlow id="SequenceFlow_72" name="" sourceRef="BoundaryEvent_2" targetRef="ScriptTask_6" /> - <bpmn2:scriptTask id="ScriptTask_6" name="Build Workflow Exception" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_72</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_31</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_79</bpmn2:outgoing> + <bpmn2:scriptTask id="ScriptTask_6" name=" MSO Update (infra active req) " scriptFormat="groovy"> + <bpmn2:incoming>SequenceFlow_1kx7ea5</bpmn2:incoming> + <bpmn2:outgoing>SequenceFlow_1u8shdz</bpmn2:outgoing> <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* def falloutHandler = new FalloutHandler() -falloutHandler.buildDBWorkflowException(execution, "FH_updateRequestGammaResponseCode")]]></bpmn2:script> +falloutHandler.updateInfraRequestDB(execution)]]></bpmn2:script> </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_79" name="" sourceRef="ScriptTask_6" targetRef="EndEvent_13" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_7" name="Update Success?" default="SequenceFlow_31"> - <bpmn2:incoming>SequenceFlow_29</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_31</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_35</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_31" name="" sourceRef="ExclusiveGateway_7" targetRef="ScriptTask_6" /> - <bpmn2:sequenceFlow id="SequenceFlow_35" name="" sourceRef="ExclusiveGateway_7" targetRef="ParallelGateway_5"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("FH_updateRequestGammaResponseCode")==200}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:scriptTask id="ScriptTask_7" name="Build Workflow Exception" scriptFormat="groovy"> - <bpmn2:incoming>SequenceFlow_32</bpmn2:incoming> - <bpmn2:incoming>SequenceFlow_80</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_73</bpmn2:outgoing> - <bpmn2:script><![CDATA[import org.onap.so.bpmn.common.scripts.* -def falloutHandler = new FalloutHandler() -falloutHandler.buildDBWorkflowException(execution, "FH_updateRequestInfraResponseCode")]]></bpmn2:script> - </bpmn2:scriptTask> - <bpmn2:sequenceFlow id="SequenceFlow_73" name="" sourceRef="ScriptTask_7" targetRef="EndEvent_14" /> - <bpmn2:serviceTask id="ServiceTask_2" name="Update Request Infra"> - <bpmn2:extensionElements> - <camunda:connector> - <camunda:inputOutput> - <camunda:inputParameter name="url"><![CDATA[${UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)}]]></camunda:inputParameter> - <camunda:inputParameter name="method">POST</camunda:inputParameter> - <camunda:inputParameter name="headers"> - <camunda:map> - <camunda:entry key="content-type">application/soap+xml</camunda:entry> - <camunda:entry key="Authorization">#{BasicAuthHeaderValueDB}</camunda:entry> - <camunda:entry key="X-ONAP-RequestID">#{FH_request_id}</camunda:entry> - </camunda:map> - </camunda:inputParameter> - <camunda:inputParameter name="payload"> - <camunda:script scriptFormat="groovy"><![CDATA[//println"INSIDE --> update Request Infra" -import org.onap.so.bpmn.common.scripts.* -def updateRequestInfra= new FalloutHandler() -return updateRequestInfra.updateRequestInfraPayload(execution)]]></camunda:script> - </camunda:inputParameter> - <camunda:outputParameter name="FH_updateRequestInfraResponse"><![CDATA[${statusCode == null || statusCode == 204 ? "" : response}]]></camunda:outputParameter> - <camunda:outputParameter name="FH_updateRequestInfraResponseCode">${statusCode}</camunda:outputParameter> - </camunda:inputOutput> - <camunda:connectorId>soap-http-connector</camunda:connectorId> - </camunda:connector> - </bpmn2:extensionElements> - <bpmn2:incoming>SequenceFlow_26</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_30</bpmn2:outgoing> - </bpmn2:serviceTask> - <bpmn2:sequenceFlow id="SequenceFlow_30" name="" sourceRef="ServiceTask_2" targetRef="ExclusiveGateway_8" /> - <bpmn2:exclusiveGateway id="ExclusiveGateway_8" name="Update Success?" default="SequenceFlow_32"> - <bpmn2:incoming>SequenceFlow_30</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_32</bpmn2:outgoing> - <bpmn2:outgoing>SequenceFlow_36</bpmn2:outgoing> - </bpmn2:exclusiveGateway> - <bpmn2:sequenceFlow id="SequenceFlow_32" name="" sourceRef="ExclusiveGateway_8" targetRef="ScriptTask_7" /> - <bpmn2:sequenceFlow id="SequenceFlow_36" name="" sourceRef="ExclusiveGateway_8" targetRef="ParallelGateway_5"> - <bpmn2:conditionExpression xsi:type="bpmn2:tFormalExpression"><![CDATA[#{execution.getVariable("FH_updateRequestInfraResponseCode")==200}]]></bpmn2:conditionExpression> - </bpmn2:sequenceFlow> - <bpmn2:boundaryEvent id="BoundaryEvent_3" name="Connect Fault" attachedToRef="ServiceTask_2"> - <bpmn2:outgoing>SequenceFlow_80</bpmn2:outgoing> - <bpmn2:errorEventDefinition id="_ErrorEventDefinition_90" errorRef="Error_2" camunda:errorCodeVariable="gJavaErrorCode" camunda:errorMessageVariable="gJavaErrorMessage" /> - </bpmn2:boundaryEvent> - <bpmn2:sequenceFlow id="SequenceFlow_80" name="" sourceRef="BoundaryEvent_3" targetRef="ScriptTask_7" /> <bpmn2:subProcess id="SubProcess_1" name="Event Handler" triggeredByEvent="true"> <bpmn2:scriptTask id="ScriptTask_4" name="Handle Event" scriptFormat="groovy"> <bpmn2:incoming>SequenceFlow_1ko8ggw</bpmn2:incoming> @@ -200,345 +59,94 @@ execution.setVariable("FH_WorkflowException", wfe)]]></bpmn2:script> <bpmn2:sequenceFlow id="SequenceFlow_1ko8ggw" sourceRef="StartEvent_2" targetRef="ScriptTask_4" /> <bpmn2:sequenceFlow id="SequenceFlow_1pm9r7h" sourceRef="ScriptTask_4" targetRef="EndEvent_2" /> </bpmn2:subProcess> - <bpmn2:endEvent id="EndEvent_14"> - <bpmn2:incoming>SequenceFlow_73</bpmn2:incoming> - <bpmn2:terminateEventDefinition /> - </bpmn2:endEvent> - <bpmn2:endEvent id="EndEvent_13"> - <bpmn2:incoming>SequenceFlow_79</bpmn2:incoming> - <bpmn2:terminateEventDefinition /> - </bpmn2:endEvent> - <bpmn2:sequenceFlow id="SequenceFlow_0m7gwor" sourceRef="Task_0ixuwt5" targetRef="ParallelGateway_4" /> - <bpmn2:callActivity id="Task_0ixuwt5" name="Call Notification Service" calledElement="${UrnPropertiesReader.getVariable("mso.workflow.notification.name", execution)}"> - <bpmn2:extensionElements> - <camunda:in source="mso-request-id" target="mso-request-id" /> - <camunda:in source="mso-service-instance-id" target="mso-service-instance-id" /> - <camunda:in variables="all" /> - <camunda:out variables="all" /> - </bpmn2:extensionElements> - <bpmn2:incoming>SequenceFlow_3</bpmn2:incoming> - <bpmn2:outgoing>SequenceFlow_0m7gwor</bpmn2:outgoing> - </bpmn2:callActivity> + <bpmn2:sequenceFlow id="SequenceFlow_1kx7ea5" sourceRef="ScriptTask_8" targetRef="ScriptTask_6" /> + <bpmn2:sequenceFlow id="SequenceFlow_1u8shdz" sourceRef="ScriptTask_6" targetRef="ScriptTask_2" /> </bpmn2:process> <bpmn2:error id="Error_1" name="MSOWorkflowException" errorCode="MSOWorkflowException" /> <bpmn2:error id="Error_2" name="Java Lang Exception" errorCode="java.lang.Exception" /> <bpmndi:BPMNDiagram id="BPMNDiagram_1"> <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="FalloutHandler"> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_52" bpmnElement="StartEvent_1"> - <dc:Bounds x="139" y="263" width="36" height="36" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="145" y="300" width="23" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ParallelGateway_12" bpmnElement="ParallelGateway_1"> - <dc:Bounds x="342" y="255" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="367" y="310" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_74" bpmnElement="ExclusiveGateway_1" isMarkerVisible="true"> - <dc:Bounds x="415" y="107" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="315" y="89" width="81" height="24" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_2" bpmnElement="SequenceFlow_2" sourceElement="_BPMNShape_ParallelGateway_12" targetElement="_BPMNShape_ExclusiveGateway_74"> - <di:waypoint xsi:type="dc:Point" x="367" y="255" /> - <di:waypoint xsi:type="dc:Point" x="367" y="132" /> - <di:waypoint xsi:type="dc:Point" x="415" y="132" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="438" y="212" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_3" bpmnElement="SequenceFlow_3" sourceElement="_BPMNShape_ExclusiveGateway_74" targetElement="CallActivity_0jz0w0k_di"> - <di:waypoint xsi:type="dc:Point" x="440" y="107" /> - <di:waypoint xsi:type="dc:Point" x="440" y="65" /> - <di:waypoint xsi:type="dc:Point" x="553" y="65" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="475" y="70" width="18" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ParallelGateway_15" bpmnElement="ParallelGateway_4" isMarkerVisible="true"> - <dc:Bounds x="742" y="107" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="767" y="162" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_23" bpmnElement="SequenceFlow_23" sourceElement="_BPMNShape_ExclusiveGateway_74" targetElement="_BPMNShape_ParallelGateway_15"> - <di:waypoint xsi:type="dc:Point" x="440" y="157" /> - <di:waypoint xsi:type="dc:Point" x="441" y="198" /> - <di:waypoint xsi:type="dc:Point" x="767" y="198" /> - <di:waypoint xsi:type="dc:Point" x="767" y="157" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="452" y="173" width="12" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_79" bpmnElement="ExclusiveGateway_6" isMarkerVisible="true"> - <dc:Bounds x="412" y="468" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="437" y="523" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_24" bpmnElement="SequenceFlow_24" sourceElement="_BPMNShape_ParallelGateway_12" targetElement="_BPMNShape_ExclusiveGateway_79"> - <di:waypoint xsi:type="dc:Point" x="367" y="305" /> - <di:waypoint xsi:type="dc:Point" x="367" y="493" /> - <di:waypoint xsi:type="dc:Point" x="412" y="493" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="415" y="445" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_25" bpmnElement="SequenceFlow_25" sourceElement="_BPMNShape_ExclusiveGateway_79" targetElement="_BPMNShape_ServiceTask_90"> - <di:waypoint xsi:type="dc:Point" x="437" y="468" /> - <di:waypoint xsi:type="dc:Point" x="437" y="402" /> - <di:waypoint xsi:type="dc:Point" x="492" y="402" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="437" y="444" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_26" bpmnElement="SequenceFlow_26" sourceElement="_BPMNShape_ExclusiveGateway_79" targetElement="_BPMNShape_ServiceTask_91"> - <di:waypoint xsi:type="dc:Point" x="437" y="518" /> - <di:waypoint xsi:type="dc:Point" x="437" y="650" /> - <di:waypoint xsi:type="dc:Point" x="488" y="650" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="437" y="596" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ServiceTask_90" bpmnElement="ServiceTask_3"> - <dc:Bounds x="492" y="362" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ServiceTask_91" bpmnElement="ServiceTask_2"> - <dc:Bounds x="488" y="610" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_80" bpmnElement="ExclusiveGateway_7" isMarkerVisible="true"> - <dc:Bounds x="675" y="376" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="657" y="431" width="87" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_29" bpmnElement="SequenceFlow_29" sourceElement="_BPMNShape_ServiceTask_90" targetElement="_BPMNShape_ExclusiveGateway_80"> - <di:waypoint xsi:type="dc:Point" x="592" y="402" /> - <di:waypoint xsi:type="dc:Point" x="675" y="401" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="632" y="404" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ExclusiveGateway_81" bpmnElement="ExclusiveGateway_8" isMarkerVisible="true"> - <dc:Bounds x="674" y="625" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="656" y="680" width="87" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_30" bpmnElement="SequenceFlow_30" sourceElement="_BPMNShape_ServiceTask_91" targetElement="_BPMNShape_ExclusiveGateway_81"> - <di:waypoint xsi:type="dc:Point" x="588" y="650" /> - <di:waypoint xsi:type="dc:Point" x="626" y="650" /> - <di:waypoint xsi:type="dc:Point" x="626" y="649" /> - <di:waypoint xsi:type="dc:Point" x="674" y="650" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="636" y="651" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_31" bpmnElement="SequenceFlow_31" sourceElement="_BPMNShape_ExclusiveGateway_80" targetElement="_BPMNShape_ScriptTask_252"> - <di:waypoint xsi:type="dc:Point" x="700" y="376" /> - <di:waypoint xsi:type="dc:Point" x="701" y="324" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="707" y="351" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_32" bpmnElement="SequenceFlow_32" sourceElement="_BPMNShape_ExclusiveGateway_81" targetElement="_BPMNShape_ScriptTask_253"> - <di:waypoint xsi:type="dc:Point" x="699" y="625" /> - <di:waypoint xsi:type="dc:Point" x="699" y="608" /> - <di:waypoint xsi:type="dc:Point" x="699" y="577" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="709" y="657" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ParallelGateway_16" bpmnElement="ParallelGateway_5" isMarkerVisible="true"> - <dc:Bounds x="853" y="468" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="878" y="523" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_35" bpmnElement="SequenceFlow_35" sourceElement="_BPMNShape_ExclusiveGateway_80" targetElement="_BPMNShape_ParallelGateway_16"> - <di:waypoint xsi:type="dc:Point" x="725" y="401" /> - <di:waypoint xsi:type="dc:Point" x="878" y="401" /> - <di:waypoint xsi:type="dc:Point" x="878" y="468" /> + <dc:Bounds x="128" y="162" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="762" y="392" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_36" bpmnElement="SequenceFlow_36" sourceElement="_BPMNShape_ExclusiveGateway_81" targetElement="_BPMNShape_ParallelGateway_16"> - <di:waypoint xsi:type="dc:Point" x="724" y="650" /> - <di:waypoint xsi:type="dc:Point" x="878" y="650" /> - <di:waypoint xsi:type="dc:Point" x="878" y="518" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="878" y="574" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_ParallelGateway_17" bpmnElement="ParallelGateway_6"> - <dc:Bounds x="957" y="254" width="50" height="50" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="982" y="309" width="0" height="0" /> + <dc:Bounds x="134" y="199" width="24" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_37" bpmnElement="SequenceFlow_37" sourceElement="_BPMNShape_ParallelGateway_16" targetElement="_BPMNShape_ParallelGateway_17"> - <di:waypoint xsi:type="dc:Point" x="903" y="493" /> - <di:waypoint xsi:type="dc:Point" x="982" y="493" /> - <di:waypoint xsi:type="dc:Point" x="982" y="304" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="943" y="478" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_38" bpmnElement="SequenceFlow_38" sourceElement="_BPMNShape_ParallelGateway_15" targetElement="_BPMNShape_ParallelGateway_17"> - <di:waypoint xsi:type="dc:Point" x="792" y="132" /> - <di:waypoint xsi:type="dc:Point" x="982" y="132" /> - <di:waypoint xsi:type="dc:Point" x="982" y="254" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="887" y="117" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_10" bpmnElement="SequenceFlow_10" sourceElement="_BPMNShape_StartEvent_52" targetElement="_BPMNShape_ScriptTask_99"> - <di:waypoint xsi:type="dc:Point" x="175" y="281" /> - <di:waypoint xsi:type="dc:Point" x="211" y="281" /> + <di:waypoint xsi:type="dc:Point" x="164" y="180" /> + <di:waypoint xsi:type="dc:Point" x="279" y="180" /> <bpmndi:BPMNLabel> - <dc:Bounds x="193" y="281" width="0" height="0" /> + <dc:Bounds x="176.5" y="165" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_99" bpmnElement="ScriptTask_8"> - <dc:Bounds x="211" y="241" width="100" height="80" /> + <dc:Bounds x="279" y="140" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_SubProcess_14" bpmnElement="SubProcess_1" isExpanded="true"> - <dc:Bounds x="146" y="759" width="329" height="167" /> + <dc:Bounds x="220" y="365" width="329" height="167" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_100" bpmnElement="ScriptTask_4"> - <dc:Bounds x="259" y="803" width="100" height="80" /> + <dc:Bounds x="333" y="409" width="100" height="80" /> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_StartEvent_54" bpmnElement="StartEvent_2"> - <dc:Bounds x="175" y="825" width="36" height="36" /> + <dc:Bounds x="249" y="431" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="193" y="869" width="0" height="0" /> + <dc:Bounds x="222" y="475" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_101" bpmnElement="ScriptTask_2"> - <dc:Bounds x="1054" y="240" width="100" height="80" /> + <dc:Bounds x="589" y="140" width="100" height="80" /> </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_8" bpmnElement="SequenceFlow_8" sourceElement="_BPMNShape_ParallelGateway_17" targetElement="_BPMNShape_ScriptTask_101"> - <di:waypoint xsi:type="dc:Point" x="1007" y="279" /> - <di:waypoint xsi:type="dc:Point" x="1054" y="280" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1177" y="280" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_12" bpmnElement="SequenceFlow_12" sourceElement="_BPMNShape_ScriptTask_99" targetElement="_BPMNShape_ParallelGateway_12"> - <di:waypoint xsi:type="dc:Point" x="311" y="281" /> - <di:waypoint xsi:type="dc:Point" x="342" y="280" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="327" y="281" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_EndEvent_129" bpmnElement="EndEvent_6"> - <dc:Bounds x="1188" y="262" width="36" height="36" /> + <dc:Bounds x="856" y="162" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="1177" y="303" width="57" height="12" /> + <dc:Bounds x="845" y="203" width="57" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_9" bpmnElement="SequenceFlow_9" sourceElement="_BPMNShape_ScriptTask_101" targetElement="_BPMNShape_EndEvent_129"> - <di:waypoint xsi:type="dc:Point" x="1154" y="280" /> - <di:waypoint xsi:type="dc:Point" x="1188" y="280" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="1171" y="280" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="_BPMNShape_BoundaryEvent_31" bpmnElement="BoundaryEvent_2"> - <dc:Bounds x="525" y="344" width="36" height="36" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="563" y="300" width="68" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_BoundaryEvent_32" bpmnElement="BoundaryEvent_3"> - <dc:Bounds x="521" y="592" width="36" height="36" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="563" y="554" width="68" height="12" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_72" bpmnElement="SequenceFlow_72" sourceElement="_BPMNShape_BoundaryEvent_31" targetElement="_BPMNShape_ScriptTask_252"> - <di:waypoint xsi:type="dc:Point" x="543" y="344" /> - <di:waypoint xsi:type="dc:Point" x="543" y="284" /> - <di:waypoint xsi:type="dc:Point" x="651" y="284" /> + <di:waypoint xsi:type="dc:Point" x="689" y="180" /> + <di:waypoint xsi:type="dc:Point" x="856" y="180" /> <bpmndi:BPMNLabel> - <dc:Bounds x="543" y="326" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_73" bpmnElement="SequenceFlow_73" sourceElement="_BPMNShape_ScriptTask_253"> - <di:waypoint xsi:type="dc:Point" x="750" y="537" /> - <di:waypoint xsi:type="dc:Point" x="790" y="537" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="770" y="522" width="0" height="0" /> + <dc:Bounds x="727.5" y="165" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_252" bpmnElement="ScriptTask_6"> - <dc:Bounds x="651" y="244" width="100" height="80" /> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="_BPMNShape_ScriptTask_253" bpmnElement="ScriptTask_7"> - <dc:Bounds x="650" y="497" width="100" height="80" /> + <dc:Bounds x="431" y="141" width="100" height="80" /> </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_79" bpmnElement="SequenceFlow_79" sourceElement="_BPMNShape_ScriptTask_252"> - <di:waypoint xsi:type="dc:Point" x="751" y="284" /> - <di:waypoint xsi:type="dc:Point" x="793" y="284" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="772" y="269" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="BPMNEdge_SequenceFlow_80" bpmnElement="SequenceFlow_80" sourceElement="_BPMNShape_BoundaryEvent_32" targetElement="_BPMNShape_ScriptTask_253"> - <di:waypoint xsi:type="dc:Point" x="539" y="592" /> - <di:waypoint xsi:type="dc:Point" x="539" y="537" /> - <di:waypoint xsi:type="dc:Point" x="650" y="537" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="567" y="537" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNEdge> <bpmndi:BPMNShape id="EndEvent_0b9vn2u_di" bpmnElement="EndEvent_2"> - <dc:Bounds x="403" y="825" width="36" height="36" /> + <dc:Bounds x="477" y="431" width="36" height="36" /> <bpmndi:BPMNLabel> - <dc:Bounds x="399" y="869" width="47" height="12" /> + <dc:Bounds x="473" y="475" width="47" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="EndEvent_1fmpj5u_di" bpmnElement="EndEvent_14"> - <dc:Bounds x="790" y="519" width="36" height="36" /> - <bpmndi:BPMNLabel> - <dc:Bounds x="808" y="560" width="0" height="0" /> - </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNShape id="EndEvent_0w1puhf_di" bpmnElement="EndEvent_13"> - <dc:Bounds x="793" y="266" width="36" height="36" /> + <bpmndi:BPMNEdge id="SequenceFlow_1ko8ggw_di" bpmnElement="SequenceFlow_1ko8ggw"> + <di:waypoint xsi:type="dc:Point" x="285" y="449" /> + <di:waypoint xsi:type="dc:Point" x="333" y="449" /> <bpmndi:BPMNLabel> - <dc:Bounds x="811" y="307" width="0" height="0" /> + <dc:Bounds x="264" y="424" width="90" height="0" /> </bpmndi:BPMNLabel> - </bpmndi:BPMNShape> - <bpmndi:BPMNEdge id="SequenceFlow_0m7gwor_di" bpmnElement="SequenceFlow_0m7gwor"> - <di:waypoint xsi:type="dc:Point" x="654" y="65" /> - <di:waypoint xsi:type="dc:Point" x="767" y="65" /> - <di:waypoint xsi:type="dc:Point" x="767" y="107" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1pm9r7h_di" bpmnElement="SequenceFlow_1pm9r7h"> + <di:waypoint xsi:type="dc:Point" x="433" y="449" /> + <di:waypoint xsi:type="dc:Point" x="477" y="449" /> <bpmndi:BPMNLabel> - <dc:Bounds x="711" y="50" width="0" height="0" /> + <dc:Bounds x="410" y="424" width="90" height="0" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_1ko8ggw_di" bpmnElement="SequenceFlow_1ko8ggw"> - <di:waypoint xsi:type="dc:Point" x="211" y="843" /> - <di:waypoint xsi:type="dc:Point" x="259" y="843" /> + <bpmndi:BPMNEdge id="SequenceFlow_1kx7ea5_di" bpmnElement="SequenceFlow_1kx7ea5"> + <di:waypoint xsi:type="dc:Point" x="379" y="180" /> + <di:waypoint xsi:type="dc:Point" x="431" y="181" /> <bpmndi:BPMNLabel> - <dc:Bounds x="235" y="818" width="0" height="0" /> + <dc:Bounds x="405" y="159.5" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNEdge id="SequenceFlow_1pm9r7h_di" bpmnElement="SequenceFlow_1pm9r7h"> - <di:waypoint xsi:type="dc:Point" x="359" y="843" /> - <di:waypoint xsi:type="dc:Point" x="403" y="843" /> + <bpmndi:BPMNEdge id="SequenceFlow_1u8shdz_di" bpmnElement="SequenceFlow_1u8shdz"> + <di:waypoint xsi:type="dc:Point" x="531" y="181" /> + <di:waypoint xsi:type="dc:Point" x="589" y="180" /> <bpmndi:BPMNLabel> - <dc:Bounds x="381" y="818" width="0" height="0" /> + <dc:Bounds x="560" y="159.5" width="0" height="12" /> </bpmndi:BPMNLabel> </bpmndi:BPMNEdge> - <bpmndi:BPMNShape id="CallActivity_0jz0w0k_di" bpmnElement="Task_0ixuwt5"> - <dc:Bounds x="554" y="25" width="100" height="80" /> - </bpmndi:BPMNShape> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> </bpmn2:definitions> diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy index 99c351c465..119159f458 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CompleteMsoProcessTest.groovy @@ -1,22 +1,22 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ package org.onap.so.bpmn.common.scripts @@ -24,13 +24,17 @@ import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.junit.Before +import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor +import org.mockito.Mock import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner import org.onap.so.bpmn.core.WorkflowException - +import org.onap.so.db.request.beans.InfraActiveRequests +import org.onap.so.db.request.client.RequestsDbClient import static org.assertj.core.api.Assertions.assertThat import static org.assertj.core.api.Assertions.assertThatThrownBy import static org.mockito.ArgumentMatchers.eq @@ -38,27 +42,20 @@ import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) class CompleteMsoProcessTest { - @Before - public void init() { - MockitoAnnotations.initMocks(this) - } - - private String completeMsoProcessRequest = """ - <sdncadapterworkflow:MsoCompletionRequest xmlns:ns="http://org.onap/so/request/types/v1" xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> - <ns:request-information> - <ns:request-id>uCPE1020_STUW105_5002</ns:request-id> - <ns:request-action>Layer3ServiceActivateRequest</ns:request-action> - <ns:request-sub-action>COMPLETE</ns:request-sub-action> - <ns:source>OMX</ns:source> - <ns:notification-url>http://localhost:28090/CCD/StatusNotification</ns:notification-url> - <ns:order-number>10205000</ns:order-number> - <ns:order-version>1</ns:order-version> - </ns:request-information> - <sdncadapterworkflow:mso-bpel-name>UCPELayer3ServiceActivateV1</sdncadapterworkflow:mso-bpel-name> - </sdncadapterworkflow:MsoCompletionRequest> - """ - - private String completeMsoNetworkProcessRequest = """ + + @Mock + RequestsDbClient requestsDbClient; + + @Spy + CompleteMsoProcess completeMsoProcess; + + + @Before + public void init() { + MockitoAnnotations.initMocks(this) + } + + private String completeMsoNetworkProcessRequest = """ <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" xmlns:ns="http://org.onap/so/request/types/v1"> <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> @@ -71,104 +68,39 @@ class CompleteMsoProcessTest { <aetgt:mso-bpel-name>BPMN Network action: CREATE</aetgt:mso-bpel-name> </aetgt:MsoCompletionRequest>""" - @Test - public void testPreProcessRequest() { - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("CompleteMsoProcessRequest")).thenReturn(completeMsoProcessRequest) - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C"); - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); - - CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess() - completeMsoProcess.preProcessRequest(mockExecution) - - /* Initialize all the process request variables in this block */ - verify(mockExecution).setVariable("prefix","CMSO_") - //verify(mockExecution).setVariable("getLayer3ServiceDetailsV1Response","") - verify(mockExecution).setVariable("CMSO_request_id","") - verify(mockExecution).setVariable("CMSO_notification-url","") - verify(mockExecution).setVariable("CMSO_mso-bpel-name","") - verify(mockExecution).setVariable("CMSO_request_action","") - - verify(mockExecution).setVariable("CMSO_notification-url-Ok", false) - verify(mockExecution).setVariable("CMSO_request_id-Ok", false) - - //updateRequest Adapter process variables - verify(mockExecution).setVariable("CMSO_updateRequestResponse", "") - verify(mockExecution).setVariable("CMSO_updateRequestResponseCode", "") - verify(mockExecution).setVariable("CMSO_updateFinalNotifyAckStatusFailedPayload", "") - - //Set DB adapter variables here - verify(mockExecution).setVariable("CMSO_updateDBStatusToSuccessPayload", "") - verify(mockExecution).setVariable("CMSO_updateInfraRequestDBPayload", "") - verify(mockExecution).setVariable("CMSO_setUpdateDBstatustoSuccessPayload", "") - - //Auth variables - verify(mockExecution).setVariable("BasicAuthHeaderValue","") - - //Response variables - verify(mockExecution).setVariable("CompletionHandlerResponse","") - verify(mockExecution).setVariable("CMSO_ErrorResponse", null) - verify(mockExecution).setVariable("CMSO_ResponseCode", "") - - verify(mockExecution).setVariable("CMSO_notification-url-Ok",true) - verify(mockExecution).setVariable("CMSO_request_id-Ok",true) - verify(mockExecution).setVariable("CMSO_notification-url","http://localhost:28090/CCD/StatusNotification") - verify(mockExecution).setVariable("CMSO_request_id","uCPE1020_STUW105_5002") - verify(mockExecution).setVariable("CMSO_request_action","Layer3ServiceActivateRequest") - verify(mockExecution).setVariable("CMSO_source","OMX") - - } - - private String setUpdateDBstatustoSuccessPayload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateInfraRequest> - <requestId>testReqId</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <statusMessage>Resource Completed Successfully</statusMessage> - <requestStatus>COMPLETE</requestStatus> - <progress>100</progress> - <networkId>bd631913-cfc6-488b-ba22-6b98504f703d</networkId> - </req:updateInfraRequest> - </soapenv:Body> - </soapenv:Envelope>""" - - @Test - public void testsetUpdateDBstatustoSuccessPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("CMSO_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("CMSO_mso-bpel-name")).thenReturn("BPEL") - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC"); - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); - when(mockExecution.getVariable("CompleteMsoProcessRequest")).thenReturn(completeMsoNetworkProcessRequest); - - CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess() - completeMsoProcess.setUpdateDBstatustoSuccessPayload(mockExecution) - - verify(mockExecution).setVariable("CMSO_setUpdateDBstatustoSuccessPayload",setUpdateDBstatustoSuccessPayload) - } - - private String msoCompletionResponse = """onse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> - <sdncadapterworkflow:out>BPEL BPEL-NAME FAILED</sdncadapterworkflow:out> -</sdncadapterworkflow:MsoCompletionResponse>""" - - - @Test - void postProcessResponse_successful() { - DelegateExecution mockExecution = mock(DelegateExecution.class) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("CMSO_mso-bpel-name")).thenReturn("mso-bpel-test") - new CompleteMsoProcess().postProcessResponse(mockExecution) - - String expectedResponse = "<sdncadapterworkflow:MsoCompletionResponse xmlns:sdncadapterworkflow=\"http://ecomp.com/mso/workflow/schema/v1\">\n" + - " <sdncadapterworkflow:out>BPEL mso-bpel-test completed</sdncadapterworkflow:out>\n" + - "</sdncadapterworkflow:MsoCompletionResponse>" - - verify(mockExecution).setVariable("WorkflowResponse", expectedResponse) - verify(mockExecution).setVariable("CompleteMsoProcessResponse", expectedResponse) - verify(mockExecution).setVariable("CMSO_ResponseCode", "200") - } + @Test + public void testPreProcessRequest() { + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("CompleteMsoProcessRequest")).thenReturn(completeMsoNetworkProcessRequest) + + completeMsoProcess.preProcessRequest(mockExecution) + + verify(mockExecution).setVariable("CMSO_request_id", "bd631913-cfc6-488b-ba22-6b98504f703d") + } + + + @Test + public void testUpdateInfraRequestDB(){ + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("CMSO_request_id")).thenReturn("testReqId") + when(mockExecution.getVariable("CompleteMsoProcessRequest")).thenReturn(completeMsoNetworkProcessRequest); + when(completeMsoProcess.getDbClient()).thenReturn(requestsDbClient) + completeMsoProcess.updateInfraRequestDB(mockExecution) + + InfraActiveRequests request = new InfraActiveRequests() + request.setRequestId("testReqId") + + completeMsoProcess.updateInfraRequestDB(mockExecution) + + request.setRequestStatus("COMPLETED") + request.setStatusMessage("Resource Completed Successfully") + request.setProgress(100) + request.setLastModifiedBy("BPMN") + request.setNetworkId("bd631913-cfc6-488b-ba22-6b98504f703d") + + + verify(requestsDbClient, times(2)).updateInfraActiveRequests(request, null, null) + } }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy index 25f62a6555..6cae293971 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/FalloutHandlerTest.groovy @@ -1,22 +1,22 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ package org.onap.so.bpmn.common.scripts @@ -29,31 +29,41 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentCaptor; +import org.mockito.Mock import org.mockito.MockitoAnnotations +import org.mockito.Spy import org.mockito.runners.MockitoJUnitRunner import org.onap.so.bpmn.common.scripts.MsoUtils; +import org.onap.so.db.request.beans.InfraActiveRequests +import org.onap.so.db.request.client.RequestsDbClient import org.onap.so.bpmn.common.scripts.FalloutHandler; @RunWith(MockitoJUnitRunner.class) class FalloutHandlerTest { - - public MsoUtils utils = new MsoUtils() - - @Before - public void init() { - MockitoAnnotations.initMocks(this) - } - private String falloutHandlerRequest = """ + public MsoUtils utils = new MsoUtils() + + @Spy + FalloutHandler falloutHandler = new FalloutHandler() + + @Mock + RequestsDbClient requestsDbClient; + + @Before + public void init() { + MockitoAnnotations.initMocks(this) + } + + private String falloutHandlerRequest = """ <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" xmlns:ns7="http://org.onap/so/request/types/v1"> - <ns7:request-information> + <ns7:request-info> <ns7:request-id>uCPE1020_STUW105_5002</ns7:request-id> <ns7:request-action>Layer3ServiceActivateRequest</ns7:request-action> <ns7:request-sub-action>CANCEL</ns7:request-sub-action> <ns7:source>OMX</ns7:source> <ns7:order-number>10205000</ns7:order-number> <ns7:order-version>1</ns7:order-version> - </ns7:request-information> + </ns7:request-info> <sdncadapterworkflow:WorkflowException> <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage> <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode> @@ -62,251 +72,64 @@ class FalloutHandlerTest { </sdncadapterworkflow:FalloutHandlerRequest> """ - private String falloutHandlerResponse = """<workflow:FalloutHandlerResponse xmlns:workflow="http://org.onap/so/workflow/schema/v1"> + private String falloutHandlerResponse = """<workflow:FalloutHandlerResponse xmlns:workflow="http://org.onap/so/workflow/schema/v1"> <workflow:out>Fallout Handler Failed</workflow:out> </workflow:FalloutHandlerResponse>""" - @Test - public void testPreProcessRequest() { - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - - when(mockExecution.getVariable("FalloutHandlerRequest")).thenReturn(falloutHandlerRequest) - when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C"); - when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.preProcessRequest(mockExecution) - - /* Initialize all the process request variables in this block */ - verify(mockExecution).setVariable("prefix","FH_") - //verify(mockExecution).setVariable("getLayer3ServiceDetailsV1Response","") + @Test + public void testPreProcessRequest() { - //These variables are form the input Message to the BPMN - verify(mockExecution).setVariable("FH_request_id","") - verify(mockExecution).setVariable("FH_request_action","") - verify(mockExecution).setVariable("FH_notification-url","") - verify(mockExecution).setVariable("FH_mso-bpel-name","") - verify(mockExecution).setVariable("FH_ErrorCode", "") - verify(mockExecution).setVariable("FH_ErrorMessage", "") + ExecutionEntity mockExecution = mock(ExecutionEntity.class) - verify(mockExecution).setVariable("FH_notification-url-Ok", false) - verify(mockExecution).setVariable("FH_request_id-Ok", false) + when(mockExecution.getVariable("FalloutHandlerRequest")).thenReturn(falloutHandlerRequest) - //These variables are for Get Mso Aai Password Adapter - verify(mockExecution).setVariable("FH_deliveryStatus", true) + falloutHandler.preProcessRequest(mockExecution) - //update Response Status to pending ...Adapter variables - verify(mockExecution).setVariable("FH_updateResponseStatusPayload", null) - verify(mockExecution).setVariable("FH_updateResponseStatusResponse", null) + verify(mockExecution).setVariable("FH_success", true) + verify(mockExecution).setVariable("FH_request_id","uCPE1020_STUW105_5002") + verify(mockExecution).setVariable("FH_ErrorCode","Some Error Code - Fallout Handler") + verify(mockExecution).setVariable("FH_ErrorMessage","Some Error Message - Fallout Handler") + } - //update Request Gamma ...Adapter variables - verify(mockExecution).setVariable("FH_updateRequestGammaPayload", "") - verify(mockExecution).setVariable("FH_updateRequestGammaResponse", null) - verify(mockExecution).setVariable("FH_updateRequestGammaResponseCode", null) + @Test + public void testpostProcessResponse(){ - //update Request Infra ...Adapter variables - verify(mockExecution).setVariable("FH_updateRequestInfraPayload", "") - verify(mockExecution).setVariable("FH_updateRequestInfraResponse", null) - verify(mockExecution).setVariable("FH_updateRequestInfraResponseCode", null) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) - //assign False to success variable - verify(mockExecution).setVariable("FH_success", true) + when(mockExecution.getVariable("FH_success")).thenReturn(false) - //Set notify status to Failed variable - verify(mockExecution).setVariable("FH_NOTIFY_STATUS", "SUCCESS") + falloutHandler.postProcessResponse(mockExecution) - //Set DB update variable - verify(mockExecution).setVariable("FH_updateRequestPayload", "") - verify(mockExecution).setVariable("FH_updateRequestResponse", null) - verify(mockExecution).setVariable("FH_updateRequestResponseCode", null) + // Capture the arguments to setVariable + ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); - //Auth variables - verify(mockExecution).setVariable("BasicAuthHeaderValue","") + verify(mockExecution, times(4)).setVariable(captor1.capture(), captor2.capture()) + List<String> arg2List = captor2.getAllValues() + String payloadResponseActual = arg2List.get(1) - //Response variables - verify(mockExecution).setVariable("FalloutHandlerResponse","") - verify(mockExecution).setVariable("FH_ErrorResponse", null) - verify(mockExecution).setVariable("FH_ResponseCode", "") + assertEquals(falloutHandlerResponse.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) - verify(mockExecution).setVariable("FH_request_id-Ok",true) - verify(mockExecution).setVariable("FH_request_id","uCPE1020_STUW105_5002") - verify(mockExecution).setVariable("FH_request_action","Layer3ServiceActivateRequest") - verify(mockExecution).setVariable("FH_source","OMX") - verify(mockExecution).setVariable("FH_ErrorCode","Some Error Code - Fallout Handler") - verify(mockExecution).setVariable("FH_ErrorMessage","Some Error Message - Fallout Handler") + verify(mockExecution).setVariable("FH_ResponseCode","500") + } - } - @Test - public void testpostProcessResponse(){ + @Test + public void testUpdateInfraRequestDB(){ - ExecutionEntity mockExecution = mock(ExecutionEntity.class) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") + when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") + when(falloutHandler.getDbClient()).thenReturn(requestsDbClient) - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") - when(mockExecution.getVariable("FH_success")).thenReturn(false) - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.postProcessResponse(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(4)).setVariable(captor1.capture(), captor2.capture()) - List<String> arg2List = captor2.getAllValues() - String payloadResponseActual = arg2List.get(1) - - assertEquals(falloutHandlerResponse.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) - - verify(mockExecution).setVariable("FH_ResponseCode","500") - } - - private String updateRequestPayload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateRequest> - <requestId>testReqId</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <finalErrorMessage>ErrorMessage</finalErrorMessage> - <finalErrorCode>ErrorCode</finalErrorCode> - <status>FAILED</status> - <responseStatus>NotifyStatus</responseStatus> - </req:updateRequest> - </soapenv:Body> - </soapenv:Envelope> - """ - - @Test - public void testupdateRequestPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") - when(mockExecution.getVariable("FH_ErrorCode")).thenReturn("ErrorCode") - when(mockExecution.getVariable("FH_NOTIFY_STATUS")).thenReturn("NotifyStatus") - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateRequestPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List<String> arg2List = captor2.getAllValues() - String payloadRequestActual = arg2List.get(0) - - assertEquals(updateRequestPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) - } - - private String updateRequestInfraPayload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateInfraRequest> - <requestId>testReqId</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <statusMessage>ErrorMessage</statusMessage> - <requestStatus>FAILED</requestStatus> - <progress>100</progress> - </req:updateInfraRequest> - </soapenv:Body> - </soapenv:Envelope> - """ - - @Test - public void testupdateRequestInfraPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateRequestInfraPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List<String> arg2List = captor2.getAllValues() - String payloadRequestActual = arg2List.get(0) - - assertEquals(updateRequestInfraPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) - } - - private String updateRequestGammaPayload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateRequest> - <requestId>testReqId</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <finalErrorMessage>ErrorMessage</finalErrorMessage> - <finalErrorCode>ErrorCode</finalErrorCode> - <status>FAILED</status> - </req:updateRequest> - </soapenv:Body> - </soapenv:Envelope> - """ - - @Test - public void testupdateRequestGammaPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") - when(mockExecution.getVariable("FH_ErrorMessage")).thenReturn("ErrorMessage") - when(mockExecution.getVariable("FH_ErrorCode")).thenReturn("ErrorCode") - when(mockExecution.getVariable("mso.default.adapter.namespace")).thenReturn("http://org.onap.so"); - - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateRequestGammaPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List<String> arg2List = captor2.getAllValues() - String payloadRequestActual = arg2List.get(0) - - assertEquals(updateRequestGammaPayload.replaceAll("\\s+", ""), payloadRequestActual.replaceAll("\\s+", "")) - } - - - String updateResponseStatusPayload = """ - <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> - <soapenv:Header/> - <soapenv:Body> - <req:updateResponseStatus> - <requestId>testReqId</requestId> - <lastModifiedBy>BPEL</lastModifiedBy> - <responseStatus>SENDING_FINAL_NOTIFY</responseStatus> - </req:updateResponseStatus> - </soapenv:Body> - </soapenv:Envelope> - """ - - @Test - public void testupdateResponseStatusPayload(){ - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("FH_request_id")).thenReturn("testReqId") + falloutHandler.updateInfraRequestDB(mockExecution) - FalloutHandler falloutHandler = new FalloutHandler() - falloutHandler.updateResponseStatusPayload(mockExecution) - - // Capture the arguments to setVariable - ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); - - verify(mockExecution, times(1)).setVariable(captor1.capture(), captor2.capture()) - List<String> arg2List = captor2.getAllValues() - String payloadResponseActual = arg2List.get(0) - - assertEquals(updateResponseStatusPayload.replaceAll("\\s+", ""), payloadResponseActual.replaceAll("\\s+", "")) - } + InfraActiveRequests infraRequest = new InfraActiveRequests(); + infraRequest.setLastModifiedBy("BPMN") + infraRequest.setStatusMessage("ErrorMessage") + infraRequest.setRequestStatus("FAILED") + infraRequest.setProgress(100) + verify(requestsDbClient, times(1)).updateInfraActiveRequests(infraRequest, null, null) + } }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java index 335d5b9d70..8ee3979386 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupTest.java @@ -46,7 +46,9 @@ import java.util.Optional; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; @@ -87,6 +89,8 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoNetwork; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceProxy; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.NoServiceInstanceFoundException; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.ServiceModelNotFoundException; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -149,6 +153,9 @@ public class BBInputSetupTest { @Mock private RequestsDbClient requestsDbClient; + @Rule + public ExpectedException expectedException = ExpectedException.none(); + @Before public void setup() { SPY_bbInputSetup.setBbInputSetupUtils(SPY_bbInputSetupUtils); @@ -450,7 +457,8 @@ public class BBInputSetupTest { doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId"); doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(executeBB.getRequestId(), - requestDetails, service, "bbName", serviceInstance, lookupKeyMap, resourceId, vnfType, null, null); + requestDetails, service, "bbName", serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, + false); doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance); doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, executeBB, requestAction, null); @@ -461,19 +469,50 @@ public class BBInputSetupTest { assertThat(actual, sameBeanAs(expected)); } - @Test(expected = Exception.class) + @Test public void testGetGBBALaCarteNonServiceWithoutServiceModelInfo() throws Exception { ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), ExecuteBuildingBlock.class); RequestDetails requestDetails = mapper.readValue( new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class); Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); String requestAction = "createInstance"; org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance(); aaiServiceInstance.setModelVersionId("modelVersionId"); String resourceId = "123"; String vnfType = "vnfType"; + doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + doReturn(null).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + + expectedException.expect(ServiceModelNotFoundException.class); + expectedException.expectMessage( + "Related service instance model not found in MSO CatalogDB: model-version-id=modelVersionId"); + + SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, + vnfType); + } + + @Test + public void testGetGBBALaCarteNonServiceServiceInstanceNotFoundInAAI() throws Exception { + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + RequestDetails requestDetails = mapper.readValue( + new File(RESOURCE_PATH + "RequestDetailsInput_withRelatedInstanceList.json"), RequestDetails.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); + String requestAction = "createInstance"; + org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance(); + aaiServiceInstance.setModelVersionId("modelVersionId"); + String resourceId = "123"; + String vnfType = "vnfType"; + + doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + + expectedException.expect(NoServiceInstanceFoundException.class); + expectedException.expectMessage("Related service instance from AAI not found: service-instance-id=si123"); + SPY_bbInputSetup.getGBBALaCarteNonService(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); } @@ -501,7 +540,8 @@ public class BBInputSetupTest { doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("instanceId"); doNothing().when(SPY_bbInputSetup).populateObjectsOnAssignAndCreateFlows(executeBB.getRequestId(), - requestDetails, service, "bbName", serviceInstance, lookupKeyMap, resourceId, vnfType, null, null); + requestDetails, service, "bbName", serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, + false); doReturn(serviceInstance).when(SPY_bbInputSetup).getExistingServiceInstance(aaiServiceInstance); doReturn(expected).when(SPY_bbInputSetup).populateGBBWithSIAndAdditionalInfo(requestDetails, serviceInstance, @@ -778,6 +818,7 @@ public class BBInputSetupTest { String vnfType = "vnfType"; String resourceId = "networkId"; String productFamilyId = "productFamilyId"; + String applicationId = "applicationId"; Service service = Mockito.mock(Service.class); ServiceInstance serviceInstance = Mockito.mock(ServiceInstance.class); RequestDetails requestDetails = Mockito.mock(RequestDetails.class); @@ -801,10 +842,11 @@ public class BBInputSetupTest { doReturn(lineOfBusiness).when(requestDetails).getLineOfBusiness(); doReturn(relatedInstanceList).when(requestDetails).getRelatedInstanceList(); doReturn(cloudConfiguration).when(requestDetails).getCloudConfiguration(); + doReturn(applicationId).when(requestInfo).getApplicationId(); doReturn(ModelType.network).when(modelInfo).getModelType(); SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbName, - serviceInstance, lookupKeyMap, resourceId, vnfType, null, null); + serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); verify(SPY_bbInputSetup, times(1)).populateL3Network(REQUEST_ID, instanceName, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, null); assertEquals("NetworkId populated", true, @@ -812,14 +854,16 @@ public class BBInputSetupTest { doReturn(ModelType.vnf).when(modelInfo).getModelType(); resourceId = "vnfId"; + doNothing().when(SPY_bbInputSetup).populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, - vnfType, null, productFamilyId); + vnfType, null, productFamilyId, applicationId); + SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbName, - serviceInstance, lookupKeyMap, resourceId, vnfType, null, null); + serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); verify(SPY_bbInputSetup, times(1)).populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, relatedInstanceList, resourceId, - vnfType, null, productFamilyId); + vnfType, null, productFamilyId, applicationId); assertEquals("VnfId populated", true, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID).equalsIgnoreCase(resourceId)); @@ -828,7 +872,7 @@ public class BBInputSetupTest { doNothing().when(SPY_bbInputSetup).populateVolumeGroup(REQUEST_ID, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbName, - serviceInstance, lookupKeyMap, resourceId, vnfType, null, null); + serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(REQUEST_ID, modelInfo, service, bbName, serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); assertEquals("VolumeGroupId populated", true, @@ -837,13 +881,25 @@ public class BBInputSetupTest { doReturn(ModelType.vfModule).when(modelInfo).getModelType(); resourceId = "vfModuleId"; doNothing().when(SPY_bbInputSetup).populateVfModule(REQUEST_ID, modelInfo, service, bbName, serviceInstance, - lookupKeyMap, resourceId, relatedInstanceList, instanceName, null, cloudConfiguration); + lookupKeyMap, resourceId, relatedInstanceList, instanceName, null, cloudConfiguration, false); SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbName, - serviceInstance, lookupKeyMap, resourceId, vnfType, null, null); + serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); verify(SPY_bbInputSetup, times(1)).populateVfModule(REQUEST_ID, modelInfo, service, bbName, serviceInstance, - lookupKeyMap, resourceId, relatedInstanceList, instanceName, null, cloudConfiguration); + lookupKeyMap, resourceId, relatedInstanceList, instanceName, null, cloudConfiguration, false); assertEquals("VfModuleId populated", true, lookupKeyMap.get(ResourceKey.VF_MODULE_ID).equalsIgnoreCase(resourceId)); + + String bbNameAssignVolume = AssignFlows.VOLUME_GROUP.toString(); + doReturn(ModelType.vfModule).when(modelInfo).getModelType(); + resourceId = "vfModuleId"; + doNothing().when(SPY_bbInputSetup).populateVolumeGroup(REQUEST_ID, modelInfo, service, bbNameAssignVolume, + serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); + SPY_bbInputSetup.populateObjectsOnAssignAndCreateFlows(REQUEST_ID, requestDetails, service, bbNameAssignVolume, + serviceInstance, lookupKeyMap, resourceId, vnfType, null, null, false); + verify(SPY_bbInputSetup, times(1)).populateVolumeGroup(REQUEST_ID, modelInfo, service, bbNameAssignVolume, + serviceInstance, lookupKeyMap, resourceId, relatedInstanceList, instanceName, vnfType, null); + assertEquals("VolumeGroupId populated", true, + lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID).equalsIgnoreCase(resourceId)); } @Test @@ -1352,6 +1408,7 @@ public class BBInputSetupTest { vnf.setVnfName("vnfName"); serviceInstance.getVnfs().add(vnf); String vnfType = "vnfType"; + String applicationId = "applicationId"; RequestDetails requestDetails = mapper.readValue(new File(RESOURCE_PATH + "RequestDetails_CreateVnf.json"), RequestDetails.class); @@ -1378,20 +1435,20 @@ public class BBInputSetupTest { SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service); instanceName = "vnfName2"; GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId()); + resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); doReturn(vnf2).when(SPY_bbInputSetup).createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId()); + resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); doNothing().when(SPY_bbInputSetup).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); @@ -1399,7 +1456,7 @@ public class BBInputSetupTest { SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service); verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); verify(SPY_bbInputSetup, times(2)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); @@ -1461,6 +1518,7 @@ public class BBInputSetupTest { Platform expectedPlatform = new Platform(); LineOfBusiness expectedLineOfBusiness = new LineOfBusiness(); String resourceId = "123"; + String applicationId = "applicationId"; doReturn(expectedPlatform).when(bbInputSetupMapperLayer).mapRequestPlatform(platform); doReturn(expectedLineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(lineOfBusiness); org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf(); @@ -1475,18 +1533,18 @@ public class BBInputSetupTest { SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(1)).mapCatalogVnf(vnf, modelInfo, service); instanceName = "vnfName2"; GenericVnf vnf2 = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, platform, lineOfBusiness, - resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId()); + resourceId, vnfType, null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); org.onap.aai.domain.yang.GenericVnf vnf2AAI = new org.onap.aai.domain.yang.GenericVnf(); vnfAAI.setModelCustomizationId("modelCustId2"); @@ -1495,7 +1553,7 @@ public class BBInputSetupTest { doNothing().when(SPY_bbInputSetup).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); SPY_bbInputSetup.populateGenericVnf(REQUEST_ID, modelInfo, instanceName, platform, lineOfBusiness, service, bbName, serviceInstance, lookupKeyMap, requestDetails.getRelatedInstanceList(), resourceId, vnfType, - null, requestDetails.getRequestInfo().getProductFamilyId()); + null, requestDetails.getRequestInfo().getProductFamilyId(), applicationId); verify(SPY_bbInputSetup, times(2)).mapCatalogVnf(vnf2, modelInfo, service); verify(SPY_bbInputSetup, times(2)).mapNetworkCollectionInstanceGroup(vnf2, "{instanceGroupId}"); verify(SPY_bbInputSetup, times(1)).mapVnfcCollectionInstanceGroup(vnf2, modelInfo, service); @@ -1876,6 +1934,7 @@ public class BBInputSetupTest { String serviceInstanceId = "serviceInstanceId"; String networkId = "networkId"; String vnfId = "vnfId"; + String pnfId = "pnfId"; String vfModuleId = "vfModuleId"; String volumeGroupId = "volumeGroupId"; String configurationId = "configurationId"; @@ -1884,6 +1943,7 @@ public class BBInputSetupTest { expected.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstanceId); expected.put(ResourceKey.NETWORK_ID, networkId); expected.put(ResourceKey.GENERIC_VNF_ID, vnfId); + expected.put(ResourceKey.PNF, pnfId); expected.put(ResourceKey.VF_MODULE_ID, vfModuleId); expected.put(ResourceKey.VOLUME_GROUP_ID, volumeGroupId); expected.put(ResourceKey.CONFIGURATION_ID, configurationId); @@ -1893,6 +1953,7 @@ public class BBInputSetupTest { workflowResourceIds.setServiceInstanceId(serviceInstanceId); workflowResourceIds.setNetworkId(networkId); workflowResourceIds.setVnfId(vnfId); + workflowResourceIds.setPnfId(pnfId); workflowResourceIds.setVfModuleId(vfModuleId); workflowResourceIds.setVolumeGroupId(volumeGroupId); workflowResourceIds.setConfigurationId(configurationId); @@ -1931,7 +1992,6 @@ public class BBInputSetupTest { configResourceKeys.setVfModuleCustomizationUUID("vfModuleCustomizationUUID"); configResourceKeys.setVnfResourceCustomizationUUID("vnfResourceCustomizationUUID"); executeBB.setConfigurationResourceKeys(configResourceKeys); - executeBB.setRequestDetails(requestDetails); doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID)); @@ -1957,7 +2017,7 @@ public class BBInputSetupTest { any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(), - any(String.class)); + any(String.class), any(String.class)); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -1965,7 +2025,7 @@ public class BBInputSetupTest { SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateVfModule(any(String.class), isA(ModelInfo.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), - any(), isA(CloudConfiguration.class)); + any(), isA(CloudConfiguration.class), Mockito.anyBoolean()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString()); @@ -2216,7 +2276,6 @@ public class BBInputSetupTest { Service service = Mockito.mock(Service.class); String requestAction = "createInstance"; - executeBB.setRequestDetails(requestDetails); doReturn(gBB).when(SPY_bbInputSetup).getGBBALaCarteService(executeBB, requestDetails, lookupKeyMap, requestAction, lookupKeyMap.get(ResourceKey.SERVICE_INSTANCE_ID)); @@ -2241,7 +2300,7 @@ public class BBInputSetupTest { any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), ArgumentMatchers.isNull(), any(String.class), - ArgumentMatchers.isNull(), any(), any(String.class)); + ArgumentMatchers.isNull(), any(), any(String.class), any()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -2249,7 +2308,7 @@ public class BBInputSetupTest { SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateVfModule(any(String.class), isA(ModelInfo.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), - any(), isA(CloudConfiguration.class)); + any(), isA(CloudConfiguration.class), Mockito.anyBoolean()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString()); @@ -2306,7 +2365,7 @@ public class BBInputSetupTest { any(String.class), isA(org.onap.so.serviceinstancebeans.Platform.class), isA(org.onap.so.serviceinstancebeans.LineOfBusiness.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(), any(String.class), any(String.class), any(), - any(String.class)); + any(String.class), any(String.class)); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VF_MODULE.toString()); @@ -2314,7 +2373,7 @@ public class BBInputSetupTest { SPY_bbInputSetup.getGBBMacro(executeBB, requestDetails, lookupKeyMap, requestAction, resourceId, vnfType); verify(SPY_bbInputSetup, times(1)).populateVfModule(any(String.class), isA(ModelInfo.class), isA(Service.class), any(String.class), isA(ServiceInstance.class), any(), any(String.class), any(), any(String.class), - any(), isA(CloudConfiguration.class)); + any(), isA(CloudConfiguration.class), Mockito.anyBoolean()); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, null); executeBB.getBuildingBlock().setBpmnFlowName(AssignFlows.VOLUME_GROUP.toString()); @@ -2666,6 +2725,48 @@ public class BBInputSetupTest { } @Test + public void testGetGBBMacroExistingServiceServiceinstancenotFoundInAai() throws Exception { + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); + + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setLcpCloudRegionId("cloudRegionId"); + + doReturn(null).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + + expectedException.expect(NoServiceInstanceFoundException.class); + expectedException.expectMessage("Related service instance from AAI not found: service-instance-id=si123"); + + SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap, "AssignVnfBB", "assign", + cloudConfiguration); + } + + @Test + public void testGetGBBMacroExistingServiceServiceModelNotFound() throws Exception { + ExecuteBuildingBlock executeBB = mapper.readValue(new File(RESOURCE_PATH + "ExecuteBuildingBlockSimple.json"), + ExecuteBuildingBlock.class); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, "si123"); + org.onap.aai.domain.yang.ServiceInstance aaiServiceInstance = new org.onap.aai.domain.yang.ServiceInstance(); + aaiServiceInstance.setModelVersionId("modelVersionId"); + + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setLcpCloudRegionId("cloudRegionId"); + + doReturn(aaiServiceInstance).when(SPY_bbInputSetupUtils).getAAIServiceInstanceById("si123"); + doReturn(null).when(SPY_bbInputSetupUtils).getCatalogServiceByModelUUID(aaiServiceInstance.getModelVersionId()); + + expectedException.expect(ServiceModelNotFoundException.class); + expectedException.expectMessage( + "Related service instance model not found in MSO CatalogDB: model-version-id=modelVersionId"); + + SPY_bbInputSetup.getGBBMacroExistingService(executeBB, lookupKeyMap, "AssignVnfBB", "assign", + cloudConfiguration); + } + + @Test public void testGetVnfId() { String expected = "vnfId"; ExecuteBuildingBlock executeBB = new ExecuteBuildingBlock(); @@ -2765,6 +2866,7 @@ public class BBInputSetupTest { String platformName = "platformName"; String lineOfBusinessName = "lineOfBusinessName"; String productFamilyId = "productFamilyId"; + String applicationId = "applicationId"; Platform platform = new Platform(); platform.setPlatformName(platformName); LineOfBusiness lineOfBusiness = new LineOfBusiness(); @@ -2781,6 +2883,7 @@ public class BBInputSetupTest { expected.setLineOfBusiness(lineOfBusiness); expected.setProvStatus("PREPROV"); expected.setServiceId(productFamilyId); + expected.setApplicationId(applicationId); Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); List<Map<String, String>> instanceParams = new ArrayList<>(); instanceParams.add(cloudParams); @@ -2794,14 +2897,14 @@ public class BBInputSetupTest { doReturn(lineOfBusiness).when(bbInputSetupMapperLayer).mapRequestLineOfBusiness(requestLineOfBusiness); GenericVnf actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, - requestLineOfBusiness, vnfId, vnfType, instanceParams, productFamilyId); + requestLineOfBusiness, vnfId, vnfType, instanceParams, productFamilyId, applicationId); assertThat(actual, sameBeanAs(expected)); assertEquals("LookupKeyMap is populated", vnfId, lookupKeyMap.get(ResourceKey.GENERIC_VNF_ID)); expected.getCloudParams().clear(); actual = SPY_bbInputSetup.createGenericVnf(lookupKeyMap, instanceName, requestPlatform, requestLineOfBusiness, - vnfId, vnfType, null, productFamilyId); + vnfId, vnfType, null, productFamilyId, applicationId); assertThat(actual, sameBeanAs(expected)); } @@ -2883,7 +2986,76 @@ public class BBInputSetupTest { isA(Service.class), isA(String.class)); SPY_bbInputSetup.populateVfModule(REQUEST_ID, modelInfo, service, bbName, serviceInstance, lookupKeyMap, - resourceId, relatedInstanceList, instanceName, instanceParams, cloudConfiguration); + resourceId, relatedInstanceList, instanceName, instanceParams, cloudConfiguration, false); + + verify(SPY_bbInputSetup, times(3)).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class), + isA(Service.class), isA(String.class)); + assertEquals("Lookup Key Map populated with VfModule Id", vfModuleId, + lookupKeyMap.get(ResourceKey.VF_MODULE_ID)); + assertEquals("Lookup Key Map populated with VolumeGroup Id", volumeGroupId, + lookupKeyMap.get(ResourceKey.VOLUME_GROUP_ID)); + } + + @Test + public void testPopulateVfModuleIsReplace() throws Exception { + String vnfId = "vnfId"; + String vfModuleId = "vfModuleId"; + String volumeGroupId = "volumeGroupId"; + String vfModuleCustomizationId = "vfModuleCustomizationId"; + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelCustomizationId(vfModuleCustomizationId); + Service service = new Service(); + String bbName = AssignFlows.VF_MODULE.toString(); + ServiceInstance serviceInstance = new ServiceInstance(); + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId(vnfId); + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId(volumeGroupId); + vnf.getVolumeGroups().add(volumeGroup); + serviceInstance.getVnfs().add(vnf); + VfModule vfModule1 = new VfModule(); + vfModule1.setVfModuleId("vfModuleId1"); + VfModule vfModule2 = new VfModule(); + vfModule2.setVfModuleId("vfModuleId2"); + vnf.getVfModules().add(vfModule1); + vnf.getVfModules().add(vfModule2); + Map<ResourceKey, String> lookupKeyMap = new HashMap<>(); + lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, vnfId); + String resourceId = vfModuleId; + RelatedInstanceList[] relatedInstanceList = new RelatedInstanceList[1]; + RelatedInstanceList relatedInstanceListObj = new RelatedInstanceList(); + RelatedInstance relatedInstance = new RelatedInstance(); + relatedInstance.setInstanceId(vnfId); + + ModelInfo vnfModelInfo = new ModelInfo(); + vnfModelInfo.setModelCustomizationId("vnfCustomizationId"); + vnfModelInfo.setModelType(ModelType.vnf); + relatedInstance.setModelInfo(vnfModelInfo); + relatedInstanceListObj.setRelatedInstance(relatedInstance); + relatedInstanceList[0] = relatedInstanceListObj; + + String instanceName = "vfModuleName"; + List<Map<String, String>> instanceParams = null; + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + + org.onap.aai.domain.yang.GenericVnf vnfAAI = new org.onap.aai.domain.yang.GenericVnf(); + vnfAAI.setModelCustomizationId("vnfModelCustId"); + org.onap.aai.domain.yang.VolumeGroup volumeGroupAAI = new org.onap.aai.domain.yang.VolumeGroup(); + volumeGroupAAI.setModelCustomizationId(vfModuleCustomizationId); + org.onap.aai.domain.yang.VfModule vfModuleAAI = new org.onap.aai.domain.yang.VfModule(); + vfModuleAAI.setModelCustomizationId(vfModuleCustomizationId); + + doReturn(vnfAAI).when(SPY_bbInputSetupUtils).getAAIGenericVnf(vnf.getVnfId()); + doReturn(volumeGroupAAI).when(SPY_bbInputSetupUtils).getAAIVolumeGroup(CLOUD_OWNER, + cloudConfiguration.getLcpCloudRegionId(), volumeGroup.getVolumeGroupId()); + doReturn(vfModuleAAI).when(SPY_bbInputSetupUtils).getAAIVfModule(isA(String.class), isA(String.class)); + doNothing().when(SPY_bbInputSetup).mapCatalogVnf(isA(GenericVnf.class), isA(ModelInfo.class), + isA(Service.class)); + doNothing().when(SPY_bbInputSetup).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class), + isA(Service.class), isA(String.class)); + + SPY_bbInputSetup.populateVfModule(REQUEST_ID, modelInfo, service, bbName, serviceInstance, lookupKeyMap, + resourceId, relatedInstanceList, instanceName, instanceParams, cloudConfiguration, true); verify(SPY_bbInputSetup, times(3)).mapCatalogVfModule(isA(VfModule.class), isA(ModelInfo.class), isA(Service.class), isA(String.class)); diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java index 7780837714..3fdbf39756 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtilsTest.java @@ -22,6 +22,7 @@ package org.onap.so.bpmn.servicedecomposition.tasks; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.any; @@ -480,7 +481,9 @@ public class BBInputSetupUtilsTest { @Test public void testGetOptionalAAIServiceInstanceByNameException() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple service instances found for customer-id: globalCustomerId, service-type: serviceType and service-instance-name: serviceInstanceId.")); String globalCustomerId = "globalCustomerId"; String serviceType = "serviceType"; @@ -628,7 +631,9 @@ public class BBInputSetupUtilsTest { @Test public void getRelatedNetworkByNameFromServiceInstanceMultipleNetworksExceptionTest() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple networks found for service-instance-id: serviceInstanceId and network-name: networkName.")); String serviceInstanceId = "serviceInstanceId"; String networkName = "networkName"; @@ -637,11 +642,12 @@ public class BBInputSetupUtilsTest { network.setNetworkId("id123"); network.setNetworkName("name123"); - L3Networks expected = new L3Networks(); - expected.getL3Network().add(network); - expected.getL3Network().add(network); + L3Networks l3Networks = new L3Networks(); + l3Networks.getL3Network().add(network); + l3Networks.getL3Network().add(network); + Optional<L3Networks> optNetworks = Optional.of(l3Networks); - doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class)); + doReturn(optNetworks).when(MOCK_aaiResourcesClient).get(eq(L3Networks.class), any(AAIResourceUri.class)); bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(serviceInstanceId, networkName); } @@ -711,7 +717,9 @@ public class BBInputSetupUtilsTest { @Test public void getRelatedVnfByNameFromServiceInstanceMultipleVnfsExceptionTest() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple vnfs found for service-instance-id: serviceInstanceId and vnf-name: vnfName.")); String serviceInstanceId = "serviceInstanceId"; String vnfName = "vnfName"; @@ -720,11 +728,13 @@ public class BBInputSetupUtilsTest { vnf.setVnfId("id123"); vnf.setVnfName("name123"); - GenericVnfs expectedVnf = new GenericVnfs(); - expectedVnf.getGenericVnf().add(vnf); - expectedVnf.getGenericVnf().add(vnf); + GenericVnfs vnfs = new GenericVnfs(); + vnfs.getGenericVnf().add(vnf); + vnfs.getGenericVnf().add(vnf); + + Optional<GenericVnfs> optVnfs = Optional.of(vnfs); - doReturn(expectedVnf).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class)); + doReturn(optVnfs).when(MOCK_aaiResourcesClient).get(eq(GenericVnfs.class), any(AAIResourceUri.class)); bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(serviceInstanceId, vnfName); } @@ -756,7 +766,10 @@ public class BBInputSetupUtilsTest { @Test public void getRelatedVolumeGroupByNameFromVnfMultipleVolumeGroupsExceptionTest() throws Exception { - expectedException.expect(Exception.class); + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple volume-groups found for vnf-id: vnfId and volume-group-name: volumeGroupName.")); + String vnfId = "vnfId"; String volumeGroupName = "volumeGroupName"; @@ -765,12 +778,12 @@ public class BBInputSetupUtilsTest { volumeGroup.setVolumeGroupId("id123"); volumeGroup.setVolumeGroupName("name123"); - VolumeGroups expectedVolumeGroup = new VolumeGroups(); - expectedVolumeGroup.getVolumeGroup().add(volumeGroup); - expectedVolumeGroup.getVolumeGroup().add(volumeGroup); + VolumeGroups volumeGroups = new VolumeGroups(); + volumeGroups.getVolumeGroup().add(volumeGroup); + volumeGroups.getVolumeGroup().add(volumeGroup); + Optional<VolumeGroups> optVolumeGroups = Optional.of(volumeGroups); - doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), - any(AAIResourceUri.class)); + doReturn(optVolumeGroups).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(vnfId, volumeGroupName); } @@ -802,12 +815,11 @@ public class BBInputSetupUtilsTest { } @Test - public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception { + public void getRelatedVolumeGroupFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception { expectedException.expect(Exception.class); String vnfId = "vnfId"; String volumeGroupId = "volumeGroupId"; - String volumeGroupName = "volumeGroupName"; VolumeGroup volumeGroup = new VolumeGroup(); volumeGroup.setVolumeGroupId("id123"); @@ -820,6 +832,54 @@ public class BBInputSetupUtilsTest { doReturn(expectedVolumeGroup).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, volumeGroupId); + } + + @Test + public void getRelatedVolumeGroupFromVfModuleNotFoundTest() throws Exception { + String vnfId = "vnfId"; + String volumeGroupId = "volumeGroupId"; + + doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + + Optional<VolumeGroup> actualVolumeGroup = + bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, volumeGroupId); + + assertEquals(actualVolumeGroup, Optional.empty()); + } + + @Test + public void getRelatedVolumeGroupFromVfModuleTest() throws Exception { + Optional<VolumeGroups> expected = Optional.of(new VolumeGroups()); + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + expected.get().getVolumeGroup().add(volumeGroup); + doReturn(expected).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + Optional<VolumeGroup> actual = this.bbInputSetupUtils.getRelatedVolumeGroupFromVfModule("id123", "id123"); + assertEquals(actual.get().getVolumeGroupId(), expected.get().getVolumeGroup().get(0).getVolumeGroupId()); + } + + @Test + public void getRelatedVolumeGroupByNameFromVfModuleMultipleVolumeGroupsExceptionTest() throws Exception { + expectedException.expect(MultipleObjectsFoundException.class); + expectedException.expectMessage(containsString( + "Multiple voulme-groups found for vnf-id: vnfId, vf-module-id: volumeGroupId and volume-group-name: volumeGroupName.")); + String vnfId = "vnfId"; + String volumeGroupId = "volumeGroupId"; + String volumeGroupName = "volumeGroupName"; + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + volumeGroup.setVolumeGroupName("name123"); + + VolumeGroups volumeGroups = new VolumeGroups(); + volumeGroups.getVolumeGroup().add(volumeGroup); + volumeGroups.getVolumeGroup().add(volumeGroup); + + Optional<VolumeGroups> optVolumeGroups = Optional.of(volumeGroups); + + doReturn(optVolumeGroups).when(MOCK_aaiResourcesClient).get(eq(VolumeGroups.class), any(AAIResourceUri.class)); + bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnfId, volumeGroupId, volumeGroupName); } @@ -837,6 +897,7 @@ public class BBInputSetupUtilsTest { assertEquals(actualVolumeGroup, Optional.empty()); } + @Test public void loadOriginalFlowExecutionPathTest() throws Exception { @@ -867,6 +928,33 @@ public class BBInputSetupUtilsTest { } @Test + public void getRelatedConfigurationByNameFromServiceInstanceExceptionTest() throws Exception { + Configuration configuration = new Configuration(); + configuration.setConfigurationId("id123"); + + Configurations configurations = new Configurations(); + configurations.getConfiguration().add(configuration); + configurations.getConfiguration().add(configuration); + + Optional<Configurations> optConfigurations = Optional.of(configurations); + + doReturn(optConfigurations).when(MOCK_aaiResourcesClient).get(eq(Configurations.class), + any(AAIResourceUri.class)); + + expectedException.expect(MultipleObjectsFoundException.class); + this.bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance("id123", "name123"); + } + + @Test + public void getRelatedConfigurationByNameFromServiceInstanceNotFoundTest() throws Exception { + doReturn(Optional.empty()).when(MOCK_aaiResourcesClient).get(eq(Configurations.class), + any(AAIResourceUri.class)); + Optional<Configuration> actualConfiguration = + bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance("id123", "name123"); + assertEquals(actualConfiguration, Optional.empty()); + } + + @Test public void getRelatedConfigurationByNameFromServiceInstanceTest() throws Exception { Optional<Configurations> expected = Optional.of(new Configurations()); Configuration configuration = new Configuration(); @@ -878,4 +966,35 @@ public class BBInputSetupUtilsTest { assertEquals(actual.get().getConfigurationId(), expected.get().getConfiguration().get(0).getConfigurationId()); } + @Test + public void existsAAIVfModuleGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = + AAIUriFactory.createNodesUri(AAIObjectPlurals.VF_MODULE).queryParam("vf-module-name", "testVfModule"); + bbInputSetupUtils.existsAAIVfModuleGloballyByName("testVfModule"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } + + @Test + public void existsAAIConfigurationGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.CONFIGURATION) + .queryParam("configuration-name", "testConfig"); + bbInputSetupUtils.existsAAIConfigurationGloballyByName("testConfig"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } + + @Test + public void existsAAINetworksGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = + AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", "testNetwork"); + bbInputSetupUtils.existsAAINetworksGloballyByName("testNetwork"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } + + @Test + public void existsAAIVolumeGroupGloballyByNameTest() throws Exception { + AAIResourceUri expectedUri = AAIUriFactory.createNodesUri(AAIObjectPlurals.VOLUME_GROUP) + .queryParam("volume-group-name", "testVoumeGroup"); + bbInputSetupUtils.existsAAIVolumeGroupGloballyByName("testVoumeGroup"); + verify(MOCK_aaiResourcesClient, times(1)).exists(expectedUri); + } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundExceptionTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundExceptionTest.java new file mode 100644 index 0000000000..1ab1d7aa9a --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/exceptions/ServiceModelNotFoundExceptionTest.java @@ -0,0 +1,19 @@ +package org.onap.so.bpmn.servicedecomposition.tasks.exceptions; + +import org.junit.Assert; +import org.junit.Test; + + +public class ServiceModelNotFoundExceptionTest { + + @Test + public void testRequestValidationException() { + + ServiceModelNotFoundException serviceModelNotFoundException = new ServiceModelNotFoundException(); + Assert.assertNull(serviceModelNotFoundException.getMessage()); + + serviceModelNotFoundException = new ServiceModelNotFoundException("test message"); + Assert.assertEquals("test message", serviceModelNotFoundException.getMessage()); + + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/Client/InfraActiveRequestExpected.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/Client/InfraActiveRequestExpected.json index 361dd9f405..45812c1c45 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/Client/InfraActiveRequestExpected.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/Client/InfraActiveRequestExpected.json @@ -22,7 +22,7 @@ "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992", "vfModuleName": null, "vfModuleModelName": "vSAMP10aDEV::base::module-0", - "aicCloudRegion": "mtn6", + "cloudRegion": "mtn6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/InfraActiveRequestExpected.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/InfraActiveRequestExpected.json index 9c962e9722..b70fd4c42a 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/InfraActiveRequestExpected.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/InfraActiveRequestExpected.json @@ -22,7 +22,7 @@ "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992", "vfModuleName": null, "vfModuleModelName": "vSAMP10aDEV::base::module-0", - "aicCloudRegion": "mtn6", + "cloudRegion": "mtn6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc", diff --git a/bpmn/MSOCommonBPMN/src/test/resources/response/infraActiveRequestsResponse.json b/bpmn/MSOCommonBPMN/src/test/resources/response/infraActiveRequestsResponse.json index 3623e888e7..45812c1c45 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/response/infraActiveRequestsResponse.json +++ b/bpmn/MSOCommonBPMN/src/test/resources/response/infraActiveRequestsResponse.json @@ -22,7 +22,7 @@ "vfModuleId": "c7d527b1-7a91-49fd-b97d-1c8c0f4a7992", "vfModuleName": null, "vfModuleModelName": "vSAMP10aDEV::base::module-0", - "aicCloudRegion": "mtn6", + "cloudRegion": "mtn6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "e3b5744d-2ad1-4cdd-8390-c999a38829bc", @@ -37,4 +37,4 @@ "configurationName": null, "operationalEnvId": null, "operationalEnvName": null -}
\ No newline at end of file +} diff --git a/bpmn/mso-infrastructure-bpmn/pom.xml b/bpmn/mso-infrastructure-bpmn/pom.xml index 1ae0dd48f7..c3c26ef5e7 100644 --- a/bpmn/mso-infrastructure-bpmn/pom.xml +++ b/bpmn/mso-infrastructure-bpmn/pom.xml @@ -304,5 +304,16 @@ <version>1.7.0</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.onap.aaf.authz</groupId> + <artifactId>aaf-cadi-aaf</artifactId> + <version>2.1.9</version> + <exclusions> + <exclusion> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </exclusion> + </exclusions> + </dependency> </dependencies> </project> diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/SecurityFilters.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/SecurityFilters.java new file mode 100644 index 0000000000..bdc1c504f0 --- /dev/null +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/SoCadiFilter.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/SoCadiFilter.java new file mode 100644 index 0000000000..cb60d5d219 --- /dev/null +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.bpmn.infrastructure; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java index 1ed3214214..bcc38ec9e0 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java @@ -24,28 +24,57 @@ package org.onap.so.bpmn.infrastructure; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService", - "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify") - .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); - } + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService", + "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify") + .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; } + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } + }; + } } diff --git a/bpmn/mso-infrastructure-bpmn/src/main/resources/application-aaf.yaml b/bpmn/mso-infrastructure-bpmn/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/bpmn/mso-infrastructure-bpmn/src/main/resources/application-aaf.yaml diff --git a/bpmn/mso-infrastructure-bpmn/src/main/resources/application-basic.yaml b/bpmn/mso-infrastructure-bpmn/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/bpmn/mso-infrastructure-bpmn/src/main/resources/application-basic.yaml diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignPnfBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignPnfBB.bpmn new file mode 100644 index 0000000000..f9c5d0cdb3 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignPnfBB.bpmn @@ -0,0 +1,137 @@ +<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="Definitions_1a52v2f" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="3.5.0"> + <bpmn:collaboration id="Collaboration_0go8wi3"> + <bpmn:participant id="Participant_1dwc5st" name="SO Assign PNF" processRef="AssignPnfBB" /> + <bpmn:participant id="Participant_0gycee4" name="AAI" /> + <bpmn:messageFlow id="MessageFlow_0xh6bkn" sourceRef="CreatePnfEntryInAai" targetRef="Participant_0gycee4" /> + <bpmn:messageFlow id="MessageFlow_0cnehf5" sourceRef="Participant_0gycee4" targetRef="CheckAaiForPnfCorrelationId" /> + <bpmn:messageFlow id="MessageFlow_1e1pjve" sourceRef="CheckAaiForPnfCorrelationId" targetRef="Participant_0gycee4" /> + </bpmn:collaboration> + <bpmn:process id="AssignPnfBB" name="AssignPnfBB" isExecutable="true"> + <bpmn:startEvent id="AssignPnf_StartEvent"> + <bpmn:outgoing>SequenceFlow_1fu9o4x</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:serviceTask id="CheckAaiForPnfCorrelationId" name="Check AAI for pnf_correlation_id" camunda:delegateExpression="${CheckAaiForPnfCorrelationIdDelegate}"> + <bpmn:incoming>SequenceFlow_02j05kk</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_081rs5d</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:exclusiveGateway id="DoesAaiContainInfoAboutPnf" name="Does AAI contain info about pnf?"> + <bpmn:incoming>SequenceFlow_081rs5d</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0fn5kgz</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_1ewfz8r</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:serviceTask id="CreatePnfEntryInAai" name="Create Pnf entry in AAI" camunda:delegateExpression="${CreatePnfEntryInAaiDelegate}"> + <bpmn:incoming>SequenceFlow_0fn5kgz</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0l6rtzy</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:endEvent id="AaiEntryExists" name="AAI entry exists"> + <bpmn:incoming>SequenceFlow_1ewfz8r</bpmn:incoming> + <bpmn:incoming>SequenceFlow_0l6rtzy</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_081rs5d" sourceRef="CheckAaiForPnfCorrelationId" targetRef="DoesAaiContainInfoAboutPnf" /> + <bpmn:sequenceFlow id="SequenceFlow_0fn5kgz" name="No" sourceRef="DoesAaiContainInfoAboutPnf" targetRef="CreatePnfEntryInAai"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{!aaiContainsInfoAboutPnf}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_1ewfz8r" name="Yes " sourceRef="DoesAaiContainInfoAboutPnf" targetRef="AaiEntryExists"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{aaiContainsInfoAboutPnf}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:sequenceFlow id="SequenceFlow_0l6rtzy" sourceRef="CreatePnfEntryInAai" targetRef="AaiEntryExists" /> + <bpmn:serviceTask id="CheckInputs" name="Check Inputs" camunda:delegateExpression="${AssignPnfInputsCheckerDelegate}"> + <bpmn:incoming>SequenceFlow_1fu9o4x</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_02j05kk</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_02j05kk" sourceRef="CheckInputs" targetRef="CheckAaiForPnfCorrelationId" /> + <bpmn:sequenceFlow id="SequenceFlow_1fu9o4x" sourceRef="AssignPnf_StartEvent" targetRef="CheckInputs" /> + <bpmn:textAnnotation id="TextAnnotation_184cxp4"> + <bpmn:text>Inputs: + - pnfCorrelationId - String + - uuid - String</bpmn:text> + </bpmn:textAnnotation> + <bpmn:association id="Association_1le3nwi" sourceRef="AssignPnf_StartEvent" targetRef="TextAnnotation_184cxp4" /> + </bpmn:process> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Collaboration_0go8wi3"> + <bpmndi:BPMNShape id="Participant_1dwc5st_di" bpmnElement="Participant_1dwc5st" isHorizontal="true"> + <dc:Bounds x="160" y="80" width="1100" height="390" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="Participant_0gycee4_di" bpmnElement="Participant_0gycee4" isHorizontal="true"> + <dc:Bounds x="590" y="570" width="502" height="60" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_1ix8822_di" bpmnElement="CreatePnfEntryInAai"> + <dc:Bounds x="920" y="247" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ExclusiveGateway_1l92fkt_di" bpmnElement="DoesAaiContainInfoAboutPnf" isMarkerVisible="true"> + <dc:Bounds x="795" y="262" width="50" height="50" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="777" y="322" width="85" height="27" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_0ebur3y_di" bpmnElement="CheckAaiForPnfCorrelationId"> + <dc:Bounds x="640" y="247" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="StartEvent_1g3euow_di" bpmnElement="AssignPnf_StartEvent"> + <dc:Bounds x="219" y="269" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="TextAnnotation_184cxp4_di" bpmnElement="TextAnnotation_184cxp4"> + <dc:Bounds x="236" y="150" width="243" height="53" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_081rs5d_di" bpmnElement="SequenceFlow_081rs5d"> + <di:waypoint x="740" y="287" /> + <di:waypoint x="795" y="287" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0fn5kgz_di" bpmnElement="SequenceFlow_0fn5kgz"> + <di:waypoint x="845" y="287" /> + <di:waypoint x="920" y="287" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="854" y="290" width="15" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="MessageFlow_0xh6bkn_di" bpmnElement="MessageFlow_0xh6bkn"> + <di:waypoint x="970" y="327" /> + <di:waypoint x="970" y="570" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="MessageFlow_0cnehf5_di" bpmnElement="MessageFlow_0cnehf5"> + <di:waypoint x="710" y="570" /> + <di:waypoint x="710" y="327" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="MessageFlow_1e1pjve_di" bpmnElement="MessageFlow_1e1pjve"> + <di:waypoint x="671" y="327" /> + <di:waypoint x="671" y="570" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="Association_1le3nwi_di" bpmnElement="Association_1le3nwi"> + <di:waypoint x="237" y="269" /> + <di:waypoint x="237" y="203" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_1wfgsdz_di" bpmnElement="AaiEntryExists"> + <dc:Bounds x="1152" y="269" width="36" height="36" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1133" y="312" width="77" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1ewfz8r_di" bpmnElement="SequenceFlow_1ewfz8r"> + <di:waypoint x="820" y="262" /> + <di:waypoint x="820" y="170" /> + <di:waypoint x="1170" y="170" /> + <di:waypoint x="1170" y="269" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="822" y="240" width="19" height="40" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0l6rtzy_di" bpmnElement="SequenceFlow_0l6rtzy"> + <di:waypoint x="1020" y="287" /> + <di:waypoint x="1152" y="287" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ServiceTask_0tv92eb_di" bpmnElement="CheckInputs"> + <dc:Bounds x="400" y="247" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_02j05kk_di" bpmnElement="SequenceFlow_02j05kk"> + <di:waypoint x="500" y="287" /> + <di:waypoint x="640" y="287" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_1fu9o4x_di" bpmnElement="SequenceFlow_1fu9o4x"> + <di:waypoint x="255" y="287" /> + <di:waypoint x="400" y="287" /> + </bpmndi:BPMNEdge> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/AssignPnfInputsCheckerDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/AssignPnfInputsCheckerDelegate.java new file mode 100644 index 0000000000..9176948288 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/AssignPnfInputsCheckerDelegate.java @@ -0,0 +1,40 @@ +package org.onap.so.bpmn.infrastructure.pnf.delegate; + +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_UUID; +import com.google.common.base.Strings; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.springframework.stereotype.Component; + +@Component +public class AssignPnfInputsCheckerDelegate implements JavaDelegate { + + public static final String UUID_REGEX = + "(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[1-5]{1}[0-9a-f]{3}-[89ab]{1}[0-9a-f]{3}-[0-9a-f]{12}$"; + + @Override + public void execute(DelegateExecution execution) { + validatePnfCorrelationId(execution); + validatePnfUuid(execution); + } + + private void validatePnfCorrelationId(DelegateExecution execution) { + String pnfCorrelationId = (String) execution.getVariable(PNF_CORRELATION_ID); + if (Strings.isNullOrEmpty(pnfCorrelationId)) { + new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, + "pnfCorrelationId variable not defined"); + } + } + + private void validatePnfUuid(DelegateExecution execution) { + String pnfUuid = (String) execution.getVariable(PNF_UUID); + if (Strings.isNullOrEmpty(pnfUuid)) { + new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, "pnfUuid variable not defined"); + } + if (!pnfUuid.matches(UUID_REGEX)) { + new ExceptionUtil().buildAndThrowWorkflowException(execution, 9999, "pnfUuid is not a valid UUID"); + } + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java index 1ed3214214..58e58464e1 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/WebSecurityConfigImpl.java @@ -24,28 +24,46 @@ package org.onap.so.bpmn.infrastructure; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; +@Configuration @EnableWebSecurity public class WebSecurityConfigImpl extends WebSecurityConfig { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService", - "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify") - .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); - } + @Bean + @Profile("test") + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/async/services/**", "/workflow/services/*", "/SDNCAdapterCallbackService", + "/WorkflowMessage", "/vnfAdapterNotify", "/vnfAdapterRestNotify") + .hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and().httpBasic(); + } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); - } + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + + }; + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/AssignPnfInputsCheckerDelegateTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/AssignPnfInputsCheckerDelegateTest.java new file mode 100644 index 0000000000..a562da490b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/AssignPnfInputsCheckerDelegateTest.java @@ -0,0 +1,52 @@ +package org.onap.so.bpmn.infrastructure.pnf.delegate; + +import org.apache.commons.lang3.StringUtils; +import org.camunda.bpm.engine.delegate.BpmnError; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.junit.Before; +import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.PnfInputCheckersTestUtils.DelegateExecutionBuilder; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.PnfInputCheckersTestUtils.RESERVED_UUID; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.PnfInputCheckersTestUtils.VALID_UUID; + +public class AssignPnfInputsCheckerDelegateTest { + + private DelegateExecutionBuilder delegateExecutionBuilder; + private AssignPnfInputsCheckerDelegate testedObject; + private DelegateExecution execution; + + @Before + public void setUp() { + testedObject = new AssignPnfInputsCheckerDelegate(); + delegateExecutionBuilder = new DelegateExecutionBuilder(); + } + + @Test + public void shouldThrowException_whenPnfCorrelationIdNotSet() { + execution = delegateExecutionBuilder.setPnfCorrelationId(null).setPnfUuid(VALID_UUID).build(); + assertThatSutExecutionThrowsExceptionOfInstance(BpmnError.class); + } + + @Test + public void shouldThrowException_whenPnfUuidIsNotSet() { + execution = delegateExecutionBuilder.setPnfUuid(null).build(); + assertThatSutExecutionThrowsExceptionOfInstance(BpmnError.class); + } + + @Test + public void shouldThrowException_whenPnfUuidIsEmptyString() { + execution = delegateExecutionBuilder.setPnfUuid(StringUtils.EMPTY).build(); + assertThatSutExecutionThrowsExceptionOfInstance(BpmnError.class); + } + + @Test + public void shouldThrowException_whenPnfUuidIsReservedUuid() { + execution = delegateExecutionBuilder.setPnfUuid(RESERVED_UUID).build(); + assertThatSutExecutionThrowsExceptionOfInstance(BpmnError.class); + } + + private void assertThatSutExecutionThrowsExceptionOfInstance(Class<?> type) { + assertThatThrownBy(() -> testedObject.execute(execution)).isInstanceOf(type); + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfInputCheckersTestUtils.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfInputCheckersTestUtils.java new file mode 100644 index 0000000000..c1c7f06d4e --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfInputCheckersTestUtils.java @@ -0,0 +1,46 @@ +package org.onap.so.bpmn.infrastructure.pnf.delegate; + +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import java.util.UUID; + + +public class PnfInputCheckersTestUtils { + + static final String PNF_ENTRY_NOTIFICATION_TIMEOUT = "P1D"; + static final String VALID_UUID = UUID.nameUUIDFromBytes("testUuid".getBytes()).toString(); + static final String RESERVED_UUID = new UUID(0, 0).toString(); + private static final String DEFAULT_SERVICE_INSTANCE_ID = "da7d07d9-b71c-4128-809d-2ec01c807169"; + private static final String DEFAULT_PNF_CORRELATION_ID = "testPnfCorrelationId"; + + static class DelegateExecutionBuilder { + private String pnfCorrelationId = DEFAULT_PNF_CORRELATION_ID; + private String pnfUuid = VALID_UUID; + private String serviceInstanceId = DEFAULT_SERVICE_INSTANCE_ID; + + public DelegateExecutionBuilder setPnfCorrelationId(String pnfCorrelationId) { + this.pnfCorrelationId = pnfCorrelationId; + return this; + } + + public DelegateExecutionBuilder setPnfUuid(String pnfUuid) { + this.pnfUuid = pnfUuid; + return this; + } + + public DelegateExecutionBuilder setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + return this; + } + + public DelegateExecution build() { + DelegateExecution execution = new DelegateExecutionFake(); + execution.setVariable("testProcessKey", "testProcessKeyValue"); + execution.setVariable(PNF_CORRELATION_ID, this.pnfCorrelationId); + execution.setVariable(PNF_UUID, this.pnfUuid); + execution.setVariable(SERVICE_INSTANCE_ID, this.serviceInstanceId); + return execution; + } + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java index bd60fbe38c..b9f73f3f0e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java @@ -372,6 +372,7 @@ public class AAICreateTasks { logger.info("VolumeGroup not found. Skipping Connect between VfModule and VolumeGroup"); } if (volumeGroup != null) { + logger.debug("Connecting VfModule to VolumGroup"); aaiVfModuleResources.connectVfModuleToVolumeGroup(vnf, vfModule, volumeGroup, execution.getGeneralBuildingBlock().getCloudRegion()); } 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 b5b1f5db2f..99ba35232c 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 @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Copyright (C) 2019 Nokia. + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -54,6 +56,7 @@ import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.DuplicateNameException; +import org.onap.so.bpmn.servicedecomposition.tasks.exceptions.MultipleObjectsFoundException; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.entities.AAIResultWrapper; @@ -62,6 +65,7 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.client.exception.ExceptionBuilder; import org.onap.so.client.orchestration.AAIConfigurationResources; +import org.onap.so.client.orchestration.AAIEntityNotFoundException; import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; @@ -71,17 +75,7 @@ import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.macro.NorthBoundRequest; import org.onap.so.db.catalog.beans.macro.OrchestrationFlow; import org.onap.so.db.catalog.client.CatalogDbClient; -import org.onap.so.serviceinstancebeans.CloudConfiguration; -import org.onap.so.serviceinstancebeans.ModelInfo; -import org.onap.so.serviceinstancebeans.ModelType; -import org.onap.so.serviceinstancebeans.Networks; -import org.onap.so.serviceinstancebeans.RelatedInstance; -import org.onap.so.serviceinstancebeans.RequestDetails; -import org.onap.so.serviceinstancebeans.RequestInfo; -import org.onap.so.serviceinstancebeans.Service; -import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; -import org.onap.so.serviceinstancebeans.VfModules; -import org.onap.so.serviceinstancebeans.Vnfs; +import org.onap.so.serviceinstancebeans.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -102,6 +96,7 @@ public class WorkflowAction { private static final String VNF_TYPE = "vnfType"; private static final String SERVICE = "Service"; private static final String VNF = "Vnf"; + private static final String PNF = "Pnf"; private static final String VFMODULE = "VfModule"; private static final String VOLUMEGROUP = "VolumeGroup"; private static final String NETWORK = "Network"; @@ -109,6 +104,8 @@ public class WorkflowAction { private static final String CONFIGURATION = "Configuration"; private static final String ASSIGNINSTANCE = "assignInstance"; private static final String CREATEINSTANCE = "createInstance"; + private static final String REPLACEINSTANCE = "replaceInstance"; + private static final String REPLACEINSTANCERETAINASSIGNMENTS = "replaceInstanceRetainAssignments"; private static final String USERPARAMSERVICE = "service"; private static final String SUPPORTEDTYPES = "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups"; @@ -128,6 +125,8 @@ public class WorkflowAction { private static final String NAME_EXISTS_WITH_DIFF_PARENT = "(%s) id (%s) and different parent relationship"; private static final String CREATENETWORKBB = "CreateNetworkBB"; private static final String ACTIVATENETWORKBB = "ActivateNetworkBB"; + private static final String VOLUMEGROUP_DELETE_PATTERN = "(Un|De)(.*)Volume(.*)"; + private static final String VOLUMEGROUP_CREATE_PATTERN = "(A|C)(.*)Volume(.*)"; @Autowired protected BBInputSetup bbInputSetup; @@ -184,7 +183,14 @@ public class WorkflowAction { execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, true); ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class); RequestDetails requestDetails = sIRequest.getRequestDetails(); - execution.setVariable("suppressRollback", isSuppressRollback(requestDetails.getRequestInfo())); + boolean suppressRollback = false; + try { + suppressRollback = requestDetails.getRequestInfo().getSuppressRollback(); + } catch (Exception ex) { + logger.error("Exception in getSuppressRollback", ex); + suppressRollback = false; + } + execution.setVariable("suppressRollback", suppressRollback); boolean isResume = false; if (isUriResume(uri)) { isResume = true; @@ -253,6 +259,18 @@ public class WorkflowAction { } orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION)) .collect(Collectors.toList()); + + if ((requestAction.equalsIgnoreCase(REPLACEINSTANCE) + || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS)) + && resourceType.equals(WorkflowType.VFMODULE)) { + logger.debug("Build a BB list for replacing BB modules"); + orchFlows = getVfModuleReplaceBuildingBlocks( + new ConfigBuildingBlocksDataObject().setsIRequest(sIRequest).setOrchFlows(orchFlows) + .setRequestId(requestId).setResourceKey(resourceKey).setApiVersion(apiVersion) + .setResourceId(resourceId).setRequestAction(requestAction).setaLaCarte(aLaCarte) + .setVnfType(vnfType).setWorkflowResourceIds(workflowResourceIds) + .setRequestDetails(requestDetails).setExecution(execution)); + } for (OrchestrationFlow orchFlow : orchFlows) { ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, @@ -263,7 +281,8 @@ public class WorkflowAction { boolean foundRelated = false; boolean containsService = false; if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) { - // SERVICE-MACRO-ASSIGN will always get user params with a + // SERVICE-MACRO-ASSIGN will always get user params with + // a // service. if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) { List<Map<String, Object>> userParams = @@ -281,7 +300,8 @@ public class WorkflowAction { "Service-Macro-Assign request details must contain user params with a service"); } } else if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(CREATEINSTANCE)) { - // SERVICE-MACRO-CREATE will get user params with a service, + // SERVICE-MACRO-CREATE will get user params with a + // service, // a service with a network, a service with a // networkcollection, OR an empty service. // If user params is just a service or null and macro @@ -310,7 +330,8 @@ public class WorkflowAction { || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) { // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and // SERVICE-MACRO-DELETE - // Will never get user params with service, macro will have + // 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); } else if (resourceType == WorkflowType.SERVICE @@ -335,14 +356,20 @@ public class WorkflowAction { orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner, serviceType); } + boolean vnfReplace = false; + if (resourceType.equals(WorkflowType.VNF) && ("replaceInstance".equalsIgnoreCase(requestAction) + || "replaceInstanceRetainAssignments".equalsIgnoreCase(requestAction))) { + vnfReplace = true; + } flowsToExecute = buildExecuteBuildingBlockList(orchFlows, resourceCounter, requestId, apiVersion, - resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails); + resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, vnfReplace); if (!resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) .collect(Collectors.toList()).isEmpty()) { logger.info("Sorting for Vlan Tagging"); flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction); } - // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE + // 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())) @@ -359,7 +386,8 @@ public class WorkflowAction { } } } - // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified, + // If the user set "Homing_Solution" to "none", disable homing, else + // if "Homing_Solution" is specified, // enable it. if (sIRequest.getRequestDetails().getRequestParameters() != null && sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) { @@ -397,7 +425,7 @@ public class WorkflowAction { execution.setVariable("isRollbackComplete", false); } catch (Exception ex) { - buildAndThrowException(execution, "Exception in create execution list. " + ex.getMessage(), ex); + buildAndThrowException(execution, "Exception in execution list. ", ex); } } @@ -473,7 +501,8 @@ public class WorkflowAction { return false; } - protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) { + protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) + throws Exception { List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>(); List<OrchestrationFlow> result = dataObj.getOrchFlows().stream() @@ -482,8 +511,17 @@ public class WorkflowAction { String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId(); String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId(); - String vfModuleCustomizationUUID = - bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId).getModelCustomizationId(); + String vfModuleCustomizationUUID = ""; + org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId); + + if (aaiVfModule == null) { + logger.error("No matching VfModule is found in Generic-Vnf in AAI for vnfId: {} and vfModuleId : {}", vnfId, + vfModuleId); + throw new AAIEntityNotFoundException("No matching VfModule is found in Generic-Vnf in AAI for vnfId: " + + vnfId + " and vfModuleId : " + vfModuleId); + } else { + vfModuleCustomizationUUID = aaiVfModule.getModelCustomizationId(); + } List<org.onap.aai.domain.yang.Vnfc> vnfcs = getRelatedResourcesInVfModule(vnfId, vfModuleId, org.onap.aai.domain.yang.Vnfc.class, AAIObjectType.VNFC); @@ -520,6 +558,68 @@ public class WorkflowAction { return flowsToExecuteConfigs; } + protected List<OrchestrationFlow> getVfModuleReplaceBuildingBlocks(ConfigBuildingBlocksDataObject dataObj) + throws Exception { + + List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>(); + + String vnfId = dataObj.getWorkflowResourceIds().getVnfId(); + String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId(); + + logger.debug("BUILDING REPLACE LIST"); + + boolean volumeGroupExisted = false; + boolean volumeGroupWillExist = false; + boolean keepVolumeGroup = false; + + boolean rebuildVolumeGroups = false; + if (dataObj.getRequestDetails().getRequestParameters() != null + && dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups() != null) { + rebuildVolumeGroups = + dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups().booleanValue(); + } + + Optional<VolumeGroup> volumeGroupFromVfModule = + bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, vfModuleId); + if (volumeGroupFromVfModule.isPresent()) { + String volumeGroupId = volumeGroupFromVfModule.get().getVolumeGroupId(); + logger.debug("Volume group id of the existing volume group is: " + volumeGroupId); + volumeGroupExisted = true; + dataObj.getWorkflowResourceIds().setVolumeGroupId(volumeGroupId); + } + + List<OrchestrationFlow> orchFlows = dataObj.getOrchFlows(); + VfModuleCustomization vfModuleCustomization = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID( + dataObj.getRequestDetails().getModelInfo().getModelCustomizationUuid()); + if (vfModuleCustomization != null && vfModuleCustomization.getVfModule() != null + && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null + && vfModuleCustomization.getVolumeHeatEnv() != null) { + volumeGroupWillExist = true; + if (!volumeGroupExisted) { + String newVolumeGroupId = UUID.randomUUID().toString(); + dataObj.getWorkflowResourceIds().setVolumeGroupId(newVolumeGroupId); + logger.debug("newVolumeGroupId: " + newVolumeGroupId); + } + } + + if (volumeGroupExisted && volumeGroupWillExist && !rebuildVolumeGroups) { + keepVolumeGroup = true; + } + + if (!volumeGroupExisted || keepVolumeGroup) { + logger.debug("Filtering out deletion of volume groups"); + orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_DELETE_PATTERN)) + .collect(Collectors.toList()); + } + if (!volumeGroupWillExist || keepVolumeGroup) { + logger.debug("Filtering out creation of volume groups"); + orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_CREATE_PATTERN)) + .collect(Collectors.toList()); + } + + return orchFlows; + } + protected String getVnfcNameForConfiguration(org.onap.aai.domain.yang.Configuration configuration) { AAIResultWrapper wrapper = new AAIResultWrapper(configuration); Optional<Relationships> relationshipsOp = wrapper.getRelationships(); @@ -620,6 +720,8 @@ public class WorkflowAction { 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) { @@ -1063,6 +1165,13 @@ public class WorkflowAction { } } } + if (validate.getResources().getPnfs() != null) { + for (Pnfs pnf : validate.getResources().getPnfs()) { + resourceCounter.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, @@ -1169,142 +1278,21 @@ public class WorkflowAction { RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws Exception { try { if ("SERVICE".equalsIgnoreCase(type.toString())) { - // Service name verification based upon name + model-version-id - // + service-type + global-customer-id per requirements - String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId(); - String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType(); - if (instanceName != null) { - Optional<ServiceInstance> serviceInstanceAAI = - bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName); - if (serviceInstanceAAI.isPresent()) { - if (serviceInstanceAAI.get().getModelVersionId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelVersionId())) { - return serviceInstanceAAI.get().getServiceInstanceId(); - } else { - throw new DuplicateNameException(SERVICE_INSTANCE, - String.format(NAME_EXISTS_WITH_DIFF_VERSION_ID, instanceName, - reqDetails.getModelInfo().getModelVersionId())); - } - } else { - ServiceInstances aaiServiceInstances = - bbInputSetupUtils.getAAIServiceInstancesGloballyByName(instanceName); - if (aaiServiceInstances != null) { - if (aaiServiceInstances.getServiceInstance() != null - && !aaiServiceInstances.getServiceInstance().isEmpty()) { - if (aaiServiceInstances.getServiceInstance().size() > 1) { - throw new DuplicateNameException(SERVICE_INSTANCE, - String.format(NAME_EXISTS_MULTIPLE, instanceName)); - } else { - ServiceInstance si = - aaiServiceInstances.getServiceInstance().stream().findFirst().get(); - Map<String, String> keys = - bbInputSetupUtils.getURIKeysFromServiceInstance(si.getServiceInstanceId()); - - throw new DuplicateNameException(SERVICE_INSTANCE, - String.format(NAME_EXISTS_WITH_DIFF_COMBINATION, instanceName, - keys.get("global-customer-id"), keys.get("service-type"), - si.getModelVersionId())); - } - } - } - } - } + return validateServiceResourceIdInAAI(generatedResourceId, instanceName, reqDetails); } else if ("NETWORK".equalsIgnoreCase(type.toString())) { - Optional<L3Network> network = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance( - workflowResourceIds.getServiceInstanceId(), instanceName); - if (network.isPresent()) { - if (network.get().getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return network.get().getNetworkId(); - } else { - throw new DuplicateNameException("l3Network", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - network.get().getModelCustomizationId())); - } - } - - if (bbInputSetupUtils.existsAAINetworksGloballyByName(instanceName)) { - throw new DuplicateNameException("l3Network", String.format(NAME_EXISTS_WITH_DIFF_PARENT, - instanceName, workflowResourceIds.getServiceInstanceId())); - } - + return validateNetworkResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } else if ("VNF".equalsIgnoreCase(type.toString())) { - Optional<GenericVnf> vnf = bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance( - workflowResourceIds.getServiceInstanceId(), instanceName); - if (vnf.isPresent()) { - if (vnf.get().getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return vnf.get().getVnfId(); - } else { - throw new DuplicateNameException("generic-vnf", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - vnf.get().getModelCustomizationId())); - } - } - GenericVnfs vnfs = bbInputSetupUtils.getAAIVnfsGloballyByName(instanceName); - if (vnfs != null) { - throw new DuplicateNameException("generic-vnf", String.format(NAME_EXISTS_WITH_DIFF_PARENT, - instanceName, vnfs.getGenericVnf().get(0).getVnfId())); - } + return validateVnfResourceIdInAAI(generatedResourceId, instanceName, reqDetails, workflowResourceIds); } else if ("VFMODULE".equalsIgnoreCase(type.toString())) { - GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId()); - if (vnf != null && vnf.getVfModules() != null) { - for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) { - if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) { - if (vfModule.getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return vfModule.getVfModuleId(); - } else { - throw new DuplicateNameException("vfModule", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - reqDetails.getModelInfo().getModelCustomizationId())); - } - } - } - } + return validateVfModuleResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } else if ("VOLUMEGROUP".equalsIgnoreCase(type.toString())) { - GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId()); - Optional<VolumeGroup> volumeGroup = bbInputSetupUtils - .getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName); - if (volumeGroup.isPresent()) { - if (vnf.getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return volumeGroup.get().getVolumeGroupId(); - } else { - throw new DuplicateNameException("volumeGroup", volumeGroup.get().getVolumeGroupName()); - } - } - if (vnf != null && vnf.getVfModules() != null) { - for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) { - Optional<VolumeGroup> volumeGroupFromVfModule = - bbInputSetupUtils.getRelatedVolumeGroupByNameFromVfModule(vnf.getVnfId(), - vfModule.getVfModuleId(), instanceName); - if (volumeGroupFromVfModule.isPresent()) { - if (vnf.getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return volumeGroupFromVfModule.get().getVolumeGroupId(); - } else { - throw new DuplicateNameException("volumeGroup", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - volumeGroupFromVfModule.get().getModelCustomizationId())); - } - } - } - } + return validateVolumeGroupResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } else if ("CONFIGURATION".equalsIgnoreCase(type.toString())) { - Optional<org.onap.aai.domain.yang.Configuration> configuration = - bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance( - workflowResourceIds.getServiceInstanceId(), instanceName); - if (configuration.isPresent()) { - if (configuration.get().getModelCustomizationId() - .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { - return configuration.get().getConfigurationId(); - } else { - throw new DuplicateNameException("configuration", - String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, - configuration.get().getConfigurationId())); - } - } + return validateConfigurationResourceIdInAAI(generatedResourceId, instanceName, reqDetails, + workflowResourceIds); } return generatedResourceId; } catch (DuplicateNameException dne) { @@ -1399,99 +1387,83 @@ public class WorkflowAction { return sortedOrchFlows; } + private void addBuildingBlockToExecuteBBList(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceList, + WorkflowType workflowType, OrchestrationFlow orchFlow, String requestId, String apiVersion, + 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(), isConfiguration))); + } + protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows, - List<Resource> resourceCounter, String requestId, String apiVersion, String resourceId, - String requestAction, boolean aLaCarte, String vnfType, WorkflowResourceIds workflowResourceIds, - RequestDetails requestDetails) { + List<Resource> resourceList, String requestId, String apiVersion, String resourceId, String requestAction, + String vnfType, WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, + boolean replaceVnf) { List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>(); for (OrchestrationFlow orchFlow : orchFlows) { if (orchFlow.getFlowName().contains(SERVICE)) { - for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType()) - .collect(Collectors.toList()).size(); i++) { + if (!replaceVnf) { workflowResourceIds.setServiceInstanceId(resourceId); - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, - resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType()) - .collect(Collectors.toList()).get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, false)); } + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.SERVICE, orchFlow, requestId, + apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, false, + false); } else if (orchFlow.getFlowName().contains(VNF)) { - for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType()) - .collect(Collectors.toList()).size(); i++) { - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, - resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType()) - .collect(Collectors.toList()).get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, false)); - } + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.VNF, orchFlow, requestId, + apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, false, + false); + } else if (orchFlow.getFlowName().contains(PNF)) { + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.PNF, orchFlow, requestId, + apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, false, + false); } else if (orchFlow.getFlowName().contains(NETWORK) && !orchFlow.getFlowName().contains(NETWORKCOLLECTION)) { - for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType()) - .collect(Collectors.toList()).size(); i++) { - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, - resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType()) - .collect(Collectors.toList()).get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, false)); - } - for (int i = 0; i < resourceCounter.stream() - .filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()).collect(Collectors.toList()) - .size(); i++) { - Resource resource = - resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()) - .collect(Collectors.toList()).get(i); - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, apiVersion, resourceId, - requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, true, - resource.getVirtualLinkKey(), false)); - } + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.NETWORK, orchFlow, requestId, + apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, false, + false); + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.VIRTUAL_LINK, orchFlow, + requestId, apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, + true, false); + } else if (orchFlow.getFlowName().contains(VFMODULE)) { List<Resource> vfModuleResourcesSorted = null; if (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE) || requestAction.equals("activateInstance")) { - vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceCounter.stream() + vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceList.stream() .filter(x -> WorkflowType.VFMODULE == x.getResourceType()).collect(Collectors.toList())); } else { - vfModuleResourcesSorted = sortVfModulesByBaseLast(resourceCounter.stream() + vfModuleResourcesSorted = sortVfModulesByBaseLast(resourceList.stream() .filter(x -> WorkflowType.VFMODULE == x.getResourceType()).collect(Collectors.toList())); } for (int i = 0; i < vfModuleResourcesSorted.size(); i++) { flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, vfModuleResourcesSorted.get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, false)); + apiVersion, resourceId, requestAction, false, vnfType, workflowResourceIds, requestDetails, + false, null, false)); } } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) { - for (int i = 0; i < resourceCounter.stream() - .filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList()) - .size(); i++) { - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, - resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()) - .collect(Collectors.toList()).get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, false)); + if (requestAction.equalsIgnoreCase(REPLACEINSTANCE) + || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS)) { + logger.debug("Replacing workflow resource id by volume group id"); + resourceId = workflowResourceIds.getVolumeGroupId(); } + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.VOLUMEGROUP, orchFlow, + requestId, apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, + false, false); } else if (orchFlow.getFlowName().contains(NETWORKCOLLECTION)) { - for (int i = 0; i < resourceCounter.stream() - .filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()) - .size(); i++) { - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, - resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()) - .collect(Collectors.toList()).get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, false)); - } + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.NETWORKCOLLECTION, orchFlow, + requestId, apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, + false, false); } else if (orchFlow.getFlowName().contains(CONFIGURATION)) { - for (int i = 0; i < resourceCounter.stream() - .filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()).collect(Collectors.toList()) - .size(); i++) { - flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, - resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()) - .collect(Collectors.toList()).get(i), - apiVersion, resourceId, requestAction, aLaCarte, vnfType, workflowResourceIds, - requestDetails, false, null, true)); - } + addBuildingBlockToExecuteBBList(flowsToExecute, resourceList, WorkflowType.CONFIGURATION, orchFlow, + requestId, apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, + false, true); } else { flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, null, apiVersion, resourceId, - requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false)); + requestAction, false, vnfType, workflowResourceIds, requestDetails, false, null, false)); } } return flowsToExecute; @@ -1503,6 +1475,11 @@ public class WorkflowAction { boolean isVirtualLink, String virtualLinkKey, boolean isConfiguration) { ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock(); BuildingBlock buildingBlock = new BuildingBlock(); + + Optional.ofNullable(orchFlow.getBpmnAction()).ifPresent(action -> buildingBlock.setBpmnAction(action)); + Optional.ofNullable(orchFlow.getBpmnScope()).ifPresent(scope -> buildingBlock.setBpmnScope(scope)); + + buildingBlock.setBpmnFlowName(orchFlow.getFlowName()); buildingBlock.setMsoId(UUID.randomUUID().toString()); if (resource == null) { @@ -1515,6 +1492,13 @@ public class WorkflowAction { executeBuildingBlock.setApiVersion(apiVersion); executeBuildingBlock.setaLaCarte(aLaCarte); executeBuildingBlock.setRequestAction(requestAction); + + if (resource != null + && (orchFlow.getFlowName().contains(VOLUMEGROUP) && (requestAction.equalsIgnoreCase(REPLACEINSTANCE) + || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS)))) { + logger.debug("Setting resourceId to volume group id for volume group flow on replace"); + resourceId = workflowResourceIds.getVolumeGroupId(); + } executeBuildingBlock.setResourceId(resourceId); executeBuildingBlock.setVnfType(vnfType); executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds); @@ -1627,5 +1611,151 @@ public class WorkflowAction { && (serviceInstanceId != null && serviceInstanceId.trim().length() > 1) && (bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId) != null)); } -} + protected String validateServiceResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails) throws DuplicateNameException, MultipleObjectsFoundException { + String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId(); + String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType(); + if (instanceName != null) { + Optional<ServiceInstance> serviceInstanceAAI = + bbInputSetupUtils.getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName); + if (serviceInstanceAAI.isPresent()) { + if (serviceInstanceAAI.get().getModelVersionId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelVersionId())) { + return serviceInstanceAAI.get().getServiceInstanceId(); + } else { + throw new DuplicateNameException(SERVICE_INSTANCE, String.format(NAME_EXISTS_WITH_DIFF_VERSION_ID, + instanceName, reqDetails.getModelInfo().getModelVersionId())); + } + } else { + ServiceInstances aaiServiceInstances = + bbInputSetupUtils.getAAIServiceInstancesGloballyByName(instanceName); + if (aaiServiceInstances != null) { + if (aaiServiceInstances.getServiceInstance() != null + && !aaiServiceInstances.getServiceInstance().isEmpty()) { + if (aaiServiceInstances.getServiceInstance().size() > 1) { + throw new DuplicateNameException(SERVICE_INSTANCE, + String.format(NAME_EXISTS_MULTIPLE, instanceName)); + } else { + ServiceInstance si = aaiServiceInstances.getServiceInstance().stream().findFirst().get(); + Map<String, String> keys = + bbInputSetupUtils.getURIKeysFromServiceInstance(si.getServiceInstanceId()); + + throw new DuplicateNameException(SERVICE_INSTANCE, + String.format(NAME_EXISTS_WITH_DIFF_COMBINATION, instanceName, + keys.get("global-customer-id"), keys.get("service-type"), + si.getModelVersionId())); + } + } + } + } + } + return generatedResourceId; + } + + protected String validateNetworkResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<L3Network> network = bbInputSetupUtils + .getRelatedNetworkByNameFromServiceInstance(workflowResourceIds.getServiceInstanceId(), instanceName); + if (network.isPresent()) { + if (network.get().getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return network.get().getNetworkId(); + } else { + throw new DuplicateNameException("l3Network", String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, + instanceName, network.get().getModelCustomizationId())); + } + } + if (bbInputSetupUtils.existsAAINetworksGloballyByName(instanceName)) { + throw new DuplicateNameException("l3Network", String.format(NAME_EXISTS_WITH_DIFF_PARENT, instanceName, + workflowResourceIds.getServiceInstanceId())); + } + return generatedResourceId; + } + + protected String validateVnfResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<GenericVnf> vnf = bbInputSetupUtils + .getRelatedVnfByNameFromServiceInstance(workflowResourceIds.getServiceInstanceId(), instanceName); + if (vnf.isPresent()) { + if (vnf.get().getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return vnf.get().getVnfId(); + } else { + throw new DuplicateNameException("generic-vnf", String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, + instanceName, vnf.get().getModelCustomizationId())); + } + } + GenericVnfs vnfs = bbInputSetupUtils.getAAIVnfsGloballyByName(instanceName); + if (vnfs != null) { + throw new DuplicateNameException("generic-vnf", + String.format(NAME_EXISTS_WITH_DIFF_PARENT, instanceName, vnfs.getGenericVnf().get(0).getVnfId())); + } + return generatedResourceId; + } + + protected String validateVfModuleResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws DuplicateNameException { + GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId()); + if (vnf != null && vnf.getVfModules() != null) { + for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) { + if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) { + if (vfModule.getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return vfModule.getVfModuleId(); + } else { + throw new DuplicateNameException("vfModule", + String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, instanceName, + reqDetails.getModelInfo().getModelCustomizationId())); + } + } + } + } + if (bbInputSetupUtils.existsAAIVfModuleGloballyByName(instanceName)) { + throw new DuplicateNameException("vfModule", instanceName); + } + return generatedResourceId; + } + + protected String validateVolumeGroupResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<VolumeGroup> volumeGroup = + bbInputSetupUtils.getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName); + if (volumeGroup.isPresent()) { + if (volumeGroup.get().getVfModuleModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return volumeGroup.get().getVolumeGroupId(); + } else { + throw new DuplicateNameException("volumeGroup", volumeGroup.get().getVolumeGroupName()); + } + } + if (bbInputSetupUtils.existsAAIVolumeGroupGloballyByName(instanceName)) { + throw new DuplicateNameException("volumeGroup", instanceName); + } + return generatedResourceId; + } + + protected String validateConfigurationResourceIdInAAI(String generatedResourceId, String instanceName, + RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) + throws DuplicateNameException, MultipleObjectsFoundException { + Optional<org.onap.aai.domain.yang.Configuration> configuration = + bbInputSetupUtils.getRelatedConfigurationByNameFromServiceInstance( + workflowResourceIds.getServiceInstanceId(), instanceName); + if (configuration.isPresent()) { + if (configuration.get().getModelCustomizationId() + .equalsIgnoreCase(reqDetails.getModelInfo().getModelCustomizationId())) { + return configuration.get().getConfigurationId(); + } else { + throw new DuplicateNameException("configuration", String.format(NAME_EXISTS_WITH_DIFF_CUSTOMIZATION_ID, + instanceName, configuration.get().getConfigurationId())); + } + } + if (bbInputSetupUtils.existsAAIConfigurationGloballyByName(instanceName)) { + throw new DuplicateNameException("configuration", instanceName); + } + return generatedResourceId; + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java index 05a51797dd..1eb5cf7437 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowType.java @@ -24,6 +24,7 @@ public enum WorkflowType { SERVICE("Service"), VNF("Vnf"), + PNF("Pnf"), VFMODULE("VfModule"), VOLUMEGROUP("VolumeGroup"), NETWORK("Network"), diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java index ebebae3cce..293bcf9f0e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapper.java @@ -52,6 +52,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Component public class VnfAdapterObjectMapper { private ObjectMapper mapper = new ObjectMapper(); + private static final String ENABLE_BRIDGE = "mso.bridgeEnabled"; @PostConstruct public void init() { @@ -86,6 +87,10 @@ public class VnfAdapterObjectMapper { createVolumeGroupRequest.setMessageId(messageId); createVolumeGroupRequest.setNotificationUrl(createCallbackUrl("VNFAResponse", messageId)); + String enableBridge = getProperty(ENABLE_BRIDGE); + if (enableBridge == null || Boolean.valueOf(enableBridge)) { + createVolumeGroupRequest.setEnableBridge(true); + } return createVolumeGroupRequest; } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java index 685531e9a7..9857adbd09 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java @@ -68,6 +68,7 @@ import org.onap.sdnc.northbound.client.model.GenericResourceApiVnfresourceassign import org.onap.sdnc.northbound.client.model.GenericResourceApiVnftopologyVnfTopology; import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; +import org.onap.so.bpmn.core.UrnPropertiesReader; import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; @@ -95,6 +96,7 @@ import com.google.common.base.Joiner; public class VnfAdapterVfModuleObjectMapper { @Autowired protected VnfAdapterObjectMapperUtils vnfAdapterObjectMapperUtils; + private static final Logger logger = LoggerFactory.getLogger(VnfAdapterVfModuleObjectMapper.class); private static List<String> sdncResponseParamsToSkip = asList("vnf_id", "vf_module_id", "vnf_name", "vf_module_name"); @@ -114,6 +116,7 @@ public class VnfAdapterVfModuleObjectMapper { private static final String FLOATING_IP = "_floating_ip"; private static final String FLOATING_V6_IP = "_floating_v6_ip"; private static final String UNDERSCORE = "_"; + private static final String ENABLE_BRIDGE = "mso.bridgeEnabled"; @PostConstruct public void init() { @@ -160,6 +163,11 @@ public class VnfAdapterVfModuleObjectMapper { createVfModuleRequest .setNotificationUrl(vnfAdapterObjectMapperUtils.createCallbackUrl("VNFAResponse", messageId)); + String enableBridge = getProperty(ENABLE_BRIDGE); + if (enableBridge == null || Boolean.valueOf(enableBridge)) { + createVfModuleRequest.setEnableBridge(true); + } + return createVfModuleRequest; } @@ -916,4 +924,8 @@ public class VnfAdapterVfModuleObjectMapper { } return baseVfModule; } + + protected String getProperty(String key) { + return UrnPropertiesReader.getVariable(key); + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java index 3994208d23..5bd4df74bb 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterRestV1Test.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Copyright (C) 2018 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 @@ -20,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.adapter.network.tasks; -import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBException; @@ -31,23 +32,24 @@ import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.onap.so.adapters.nwrest.CreateNetworkRequest; import org.onap.so.adapters.nwrest.CreateNetworkResponse; +import org.onap.so.adapters.nwrest.DeleteNetworkRequest; +import org.onap.so.adapters.nwrest.DeleteNetworkResponse; import org.onap.so.adapters.nwrest.UpdateNetworkError; import org.onap.so.adapters.nwrest.UpdateNetworkRequest; import org.onap.so.adapters.nwrest.UpdateNetworkResponse; import org.onap.so.bpmn.BaseTaskTest; -import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.exception.ExceptionBuilder; -import org.onap.so.client.exception.MapperException; import org.onap.so.utils.Components; import org.onap.logging.filter.base.ONAPComponents; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -60,13 +62,22 @@ public class NetworkAdapterRestV1Test extends BaseTaskTest { @Mock ExceptionBuilder exceptionBuilder = new ExceptionBuilder(); + private static final String CREATE_NETWORK_RESPONSE = "createNetworkResponse"; + private static final String DELETE_NETWORK_RESPONSE = "deleteNetworkResponse"; + private static final String CREATE_NETWORK_ERROR = "createNetworkError"; + private static final String DELETE_NETWORK_ERROR = "deleteNetworkError"; + private static final String NET_ID_FOR_CREATE_NETWORK_RESPONSE = "netIdForCreateNetworkResponse"; + private static final String NET_ID_FOR_DELETE_NETWORK_RESPONSE = "netIdForDeleteNetworkResponse"; + private static final String CREATE_NETWORK_ERROR_MESSAGE = "createNetErrorMessage"; + private static final String DELETE_NETWORK_ERROR_MESSAGE = "deleteNetErrorMessage"; + @Before public void setup() { delegateExecution = new DelegateExecutionFake(); } @Test - public void testUnmarshalXml() throws IOException, JAXBException { + public void testUnmarshalXml() throws JAXBException { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><createNetworkResponse><messageId>ec37c121-e3ec-4697-8adf-2d7dca7044fc</messageId><networkCreated>true</networkCreated><networkFqdn>someNetworkFqdn</networkFqdn><networkId>991ec7bf-c9c4-4ac1-bb9c-4b61645bddb3</networkId><networkStackId>someStackId</networkStackId><neutronNetworkId>9c47521a-2916-4018-b2bc-71ab767497e3</neutronNetworkId><rollback><cloudId>someCloudId</cloudId><modelCustomizationUuid>b7171cdd-8b05-459b-80ef-2093150e8983</modelCustomizationUuid><msoRequest><requestId>90b32315-176e-4dab-bcf1-80eb97a1c4f4</requestId><serviceInstanceId>71e7db22-7907-4d78-8fcc-8d89d28e90be</serviceInstanceId></msoRequest><networkCreated>true</networkCreated><networkStackId>someStackId</networkStackId><networkType>SomeNetworkType</networkType><neutronNetworkId>9c47521a-2916-4018-b2bc-71ab767497e3</neutronNetworkId><tenantId>b60da4f71c1d4b35b8113d4eca6deaa1</tenantId></rollback><subnetMap><entry><key>6b381fa9-48ce-4e16-9978-d75309565bb6</key><value>bc1d5537-860b-4894-8eba-6faff41e648c</value></entry></subnetMap></createNetworkResponse>"; CreateNetworkResponse response = @@ -76,11 +87,11 @@ public class NetworkAdapterRestV1Test extends BaseTaskTest { } @Test - public void testUnmarshalXmlUpdate() throws IOException, JAXBException { + public void testUnmarshalXmlUpdate() throws JAXBException { UpdateNetworkResponse expectedResponse = new UpdateNetworkResponse(); expectedResponse.setMessageId("ec100bcc-2659-4aa4-b4d8-3255715c2a51"); expectedResponse.setNetworkId("80de31e3-cc78-4111-a9d3-5b92bf0a39eb"); - Map<String, String> subnetMap = new HashMap<String, String>(); + Map<String, String> subnetMap = new HashMap<>(); subnetMap.put("95cd8437-25f1-4238-8720-cbfe7fa81476", "d8d16606-5d01-4822-b160-9a0d257303e0"); expectedResponse.setSubnetMap(subnetMap); String xml = @@ -91,7 +102,7 @@ public class NetworkAdapterRestV1Test extends BaseTaskTest { } @Test - public void processCallbackTest() throws MapperException, BadResponseException, IOException { + public void processCallbackTest() { UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest(); UpdateNetworkResponse updateNetworkResponse = new UpdateNetworkResponse(); updateNetworkResponse.setMessageId("messageId"); @@ -105,7 +116,7 @@ public class NetworkAdapterRestV1Test extends BaseTaskTest { } @Test - public void processCallbackErrorTest() throws MapperException, BadResponseException, IOException { + public void processCallbackErrorTest() { UpdateNetworkRequest updateNetworkRequest = new UpdateNetworkRequest(); UpdateNetworkError updateNetworkResponse = new UpdateNetworkError(); updateNetworkResponse.setMessageId("messageId"); @@ -125,4 +136,67 @@ public class NetworkAdapterRestV1Test extends BaseTaskTest { verify(exceptionBuilder, times(1)).buildAndThrowWorkflowException(any(DelegateExecution.class), eq(7000), eq("test error message"), eq(Components.OPENSTACK)); } + + @Test + public void processCallback_createNetworkResponse() { + delegateExecution.setVariable("networkAdapterRequest", new CreateNetworkRequest()); + delegateExecution.setVariable("NetworkAResponse_MESSAGE", + createNetworkResponse(CREATE_NETWORK_RESPONSE, NET_ID_FOR_CREATE_NETWORK_RESPONSE)); + networkAdapterRestV1Tasks.processCallback(delegateExecution); + + Object result = delegateExecution.getVariable("createNetworkResponse"); + assertTrue(result instanceof CreateNetworkResponse); + CreateNetworkResponse createNetworkResponse = (CreateNetworkResponse) result; + assertEquals(createNetworkResponse.getNetworkId(), NET_ID_FOR_CREATE_NETWORK_RESPONSE); + } + + @Test + public void processCallback_deleteNetworkResponse() { + delegateExecution.setVariable("networkAdapterRequest", new DeleteNetworkRequest()); + delegateExecution.setVariable("NetworkAResponse_MESSAGE", + createNetworkResponse(DELETE_NETWORK_RESPONSE, NET_ID_FOR_DELETE_NETWORK_RESPONSE)); + networkAdapterRestV1Tasks.processCallback(delegateExecution); + + Object result = delegateExecution.getVariable("deleteNetworkResponse"); + assertTrue(result instanceof DeleteNetworkResponse); + DeleteNetworkResponse deleteNetworkResponse = (DeleteNetworkResponse) result; + assertEquals(deleteNetworkResponse.getNetworkId(), NET_ID_FOR_DELETE_NETWORK_RESPONSE); + } + + @Test + public void processCallback_createNetworkError() { + try { + delegateExecution.setVariable("networkAdapterRequest", new CreateNetworkRequest()); + delegateExecution.setVariable("NetworkAResponse_MESSAGE", + createNetworkError(CREATE_NETWORK_ERROR, CREATE_NETWORK_ERROR_MESSAGE)); + networkAdapterRestV1Tasks.processCallback(delegateExecution); + } catch (Exception e) { + assertEquals(e.getMessage(), CREATE_NETWORK_ERROR_MESSAGE); + } + } + + @Test + public void processCallback_deleteNetworkError() { + try { + delegateExecution.setVariable("networkAdapterRequest", new DeleteNetworkRequest()); + delegateExecution.setVariable("NetworkAResponse_MESSAGE", + createNetworkError(DELETE_NETWORK_ERROR, DELETE_NETWORK_ERROR_MESSAGE)); + networkAdapterRestV1Tasks.processCallback(delegateExecution); + } catch (Exception e) { + assertEquals(e.getMessage(), DELETE_NETWORK_ERROR_MESSAGE); + } + } + + private String createNetworkResponse(String networkResponseType, String networkId) { + + return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><" + networkResponseType + "><networkId>" + + networkId + "</networkId></" + networkResponseType + ">"; + } + + private String createNetworkError(String networkErrorType, String message) { + + return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><" + networkErrorType + "><message>" + + message + "</message></" + networkErrorType + ">"; + } + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java index cb5ffd6fa7..ed3ee0a3a1 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionTest.java @@ -83,6 +83,7 @@ import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.aai.entities.Relationships; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.orchestration.AAIEntityNotFoundException; import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResource; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; @@ -124,6 +125,16 @@ public class WorkflowActionTest extends BaseTaskTest { private String RESOURCE_PATH = "src/test/resources/__files/"; + private List<OrchestrationFlow> replaceVfModuleOrchFlows = + createFlowList("DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVFModuleBB", "UnassignVolumeGroupBB", "AssignVolumeGroupBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "CreateVolumeGroupBB", + "ActivateVolumeGroupBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + private List<OrchestrationFlow> replaceRetainAssignmentsVfModuleOrchFlows = createFlowList("DeactivateVfModuleBB", + "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", "DeleteVolumeGroupBB", "UnassignVolumeGroupBB", + "AssignVolumeGroupBB", "ChangeModelVfModuleBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + @Before public void before() throws Exception { execution = new DelegateExecutionFake(); @@ -927,6 +938,9 @@ public class WorkflowActionTest extends BaseTaskTest { "CreateVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ActivateVfModuleBB", "AssignFabricConfigurationBB", "ActivateFabricConfigurationBB", "ChangeModelVnfBB", "ActivateVnfBB", "ChangeModelServiceInstanceBB", "SDNOVnfHealthCheckBB", "AAIUnsetVnfInMaintBB"); + for (ExecuteBuildingBlock executeBuildingBlock : ebbs) { + assertEquals("123", executeBuildingBlock.getWorkflowResourceIds().getServiceInstanceId()); + } } @Ignore @@ -1089,6 +1103,362 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "UnassignVFModuleBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", + "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupReplaceRetainAssignmentsTest() throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "ChangeModelVfModuleBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleVolumeGroupToNoVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVFModuleBB", "UnassignVolumeGroupBB", "AssignVfModuleBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleVolumeGroupToNoVolumeGroupReplaceRetainAssignmentsTest() + throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVolumeGroupBB", "ChangeModelVfModuleBB", "CreateVfModuleBB", + "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleKeepVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "UnassignVFModuleBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", + "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleKeepVolumeGroupReplaceRetainAssignmentsTest() throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "ChangeModelVfModuleBB", + "CreateVfModuleBB", "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupToVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "UnassignVFModuleBB", + "AssignVolumeGroupBB", "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", + "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleNoVolumeGroupToVolumeGroupReplaceRetainAssignmentsTest() + throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "AssignVolumeGroupBB", + "ChangeModelVfModuleBB", "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB", + "ActivateVfModuleBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleRebuildVolumeGroupReplaceTest() throws Exception { + String gAction = "replaceInstance"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = new String( + Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVFModuleBB", "UnassignVolumeGroupBB", "AssignVolumeGroupBB", + "AssignVfModuleBB", "CreateVfModuleBB", "ActivateVfModuleBB", "CreateVolumeGroupBB", + "ActivateVolumeGroupBB", "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + @Test + public void selectExecutionListALaCarteVfModuleRebuildVolumeGroupReplaceRetainAssignmentsTest() throws Exception { + String gAction = "replaceInstanceRetainAssignments"; + String resource = "VfModule"; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = new String( + Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("aLaCarte", true); + execution.setVariable("apiVersion", "7"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules/1234"); + execution.setVariable("vnfId", "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d"); + execution.setVariable("vfModuleId", "1234"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("volumeGroupId"); + doReturn(Optional.of(volumeGroup)).when(bbSetupUtils) + .getRelatedVolumeGroupFromVfModule("b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", "1234"); + + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVolumeHeatEnv(new HeatEnvironment()); + org.onap.so.db.catalog.beans.VfModule vfModule = new org.onap.so.db.catalog.beans.VfModule(); + vfModule.setVolumeHeatTemplate(new HeatTemplate()); + vfModuleCustomization.setVfModule(vfModule); + when(catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID("9a6d01fd-19a7-490a-9800-460830a12e0b")) + .thenReturn(vfModuleCustomization); + + NorthBoundRequest northBoundRequest = new NorthBoundRequest(); + northBoundRequest.setOrchestrationFlowList(replaceRetainAssignmentsVfModuleOrchFlows); + when(catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(gAction, resource, + true, "my-custom-cloud-owner")).thenReturn(northBoundRequest); + workflowAction.selectExecutionList(execution); + List<ExecuteBuildingBlock> ebbs = (List<ExecuteBuildingBlock>) execution.getVariable("flowsToExecute"); + + assertEqualsBulkFlowName(ebbs, "DeactivateVfModuleBB", "DeleteVfModuleATTBB", "DeactivateVolumeGroupBB", + "DeleteVolumeGroupBB", "UnassignVolumeGroupBB", "AssignVolumeGroupBB", "ChangeModelVfModuleBB", + "CreateVolumeGroupBB", "ActivateVolumeGroupBB", "CreateVfModuleBB", "ActivateVfModuleBB", + "ChangeModelVnfBB", "ChangeModelServiceInstanceBB"); + } + + + @Test public void selectExecutionListALaCarteVfModuleFabricDeleteTest() throws Exception { String gAction = "deleteInstance"; String resource = "VfModule"; @@ -1146,6 +1516,56 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test + public void getConfigBuildingBlocksNoVfModuleFabricDeleteTest() throws Exception { + String gAction = "deleteInstance"; + ObjectMapper mapper = new ObjectMapper(); + WorkflowType resourceType = WorkflowType.VFMODULE; + execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); + execution.setVariable("requestAction", gAction); + String bpmnRequest = + new String(Files.readAllBytes(Paths.get("src/test/resources/__files/VfModuleCreateWithFabric.json"))); + execution.setVariable("bpmnRequest", bpmnRequest); + execution.setVariable("vnfId", "1234"); + execution.setVariable("vfModuleId", "vfModuleId1234"); + execution.setVariable("requestUri", + "v7/serviceInstances/f647e3ef-6d2e-4cd3-bff4-8df4634208de/vnfs/b80b16a5-f80d-4ffa-91c8-bd47c7438a3d/vfModules"); + ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class); + RequestDetails requestDetails = sIRequest.getRequestDetails(); + String requestAction = "deleteInstance"; + String requestId = "9c944122-d161-4280-8594-48c06a9d96d5"; + boolean aLaCarte = true; + String apiVersion = "7"; + String vnfType = "vnfType"; + String key = "00d15ebb-c80e-43c1-80f0-90c40dde70b0"; + String resourceId = "d1d35800-783d-42d3-82f6-d654c5054a6e"; + Resource resourceKey = new Resource(resourceType, key, aLaCarte); + WorkflowResourceIds workflowResourceIds = SPY_workflowAction.populateResourceIdsFromApiHandler(execution); + + thrown.expect(AAIEntityNotFoundException.class); + thrown.expectMessage(containsString( + "No matching VfModule is found in Generic-Vnf in AAI for vnfId: 1234 and vfModuleId : vfModuleId1234")); + + List<OrchestrationFlow> orchFlows = createFlowList("DeactivateVfModuleBB", "DeleteVfModuleBB", + "UnassignVfModuleBB", "DeactivateFabricConfigurationBB", "UnassignFabricConfigurationBB"); + + ConfigBuildingBlocksDataObject dataObj = new ConfigBuildingBlocksDataObject().setsIRequest(sIRequest) + .setOrchFlows(orchFlows).setRequestId(requestId).setResourceKey(resourceKey).setApiVersion(apiVersion) + .setResourceId(resourceId).setRequestAction(requestAction).setaLaCarte(aLaCarte).setVnfType(vnfType) + .setWorkflowResourceIds(workflowResourceIds).setRequestDetails(requestDetails).setExecution(execution); + + org.onap.aai.domain.yang.GenericVnf vnf = new org.onap.aai.domain.yang.GenericVnf(); + vnf.setVnfId("vnf0"); + vnf.setModelCustomizationId("modelCustomizationId"); + when(bbSetupUtils.getAAIGenericVnf(anyObject())).thenReturn(vnf); + + org.onap.aai.domain.yang.VfModule vfModule = new org.onap.aai.domain.yang.VfModule(); + vfModule.setModelCustomizationId("modelCustomizationId"); + when(bbSetupUtils.getAAIVfModule(anyObject(), anyObject())).thenReturn(null); + + SPY_workflowAction.getConfigBuildingBlocks(dataObj); + } + + @Test public void selectExecutionListALaCarteVfModuleNoFabricDeleteTest() throws Exception { String gAction = "deleteInstance"; String resource = "VfModule"; @@ -1541,7 +1961,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateVnfResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIVnfTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1574,7 +1994,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateVnfResourceNameInAAITest() throws Exception { + public void validateResourceIdInAAIVnfNotGloballyUniqueTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1596,7 +2016,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateNetworkResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAINetworkTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1656,7 +2076,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateVfModuleResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIVfModuleTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1699,11 +2119,28 @@ public class WorkflowActionTest extends BaseTaskTest { "vfModule with name (vFModName222), same parent and different customization id (1234567) already exists. The name must be unique.")); workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "vFModName222", reqDetails, workflowResourceIds); + } + + @Test + public void validateResourceIdInAAIVfModuleNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("id111"); + + GenericVnf vnf1 = new GenericVnf(); + workflowResourceIds.setVnfId("id111"); + when(bbSetupUtils.getAAIGenericVnf("id111")).thenReturn(vnf1); + when(bbSetupUtils.existsAAIVfModuleGloballyByName("vFModName333")).thenReturn(true); + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("vfModule with name vFModName333 already exists. The name must be unique.")); + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VFMODULE, "vFModName333", reqDetails, + workflowResourceIds); } @Test - public void validateVolumeGroupResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIVolumeGroupTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1722,6 +2159,7 @@ public class WorkflowActionTest extends BaseTaskTest { VolumeGroup volumeGroup = new VolumeGroup(); volumeGroup.setVolumeGroupId("id123"); volumeGroup.setVolumeGroupName("name123"); + volumeGroup.setVfModuleModelCustomizationId("1234567"); workflowResourceIds.setVnfId("id123"); Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup); @@ -1744,7 +2182,25 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateConfigurationResourceIdInAAITest() throws Exception { + public void validatesourceIdInAAIVolumeGroupNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("id123"); + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(vnf); + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "testVolumeGroup")).thenReturn(Optional.empty()); + + when(bbSetupUtils.existsAAIVolumeGroupGloballyByName("testVolumeGroup")).thenReturn(true); + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("volumeGroup with name testVolumeGroup already exists. The name must be unique.")); + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "testVolumeGroup", + reqDetails, workflowResourceIds); + } + + @Test + public void validateResourceIdInAAIConfigurationTest() throws Exception { RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); @@ -1786,7 +2242,23 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateServiceInstanceResourceIdInAAITest() throws Exception { + public void validateResourceIdInAAIConfigurationNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "testConfig")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("testConfig")).thenReturn(true); + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("configuration with name testConfig already exists. The name must be unique.")); + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.CONFIGURATION, "testConfig", reqDetails, + workflowResourceIds); + } + + @Test + public void validateResourceIdInAAISITest() throws Exception { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); @@ -1828,7 +2300,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateServiceInstanceResourceIdInAAIMultipleTest() throws Exception { + public void validateResourceIdInAAIMultipleSITest() throws Exception { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); @@ -1859,7 +2331,7 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test - public void validateServiceInstanceResourceIdInAAIExistsTest() throws Exception { + public void validateResourceIdInAAISIExistsTest() throws Exception { WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); workflowResourceIds.setServiceInstanceId("siId123"); RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); @@ -1890,6 +2362,490 @@ public class WorkflowActionTest extends BaseTaskTest { } @Test + public void validateServiceResourceIdInAAINoDupTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIServiceInstancesGloballyByName("siName123")).thenReturn(null); + String id = workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName123", reqDetails); + assertEquals("generatedId123", id); + } + + @Test + public void validateServiceResourceIdInAAISameModelVersionId() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("1234567"); + Optional<ServiceInstance> siOp = Optional.of(si); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")).thenReturn(siOp); + String id = workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName123", reqDetails); + assertEquals("siId123", id); + } + + @Test + public void validateServiceResourceIdInAAIDifferentModelVersionId() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("9999999"); + ServiceInstances serviceInstances = new ServiceInstances(); + serviceInstances.getServiceInstance().add(si); + Optional<ServiceInstance> siOp = Optional.of(si); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName123")).thenReturn(siOp); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "serviceInstance with name (siName123) and different version id (1234567) already exists. The name must be unique.")); + + String id = workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName123", reqDetails); + assertEquals("siId123", id); + } + + @Test + public void validateServiceResourceIdInAAIDuplicateNameTest() throws Exception { + + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("1234567"); + + ServiceInstances serviceInstances = new ServiceInstances(); + serviceInstances.getServiceInstance().add(si); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIServiceInstancesGloballyByName("siName")).thenReturn(serviceInstances); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "serviceInstance with name (siName) and global-customer-id (null), service-type (null), model-version-id (1234567) already exists. The name must be unique.")); + + workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName", reqDetails); + } + + @Test + public void validateServiceResourceIdInAAIDuplicateNameMultipleTest() throws Exception { + + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + reqDetails.getModelInfo().setModelVersionId("1234567"); + + ServiceInstance si = new ServiceInstance(); + si.setServiceInstanceId("siId123"); + si.setModelVersionId("1234567"); + + ServiceInstance si2 = new ServiceInstance(); + si2.setServiceInstanceId("siId222"); + si2.setModelVersionId("22222"); + si2.setServiceInstanceName("siName222"); + + ServiceInstances serviceInstances = new ServiceInstances(); + serviceInstances.getServiceInstance().add(si); + serviceInstances.getServiceInstance().add(si2); + + when(bbSetupUtils.getAAIServiceInstanceByName("id123", "subServiceType123", "siName")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIServiceInstancesGloballyByName("siName")).thenReturn(serviceInstances); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "serviceInstance with name (siName) and multiple combination of model-version-id + service-type + global-customer-id already exists. The name must be unique.")); + + workflowAction.validateServiceResourceIdInAAI("generatedId123", "siName", reqDetails); + } + + @Test + public void validateNetworkResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAINetworksGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateNetworkResourceIdInAAISameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + L3Network network = new L3Network(); + network.setNetworkId("id123"); + network.setNetworkName("name123"); + network.setModelCustomizationId("1234567"); + Optional<L3Network> opNetwork = Optional.of(network); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")).thenReturn(opNetwork); + + String id = workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateNetworkResourceIdInAAIDuplicateNameTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + L3Network network = new L3Network(); + network.setNetworkId("id123"); + network.setNetworkName("name123"); + network.setModelCustomizationId("9999999"); + Optional<L3Network> opNetwork = Optional.of(network); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")).thenReturn(opNetwork); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "l3Network with name (name123), same parent and different customization id (9999999) already exists. The name must be unique.")); + + workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + } + + @Test + public void validateNetworkResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedNetworkByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAINetworksGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "l3Network with name (name123) id (siId123) and different parent relationship already exists. The name must be unique.")); + + workflowAction.validateNetworkResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVnfResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(Optional.empty()); + String id = workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateVnfResourceIdInAAISameModelCustomizationIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setModelCustomizationId("1234567"); + Optional<GenericVnf> opVnf = Optional.of(vnf); + + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(opVnf); + String id = workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateVnfResourceIdInAAIDiffModelCustomizationIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setModelCustomizationId("9999999"); + Optional<GenericVnf> opVnf = Optional.of(vnf); + + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(opVnf); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "generic-vnf with name (vnfName123), same parent and different customization id (9999999) already exists. The name must be unique.")); + + workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVnfResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + GenericVnfs genericVnfs = new GenericVnfs(); + genericVnfs.getGenericVnf().add(vnf); + + when(bbSetupUtils.getRelatedVnfByNameFromServiceInstance("siId123", "vnfName123")).thenReturn(Optional.empty()); + when(bbSetupUtils.getAAIVnfsGloballyByName("vnfName123")).thenReturn(genericVnfs); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "generic-vnf with name (vnfName123) id (id123) and different parent relationship already exists. The name must be unique.")); + + workflowAction.validateVnfResourceIdInAAI("generatedId123", "vnfName123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVfModuleResourceIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(null); + when(bbSetupUtils.existsAAIVfModuleGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateVfModuleResourceIdSameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + VfModules vfModules = new VfModules(); + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("id123"); + vfModule.setVfModuleName("name123"); + vfModule.setModelCustomizationId("1234567"); + vfModules.getVfModule().add(vfModule); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setVfModules(vfModules); + + when(bbSetupUtils.getAAIGenericVnf("vnfId123")).thenReturn(vnf); + + String id = workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateVfModuleResourceIdDifferentModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + VfModules vfModules = new VfModules(); + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("id123"); + vfModule.setVfModuleName("name123"); + vfModule.setModelCustomizationId("9999999"); + vfModules.getVfModule().add(vfModule); + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("id123"); + vnf.setVnfName("vnfName123"); + vnf.setVfModules(vfModules); + + when(bbSetupUtils.getAAIGenericVnf("vnfId123")).thenReturn(vnf); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "vfModule with name (name123), same parent and different customization id (1234567) already exists. The name must be unique.")); + + workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + + } + + @Test + public void validateVfModuleResourceIdNotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getAAIGenericVnf("id123")).thenReturn(null); + when(bbSetupUtils.existsAAIVfModuleGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException + .expectMessage(containsString("vfModule with name name123 already exists. The name must be unique.")); + + workflowAction.validateVfModuleResourceIdInAAI("generatedId123", "name123", reqDetails, workflowResourceIds); + } + + @Test + public void validateVolumeGroupResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("id123", "name123")).thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIVolumeGroupGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateVolumeGroupResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateVolumeGroupResourceIdInAAISameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + workflowResourceIds.setVnfId("vnfId123"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + volumeGroup.setVolumeGroupName("name123"); + volumeGroup.setVfModuleModelCustomizationId("1234567"); + + Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("vnfId123", "name123")).thenReturn(opVolumeGroup); + String id = workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", + reqDetails, workflowResourceIds); + + assertEquals("id123", id); + } + + @Test + public void validateVolumeGroupResourceIdInAAIDifferentModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + workflowResourceIds.setVnfId("vnfId123"); + + VolumeGroup volumeGroup = new VolumeGroup(); + volumeGroup.setVolumeGroupId("id123"); + volumeGroup.setVolumeGroupName("name123"); + volumeGroup.setVfModuleModelCustomizationId("9999999"); + + Optional<VolumeGroup> opVolumeGroup = Optional.of(volumeGroup); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("vnfId123", "name123")).thenReturn(opVolumeGroup); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("volumeGroup with name name123 already exists. The name must be unique.")); + + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", reqDetails, + workflowResourceIds); + } + + @Test + public void validateVolumeGroupResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setVnfId("vnfId123"); + + when(bbSetupUtils.getRelatedVolumeGroupByNameFromVnf("vnfId123", "name123")).thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIVolumeGroupGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("volumeGroup with name name123 already exists. The name must be unique.")); + + workflowAction.validateResourceIdInAAI("generatedId123", WorkflowType.VOLUMEGROUP, "name123", reqDetails, + workflowResourceIds); + } + + @Test + public void validateConfigurationResourceIdInAAITest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("generatedId123", id); + } + + @Test + public void validateConfigurationResourceIdInAAISameModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration(); + configuration.setConfigurationId("id123"); + configuration.setConfigurationName("name123"); + configuration.setModelCustomizationId("1234567"); + Optional<org.onap.aai.domain.yang.Configuration> opConfiguration = Optional.of(configuration); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(opConfiguration); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(false); + + String id = workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + assertEquals("id123", id); + } + + @Test + public void validateConfigurationResourceIdInAAIDifferentModelCustIdTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + org.onap.aai.domain.yang.Configuration configuration = new org.onap.aai.domain.yang.Configuration(); + configuration.setConfigurationId("id123"); + configuration.setConfigurationName("name123"); + configuration.setModelCustomizationId("9999999"); + Optional<org.onap.aai.domain.yang.Configuration> opConfiguration = Optional.of(configuration); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(opConfiguration); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(false); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage(containsString( + "configuration with name (name123), same parent and different customization id (id123) already exists. The name must be unique.")); + + workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + } + + @Test + public void validateConfigurationResourceIdInAAINotGloballyUniqueTest() throws Exception { + RequestDetails reqDetails = setupRequestDetails("id123", "subServiceType123", "1234567"); + WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds(); + workflowResourceIds.setServiceInstanceId("siId123"); + + when(bbSetupUtils.getRelatedConfigurationByNameFromServiceInstance("siId123", "name123")) + .thenReturn(Optional.empty()); + when(bbSetupUtils.existsAAIConfigurationGloballyByName("name123")).thenReturn(true); + + this.expectedException.expect(DuplicateNameException.class); + this.expectedException.expectMessage( + containsString("configuration with name name123 already exists. The name must be unique.")); + + workflowAction.validateConfigurationResourceIdInAAI("generatedId123", "name123", reqDetails, + workflowResourceIds); + } + + @Test public void handleRuntimeExceptionTest() { execution.setVariable("BPMN_javaExpMsg", "test runtime error message"); execution.setVariable("testProcessKey", "testProcessKeyValue"); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java index 2e77023757..a482da5158 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java @@ -150,7 +150,23 @@ public class VnfAdapterObjectMapperTest { CreateVolumeGroupRequest actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse); + assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest)); + + doReturn("false").when(vnfAdapterObjectMapper).getProperty("mso.bridgeEnabled"); + actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, + cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse); + assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest)); + + doReturn(null).when(vnfAdapterObjectMapper).getProperty("mso.bridgeEnabled"); + expectedCreateVolumeGroupRequest.setEnableBridge(true); + actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, + cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse); + assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest)); + doReturn("true").when(vnfAdapterObjectMapper).getProperty("mso.bridgeEnabled"); + expectedCreateVolumeGroupRequest.setEnableBridge(true); + actualCreateVolumeGroupRequest = vnfAdapterObjectMapper.createVolumeGroupRequestMapper(requestContext, + cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVfModuleQueryResponse); assertThat(actualCreateVolumeGroupRequest, sameBeanAs(expectedCreateVolumeGroupRequest)); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java index 44a08139d6..836f8c1842 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapperPayloadTest.java @@ -23,6 +23,7 @@ package org.onap.so.client.adapter.vnf.mapper; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -32,6 +33,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.mockito.Mockito; import org.onap.sdnc.northbound.client.model.GenericResourceApiVmNetworkData; import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; @@ -46,6 +48,7 @@ import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance; import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule; import org.onap.so.openstack.utils.MsoMulticloudUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.onap.so.client.adapter.vnf.mapper.exceptions.MissingValueTagException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -56,6 +59,9 @@ public class VnfAdapterVfModuleObjectMapperPayloadTest { private VnfAdapterVfModuleObjectMapper vfModuleObjectMapper = new VnfAdapterVfModuleObjectMapper(); private ObjectMapper omapper = new ObjectMapper(); + @Autowired + protected VnfAdapterObjectMapperUtils vnfAdapterObjectMapperUtils; + @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -128,16 +134,35 @@ public class VnfAdapterVfModuleObjectMapperPayloadTest { String sdncVfModuleQueryResponse = new String(Files .readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleSdncVfModuleTopology.json"))); + VnfAdapterVfModuleObjectMapper spyMapper = Mockito.spy(vfModuleObjectMapper); + + doReturn("false").when(spyMapper).getProperty("mso.bridgeEnabled"); CreateVfModuleRequest vfModuleVNFAdapterRequest = - vfModuleObjectMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, + spyMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse); - - String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequest.json"))); - CreateVfModuleRequest reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class); + assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl")); + + doReturn("true").when(spyMapper).getProperty("mso.bridgeEnabled"); + vfModuleVNFAdapterRequest = + spyMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, + serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse); + jsonToCompare = new String(Files + .readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestBridgeEnabled.json"))); + reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class); + assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl")); + + + doReturn(null).when(spyMapper).getProperty("mso.bridgeEnabled"); + vfModuleVNFAdapterRequest = + spyMapper.createVfModuleRequestMapper(requestContext, cloudRegion, orchestrationContext, + serviceInstance, vnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse); + jsonToCompare = new String(Files + .readAllBytes(Paths.get(JSON_FILE_LOCATION + "vnfAdapterCreateVfModuleRequestBridgeEnabled.json"))); + reqMapper1 = omapper.readValue(jsonToCompare, CreateVfModuleRequest.class); assertThat(vfModuleVNFAdapterRequest, sameBeanAs(reqMapper1).ignoring("messageId").ignoring("notificationUrl")); } diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json index 5975cb21fe..b57c8341f1 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json @@ -13,6 +13,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestBridgeEnabled.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestBridgeEnabled.json new file mode 100644 index 0000000000..a02b1c901d --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestBridgeEnabled.json @@ -0,0 +1,71 @@ +{ + "cloudSiteId": "cloudRegionId", + "tenantId": "tenantId", + "vnfId": "vnfId", + "vnfType": "vnfType", + "vfModuleId": "vfModuleId", + "vfModuleName": "vfModuleName", + "vfModuleType": "vfModuleModelName", + "vnfVersion": "serviceModelVersion", + "modelCustomizationUuid": "vfModuleModelCustomizationUuid", + "skipAAI": true, + "backout": false, + "failIfExists": false, + "enableBridge": true, + "msoRequest": + { + "requestId": "requestId", + "serviceInstanceId": "serviceInstanceId" + }, + + "vfModuleParams": + { + "vnf_id": "vnfId", + "vnf_name": "vnfName", + "vf_module_id": "vfModuleId", + "vf_module_index": "1", + "vf_module_name": "vfModuleName", + "environment_context": "environmentContext", + "fw_0_subint_ctrl_port_0_ip": "ip0,ip1", + "fw_0_subint_ctrl_port_0_ip_0": "ip0", + "fw_0_subint_ctrl_port_0_ip_1": "ip1", + "fw_0_subint_ctrl_port_0_net_ids": "networkId0", + "fw_0_subint_ctrl_port_0_net_names": "1", + "fw_subint_ctrl_port_0_subintcount": "1", + "fw_0_subint_ctrl_port_0_v6_ip": "ip0,ip1", + "fw_0_subint_ctrl_port_0_v6_ip_0": "ip0", + "fw_0_subint_ctrl_port_0_v6_ip_1": "ip1", + "fw_0_subint_ctrl_port_0_vlan_ids": "1", + "fw_subint_ctrl_port_0_floating_ip": "floatingIpV40", + "fw_subint_ctrl_port_0_floating_v6_ip": "floatingIpV60", + "workload_context": "workloadContext", + "key1": "value2", + "key3": "value3", + "availability_zone_0": "zone0", + "availability_zone_1": "zone1", + "availability_zone_2": "zone2", + "vnfNetworkRole0_net_fqdn": "netFqdnValue0", + "vnfNetworkRole0_net_id": "neutronId0", + "vnfNetworkRole0_net_name": "netName0", + "vnfNetworkRole0_subnet_id": "subnetId0", + "vnfNetworkRole0_v6_subnet_id": "subnetId1", + "vmType0_name_0": "vmName0", + "vmType0_name_1": "vmName1", + "vmType0_names": "vmName0,vmName1", + "vmType0_vmNetworkRole0_floating_ip": "floatingIpV40", + "vmType0_vmNetworkRole0_floating_v6_ip": "floatingIpV60", + "vmType0_vmNetworkRole0_route_prefixes": "[{\"interface_route_table_routes_route_prefix\": \"interfaceRoutePrefix0\"},{\"interface_route_table_routes_route_prefix\": \"interfaceRoutePrefix1\"}]", + "vmNetworkRole0_ATT_VF_VLAN_FILTER": "heatVlanFilter0,heatVlanFilter1", + "vmType0_vmNetworkRole0_ip_0": "ip0", + "vmType0_vmNetworkRole0_ip_1": "ip1", + "vmType0_vmNetworkRole0_ips": "ip0,ip1", + "vmType0_vmNetworkRole0_v6_ip_0": "ip2", + "vmType0_vmNetworkRole0_v6_ip_1": "ip3", + "vmType0_vmNetworkRole0_v6_ips": "ip2,ip3", + "paramOne": "paramOneValue", + "paramTwo": "paramTwoValue", + "paramThree": "paramThreeValue", + "sdnc_directives": "{ \"attributes\": [ {\"attribute_name\": \"key1\", \"attribute_value\": \"value1\"}, {\"attribute_name\": \"fw_subint_ctrl_port_0_subintcount\", \"attribute_value\": \"1\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_floating_ip\", \"attribute_value\": \"floatingIpV40\"}, {\"attribute_name\": \"paramOne\", \"attribute_value\": \"paramOneValue\"}, {\"attribute_name\": \"vmType0_name_0\", \"attribute_value\": \"vmName0\"}, {\"attribute_name\": \"vnfNetworkRole0_v6_subnet_id\", \"attribute_value\": \"subnetId1\"}, {\"attribute_name\": \"vmType0_name_1\", \"attribute_value\": \"vmName1\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_ip_1\", \"attribute_value\": \"ip1\"}, {\"attribute_name\": \"vnfNetworkRole0_net_name\", \"attribute_value\": \"netName0\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_ip_0\", \"attribute_value\": \"ip0\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_vlan_ids\", \"attribute_value\": \"1\"}, {\"attribute_name\": \"vnfNetworkRole0_net_id\", \"attribute_value\": \"neutronId0\"}, {\"attribute_name\": \"availability_zone_0\", \"attribute_value\": \"zone0\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_v6_ip_1\", \"attribute_value\": \"ip3\"}, {\"attribute_name\": \"availability_zone_1\", \"attribute_value\": \"zone1\"}, {\"attribute_name\": \"fw_subint_ctrl_port_0_floating_v6_ip\", \"attribute_value\": \"floatingIpV60\"}, {\"attribute_name\": \"availability_zone_2\", \"attribute_value\": \"zone2\"}, {\"attribute_name\": \"vmType0_names\", \"attribute_value\": \"vmName0,vmName1\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_route_prefixes\", \"attribute_value\": \"[{\"interface_route_table_routes_route_prefix\": \"interfaceRoutePrefix0\"},{\"interface_route_table_routes_route_prefix\": \"interfaceRoutePrefix1\"}]\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_v6_ip_0\", \"attribute_value\": \"ip2\"}, {\"attribute_name\": \"vnfNetworkRole0_subnet_id\", \"attribute_value\": \"subnetId0\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_v6_ip_1\", \"attribute_value\": \"ip1\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_ip_1\", \"attribute_value\": \"ip1\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_ip_0\", \"attribute_value\": \"ip0\"}, {\"attribute_name\": \"vnfNetworkRole0_net_fqdn\", \"attribute_value\": \"netFqdnValue0\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_v6_ip_0\", \"attribute_value\": \"ip0\"}, {\"attribute_name\": \"vmNetworkRole0_ATT_VF_VLAN_FILTER\", \"attribute_value\": \"heatVlanFilter0,heatVlanFilter1\"}, {\"attribute_name\": \"paramTwo\", \"attribute_value\": \"paramTwoValue\"}, {\"attribute_name\": \"paramThree\", \"attribute_value\": \"paramThreeValue\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_v6_ips\", \"attribute_value\": \"ip2,ip3\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_floating_v6_ip\", \"attribute_value\": \"floatingIpV60\"}, {\"attribute_name\": \"vmType0_vmNetworkRole0_ips\", \"attribute_value\": \"ip0,ip1\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_ip\", \"attribute_value\": \"ip0,ip1\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_net_names\", \"attribute_value\": \"1\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_net_ids\", \"attribute_value\": \"networkId0\"}, {\"attribute_name\": \"fw_0_subint_ctrl_port_0_v6_ip\", \"attribute_value\": \"ip0,ip1\"}, {\"attribute_name\": \"fw_subint_ctrl_port_0_floating_ip\", \"attribute_value\": \"floatingIpV40\"}] }", + "user_directives": "{ \"attributes\": [ {\"attribute_name\": \"key1\", \"attribute_value\": \"value2\"}] }" + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestDhcpDisabled.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestDhcpDisabled.json index aa4ada059d..ea51d2c6b2 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestDhcpDisabled.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestDhcpDisabled.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestMultipleDhcp.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestMultipleDhcp.json index f7fb1e9f44..aa633bf5a8 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestMultipleDhcp.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestMultipleDhcp.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestNoUserParams.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestNoUserParams.json index e06f9cbf36..9bddf29433 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestNoUserParams.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestNoUserParams.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestTrueBackout.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestTrueBackout.json index b97bab4149..4ccfdbe890 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestTrueBackout.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestTrueBackout.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": true, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json index 7b78510f56..da826b8a89 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithSingleAvailabilityZone.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithSingleAvailabilityZone.json index 83ba299914..3170b8ba54 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithSingleAvailabilityZone.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithSingleAvailabilityZone.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithNoEnvironmentAndWorkloadContextRequest.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithNoEnvironmentAndWorkloadContextRequest.json index aaee92b083..be860ace96 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithNoEnvironmentAndWorkloadContextRequest.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithNoEnvironmentAndWorkloadContextRequest.json @@ -11,6 +11,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json index a419c2ee59..54f6e403ed 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json @@ -13,6 +13,7 @@ "skipAAI": true, "backout": false, "failIfExists": false, + "enableBridge": true, "msoRequest": { "requestId": "requestId", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json new file mode 100644 index 0000000000..aa2462f371 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/VfModuleReplaceRebuildVolumeGroups.json @@ -0,0 +1,66 @@ +{ + "requestDetails": { + "modelInfo": { + "modelCustomizationName": "model-cust-name", + "modelInvariantId": "db86e4a6-c027-452e-a559-3a23b3128367", + "modelType": "vfModule", + "modelName": "test-model-name", + "modelVersion": "1", + "modelCustomizationUuid": "9a6d01fd-19a7-490a-9800-460830a12e0b", + "modelVersionId": "14c8f313-fb0f-4cf6-8caf-c7cce8137b60", + "modelCustomizationId": "9a6d01fd-19a7-490a-9800-460830a12e0b", + "modelUuid": "14c8f313-fb0f-4cf6-8caf-c7cce8137b60", + "modelInvariantUuid": "db86e4a6-c027-452e-a559-3a23b3128367", + "modelInstanceName": "test-model-instance-name" + }, + "requestInfo": { + "source": "VID", + "instanceName": "instanceName", + "suppressRollback": false, + "requestorId": "user" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f647e3ef-6d2e-4cd3-bff4-8df4634208de", + "modelInfo": { + "modelInvariantId": "86adb376-5303-441a-b50e-96c0cd643b0f", + "modelType": "service", + "modelName": "model-name", + "modelVersion": "1.0", + "modelVersionId": "599e21ed-803d-4d1f-83df-20005339b83f", + "modelUuid": "599e21ed-803d-4d1f-83df-20005339b83f", + "modelInvariantUuid": "86adb376-5303-441a-b50e-96c0cd643b0f" + } + } + }, + { + "relatedInstance": { + "instanceId": "b80b16a5-f80d-4ffa-91c8-bd47c7438a3d", + "modelInfo": { + "modelCustomizationName": "modle-cust-name", + "modelInvariantId": "5cca9285-4ed4-4e11-a609-921ed3344811", + "modelType": "vnf", + "modelName": "modle-name", + "modelVersion": "1.0", + "modelCustomizationUuid": "fc25201d-36d6-43a3-8d39-fdae88e526ae", + "modelVersionId": "7cae703a-b20d-481a-863a-b862236c00f7", + "modelCustomizationId": "fc25201d-36d6-43a3-8d39-fdae88e526ae", + "modelUuid": "7cae703a-b20d-481a-863a-b862236c00f7", + "modelInvariantUuid": "5cca9285-4ed4-4e11-a609-921ed3344811", + "modelInstanceName": "model-inst-name" + } + } + } + ], + "cloudConfiguration": { + "tenantId": "872f331350c54e59991a8de2cbffb40c", + "cloudOwner": "my-custom-cloud-owner", + "lcpCloudRegionId": "cloud-region" + }, + "requestParameters": { + "usePreload": true, + "rebuildVolumeGroups": true + } + } +}
\ No newline at end of file diff --git a/common/pom.xml b/common/pom.xml index 3690d7b5a1..94b28e91bd 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -58,7 +58,7 @@ <dependency> <groupId>org.onap.aai.schema-service</groupId> <artifactId>aai-schema</artifactId> - <version>1.0.5</version> + <version>1.6.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.modelmapper</groupId> @@ -131,6 +131,17 @@ <scope>test</scope> </dependency> <dependency> + <groupId>org.onap.aaf.authz</groupId> + <artifactId>aaf-cadi-aaf</artifactId> + <version>2.1.9</version> + <exclusions> + <exclusion> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> <groupId>org.reflections</groupId> <artifactId>reflections</artifactId> <version>0.9.11</version> diff --git a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java index 3a59b2b337..4f06b787f7 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java @@ -23,7 +23,7 @@ package org.onap.so.client.aai; import org.onap.so.client.graphinventory.GraphInventoryVersion; public enum AAIVersion implements GraphInventoryVersion { - V13("v13"), V14("v14"), V15("v15"), V16("v16"), V17("v17"); + V13("v13"), V14("v14"), V15("v15"), V16("v16"), V17("v17"), V18("v18"), V19("v19"); public static final AAIVersion LATEST = AAIVersion.values()[AAIVersion.values().length - 1]; private final String value; diff --git a/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java b/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java index ccfd2f4de6..641bbb28c7 100644 --- a/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java +++ b/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java @@ -21,5 +21,5 @@ package org.onap.so.constants; public enum OrchestrationRequestFormat { - DETAIL, STATUSDETAIL + DETAIL, STATUSDETAIL, SIMPLE } diff --git a/common/src/main/java/org/onap/so/security/WebSecurityConfig.java b/common/src/main/java/org/onap/so/security/WebSecurityConfig.java index 635784c642..44ac62d14f 100644 --- a/common/src/main/java/org/onap/so/security/WebSecurityConfig.java +++ b/common/src/main/java/org/onap/so/security/WebSecurityConfig.java @@ -32,7 +32,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @ConfigurationProperties(prefix = "spring.security") -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { +public class WebSecurityConfig { private List<UserCredentials> credentials; private List<String> roles = new ArrayList<>(); @@ -65,10 +65,4 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder()); - } - } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java new file mode 100644 index 0000000000..f601ebc3bd --- /dev/null +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.serviceinstancebeans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonRootName; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@JsonRootName(value = "pnfs") +@JsonInclude(JsonInclude.Include.NON_DEFAULT) +public class Pnfs implements Serializable { + + private static final long serialVersionUID = 8081495240474276501L; + @JsonProperty("modelInfo") + protected ModelInfo modelInfo; + @JsonProperty("cloudConfiguration") + protected CloudConfiguration cloudConfiguration; + @JsonProperty("instanceName") + protected String instanceName; + @JsonProperty("platform") + protected Platform platform; + @JsonProperty("lineOfBusiness") + protected LineOfBusiness lineOfBusiness; + @JsonProperty("productFamilyId") + protected String productFamilyId; + @JsonProperty("instanceParams") + private List<Map<String, String>> instanceParams = new ArrayList<>(); + + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public CloudConfiguration getCloudConfiguration() { + return cloudConfiguration; + } + + public void setCloudConfiguration(CloudConfiguration cloudConfiguration) { + this.cloudConfiguration = cloudConfiguration; + } + + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + public Platform getPlatform() { + return platform; + } + + public void setPlatform(Platform platform) { + this.platform = platform; + } + + public LineOfBusiness getLineOfBusiness() { + return lineOfBusiness; + } + + public void setLineOfBusiness(LineOfBusiness lineOfBusiness) { + this.lineOfBusiness = lineOfBusiness; + } + + public String getProductFamilyId() { + return productFamilyId; + } + + public void setProductFamilyId(String productFamilyId) { + this.productFamilyId = productFamilyId; + } + + public List<Map<String, String>> getInstanceParams() { + return instanceParams; + } + + public void setInstanceParams(List<Map<String, String>> instanceParams) { + this.instanceParams = instanceParams; + } + + @Override + public String toString() { + return "Pnfs [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName=" + + instanceName + ", platform=" + platform + ", " + "lineOfBusiness=" + lineOfBusiness + + ", productFamilyId=" + productFamilyId + ", instanceParams=" + instanceParams + "]"; + } + +} 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 61192c3147..250c5df5ce 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java @@ -55,6 +55,8 @@ public class RequestInfo implements Serializable { protected boolean suppressRollback; @JsonProperty("requestorId") protected String requestorId; + @JsonProperty("applicationId") + protected String applicationId; /** * Gets the value of the callbackUrl property. @@ -201,12 +203,21 @@ public class RequestInfo implements Serializable { this.requestorId = requestorId; } + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + @Override 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 + "]"; + + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + ", applicationId=" + + applicationId + "]"; } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java index 2123b2f6fc..acac8c4033 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -36,6 +38,8 @@ public class Resources implements Serializable { private static final long serialVersionUID = 2194797231782624520L; @JsonProperty("vnfs") private List<Vnfs> vnfs = new ArrayList<>(); + @JsonProperty("pnfs") + private List<Pnfs> pnfs = new ArrayList<>(); @JsonProperty("networks") private List<Networks> networks = new ArrayList<>(); @@ -47,6 +51,14 @@ public class Resources implements Serializable { this.vnfs = vnfs; } + public List<Pnfs> getPnfs() { + return pnfs; + } + + public void setPnfs(List<Pnfs> pnfs) { + this.pnfs = pnfs; + } + public List<Networks> getNetworks() { return networks; } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java index 1a0e13587e..5bcdcb181b 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java @@ -32,6 +32,8 @@ public class ServiceInstancesRequest implements Serializable { private String serviceInstanceId; @JsonProperty("vnfInstanceId") private String vnfInstanceId; + @JsonProperty("pnfId") + private String pnfId; @JsonProperty("networkInstanceId") private String networkInstanceId; @JsonProperty("volumeGroupInstanceId") @@ -67,6 +69,14 @@ public class ServiceInstancesRequest implements Serializable { this.vnfInstanceId = vnfInstanceId; } + public String getPnfId() { + return pnfId; + } + + public void setPnfId(String pnfId) { + this.pnfId = pnfId; + } + public String getNetworkInstanceId() { return networkInstanceId; } @@ -113,6 +123,7 @@ public class ServiceInstancesRequest implements Serializable { sb.append("requestDetails=").append(requestDetails); sb.append(", serviceInstanceId='").append(serviceInstanceId).append('\''); sb.append(", vnfInstanceId='").append(vnfInstanceId).append('\''); + sb.append(", pnfId='").append(pnfId).append('\''); sb.append(", networkInstanceId='").append(networkInstanceId).append('\''); sb.append(", volumeGroupInstanceId='").append(volumeGroupInstanceId).append('\''); sb.append(", vfModuleInstanceId='").append(vfModuleInstanceId).append('\''); diff --git a/common/src/main/java/org/onap/so/utils/Components.java b/common/src/main/java/org/onap/so/utils/Components.java index d8d703affc..5af8c5aa56 100644 --- a/common/src/main/java/org/onap/so/utils/Components.java +++ b/common/src/main/java/org/onap/so/utils/Components.java @@ -6,10 +6,11 @@ import org.onap.logging.filter.base.ONAPComponents; import org.onap.logging.filter.base.ONAPComponentsList; public enum Components implements ONAPComponentsList { - OPENSTACK, UNKNOWN, ASDC_CONTROLLER, APIH; + OPENSTACK, UNKNOWN, ASDC_CONTROLLER, APIH, SDNC_ADAPTER; + public static Set<Components> getSOInternalComponents() { - return EnumSet.of(ASDC_CONTROLLER, APIH); + return EnumSet.of(ASDC_CONTROLLER, APIH, SDNC_ADAPTER); } @Override diff --git a/common/src/test/java/org/onap/so/utils/ExternalTaskServiceUtilsTest.java b/common/src/test/java/org/onap/so/utils/ExternalTaskServiceUtilsTest.java deleted file mode 100644 index b2db986d02..0000000000 --- a/common/src/test/java/org/onap/so/utils/ExternalTaskServiceUtilsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.onap.so.utils; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doReturn; -import org.camunda.bpm.client.ExternalTaskClient; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.core.env.Environment; - -@RunWith(MockitoJUnitRunner.class) -public class ExternalTaskServiceUtilsTest { - - @Spy - @InjectMocks - private ExternalTaskServiceUtils utils = new ExternalTaskServiceUtils(); - - @Mock - private Environment mockEnv; - - @Mock - private ExternalTaskClient mockClient; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - doReturn("3").when(mockEnv).getProperty("workflow.topics.maxClients", "3"); - doReturn("07a7159d3bf51a0e53be7a8f89699be7").when(mockEnv).getRequiredProperty("mso.msoKey"); - doReturn("6B466C603A260F3655DBF91E53CE54667041C01406D10E8CAF9CC24D8FA5388D06F90BFE4C852052B436").when(mockEnv) - .getRequiredProperty("mso.auth"); - doReturn("someid").when(mockEnv).getRequiredProperty("mso.config.cadi.aafId"); - doReturn("http://camunda.com").when(mockEnv).getRequiredProperty("mso.workflow.endpoint"); - } - - @Test - public void testCreateExternalTaskClient() throws Exception { - ExternalTaskClient actualClient = utils.createExternalTaskClient(); - Assert.assertNotNull(actualClient); - } - - @Test - public void testGetAuth() throws Exception { - String actual = utils.getAuth(); - String expected = "Att32054Life!@"; - assertEquals(expected, actual); - } - - @Test - public void testGetMaxClients() throws Exception { - int actual = utils.getMaxClients(); - int expected = 3; - assertEquals(expected, actual); - } - -} diff --git a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java index f6ac449057..d1f509f476 100644 --- a/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java +++ b/cxf-logging/src/main/java/org/onap/so/logging/cxf/interceptor/SOAPLoggingInInterceptor.java @@ -83,6 +83,7 @@ public class SOAPLoggingInInterceptor extends AbstractSoapInterceptor { String invocationId = getValueOrDefault(headers, ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase(), UUID.randomUUID().toString()); MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + MDC.put(ONAPLogConstants.MDCs.SERVER_INVOCATION_ID, invocationId); } private void setRequestId(Map<String, List<String>> headers) { diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java index 0f51341a61..4517811494 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/camundabeans/CamundaVIDRequest.java @@ -357,5 +357,4 @@ public class CamundaVIDRequest { public void setGenerateIds(CamundaBooleanInput generateIds) { this.generateIds = generateIds; } - } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java index e098ea4354..3cf3907424 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandler/common/RequestClientParameter.java @@ -302,6 +302,4 @@ public class RequestClientParameter { } } - - } diff --git a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java index 0653513184..6869a3a213 100644 --- a/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -47,5 +47,6 @@ public enum Action implements Actions { scaleOut, recreateInstance, addMembers, - removeMembers + removeMembers, + forCustomWorkflow } diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index 82b86f89cc..84a80e6617 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -225,6 +225,17 @@ <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> + <dependency> + <groupId>org.onap.aaf.authz</groupId> + <artifactId>aaf-cadi-aaf</artifactId> + <version>2.1.9</version> + <exclusions> + <exclusion> + <groupId>javax.servlet</groupId> + <artifactId>servlet-api</artifactId> + </exclusion> + </exclusions> + </dependency> </dependencies> <build> diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java index d0302f2e59..88c4bc3b04 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -45,5 +45,6 @@ public enum Action implements Actions { scaleOut, recreateInstance, addMembers, - removeMembers + removeMembers, + forCustomWorkflow } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index fb7ab3a61e..e9f17c42d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -61,7 +61,8 @@ public class CamundaRequestHandler { if (context.getRetryCount() == 0) { logger.info("Querying Camunda for process-instance history for requestId: {}", requestId); } else { - logger.info("Retry: Querying Camunda for process-instance history for requestId: {}", + logger.info( + "Retry: Querying Camunda for process-instance history for retryCount: {} and requestId: {}", context.getRetryCount(), requestId); } return restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index d3bd769386..dbdc274bc6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -96,7 +96,7 @@ public class InstanceManagement { @Operation(description = "Execute custom workflow", responses = @ApiResponse( content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional - public Response executeCustomWorkflow(String request, @PathParam("version") String version, + public Response executeVNFCustomWorkflow(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException { @@ -109,6 +109,26 @@ public class InstanceManagement { requestContext); } + @POST + @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/pnfs/{pnfId}/workflows/{workflowUuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(description = "Execute custom workflow", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Transactional + public Response executePNFCustomWorkflow(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("pnfId") String pnfId, + @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("pnfId", pnfId); + instanceIdMap.put("workflowUuid", workflowUuid); + return processPNFCustomWorkflowRequest(request, Action.forCustomWorkflow, instanceIdMap, version, requestId, + requestContext); + } + private Response processCustomWorkflowRequest(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException { @@ -217,6 +237,93 @@ public class InstanceManagement { recipeLookupResult.getOrchestrationURI(), requestScope); } + private Response processPNFCustomWorkflowRequest(String requestJSON, Actions action, + HashMap<String, String> instanceIdMap, String version, String requestId, + ContainerRequestContext requestContext) throws ApiException { + Boolean aLaCarte = false; + ServiceInstancesRequest sir; + String apiVersion = version.substring(1); + + String serviceInstanceId = ""; + String pnfId = ""; + String workflowUuid = ""; + if (instanceIdMap != null) { + serviceInstanceId = instanceIdMap.get("serviceInstanceId"); + pnfId = instanceIdMap.get("pnfId"); + workflowUuid = instanceIdMap.get("workflowUuid"); + } + + String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); + sir.setServiceInstanceId(serviceInstanceId); + sir.setPnfId(pnfId); + String requestScope = ModelType.pnf.name(); + InfraActiveRequests currentActiveReq = + msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); + + try { + requestHandlerUtils.validateHeaders(requestContext); + } catch (ValidationException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, + currentActiveReq); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); + + if (dup != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); + } + + RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid); + + try { + infraActiveRequestsClient.save(currentActiveReq); + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.toString()) + .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfId) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, null, aLaCarte, action)) + .setApiVersion(apiVersion).setRequestUri(requestUri).build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq, String workflowUuid) throws ApiException { RecipeLookupResult recipeLookupResult = null; 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 2307a18c1a..e3e840bbcd 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 @@ -301,7 +301,7 @@ public class MsoRequest { if (servInsReq.getRequestDetails().getCloudConfiguration() != null) { CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration(); if (cloudConfiguration.getLcpCloudRegionId() != null) { - aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); + aq.setCloudRegion(cloudConfiguration.getLcpCloudRegionId()); } if (cloudConfiguration.getTenantId() != null) { @@ -318,9 +318,16 @@ public class MsoRequest { aq.setVnfId(servInsReq.getVnfInstanceId()); } + if (servInsReq.getPnfId() != null) { + aq.setRequestScope(requestScope); + aq.setPnfId(servInsReq.getPnfId()); + } + if (ModelType.service.name().equalsIgnoreCase(requestScope)) { - if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { - aq.setServiceInstanceName(requestInfo.getInstanceName()); + if (servInsReq.getRequestDetails().getRequestInfo() != null) { + if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { + aq.setServiceInstanceName(requestInfo.getInstanceName()); + } } } 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 6ccef65e46..ae68cc6032 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 @@ -44,6 +44,7 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.EnumUtils; import org.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ApiException; @@ -70,6 +71,7 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; @@ -130,31 +132,36 @@ public class OrchestrationRequests { infraActiveRequest = infraActiveRequestLookup(requestId); - try { - requestProcessingData = requestsDbClient.getExternalRequestProcessingDataBySoRequestId(requestId); - } catch (Exception e) { - logger.error("Exception occurred while communicating with RequestDb during requestProcessingData lookup ", - e); - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + if (isRequestProcessingDataRequired(format)) { + try { + requestProcessingData = requestsDbClient.getExternalRequestProcessingDataBySoRequestId(requestId); + } catch (Exception e) { + logger.error( + "Exception occurred while communicating with RequestDb during requestProcessingData lookup ", + e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError) + .build(); - ValidateException validateException = new ValidateException.Builder( - "Exception occurred while communicating with RequestDb during requestProcessingData lookup", - HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) - .errorInfo(errorLoggerInfo).build(); + ValidateException validateException = new ValidateException.Builder( + "Exception occurred while communicating with RequestDb during requestProcessingData lookup", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); - throw validateException; + throw validateException; + } } Request request = mapInfraActiveRequestToRequest(infraActiveRequest, includeCloudRequest, format); - if (!requestProcessingData.isEmpty()) { + if (null != requestProcessingData && !requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } request.setRequestId(requestId); orchestrationResponse.setRequest(request); - return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion); + return builder.buildResponse(HttpStatus.SC_OK, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), orchestrationResponse, + apiVersion); } @GET @@ -196,21 +203,26 @@ public class OrchestrationRequests { orchestrationList = new GetOrchestrationListResponse(); List<RequestList> requestLists = new ArrayList<>(); + for (InfraActiveRequests infraActive : activeRequests) { - List<RequestProcessingData> requestProcessingData = - requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); RequestList requestList = new RequestList(); Request request = mapInfraActiveRequestToRequest(infraActive, includeCloudRequest, format); - if (!requestProcessingData.isEmpty()) { - request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + if (isRequestProcessingDataRequired(format)) { + List<RequestProcessingData> requestProcessingData = + requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); + if (null != requestProcessingData && !requestProcessingData.isEmpty()) { + request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + } } + requestList.setRequest(request); requestLists.add(requestList); } orchestrationList.setRequestList(requestLists); - return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); + return builder.buildResponse(HttpStatus.SC_OK, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), orchestrationList, + apiVersion); } @POST @@ -524,6 +536,14 @@ public class OrchestrationRequests { return addedRequestProcessingData; } + protected boolean isRequestProcessingDataRequired(String format) { + if (StringUtils.isNotEmpty(format) && format.equalsIgnoreCase(OrchestrationRequestFormat.SIMPLE.name())) { + return false; + } else { + return true; + } + } + protected InfraActiveRequests infraActiveRequestLookup(String requestId) throws ApiException { InfraActiveRequests infraActiveRequest = null; try { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index b078aed6ac..0c6ad0ba22 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -275,12 +275,18 @@ public class RequestHandlerUtils extends AbstractRestHandler { } else if (action == Action.addMembers || action == Action.removeMembers) { return (ModelType.instanceGroup.toString()); } else { - String requestScope; + String requestScope = requestScopeFromUri(requestUri);; + + if (sir.getRequestDetails() == null) { + return requestScope; + } + if (sir.getRequestDetails().getModelInfo() == null) { + return requestScope; + } if (sir.getRequestDetails().getModelInfo().getModelType() == null) { - requestScope = requestScopeFromUri(requestUri); - } else { - requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); + return requestScope; } + requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); return requestScope; } } @@ -505,6 +511,9 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); } + if (instanceIdMap.get("PnfId") != null) { + currentActiveReq.setPnfId(instanceIdMap.get("PnfId")); + } } } @@ -610,6 +619,8 @@ public class RequestHandlerUtils extends AbstractRestHandler { requestScope = ModelType.configuration.name(); } else if (requestUri.contains(ModelType.vnf.name())) { requestScope = ModelType.vnf.name(); + } else if (requestUri.contains(ModelType.pnf.name())) { + requestScope = ModelType.pnf.name(); } else { requestScope = ModelType.service.name(); } @@ -632,7 +643,7 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (infraActiveRequest != null) { request.setTenantId(infraActiveRequest.getTenantId()); request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId)); - request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); + request.setCloudRegion(infraActiveRequest.getCloudRegion()); request.setRequestScope(infraActiveRequest.getRequestScope()); request.setRequestAction(infraActiveRequest.getRequestAction()); setInstanceIdAndName(infraActiveRequest, request); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SecurityFilters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SecurityFilters.java new file mode 100644 index 0000000000..0cf63b9605 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SecurityFilters.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.Ordered; + +@Configuration +@Profile("aaf") +public class SecurityFilters { + + @Bean + public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() { + FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>(); + filterRegistrationBean.setFilter(new SoCadiFilter()); + filterRegistrationBean.setName("cadiFilter"); + filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); + return filterRegistrationBean; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index a1779ba0fd..175b212c86 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -1176,7 +1176,7 @@ public class ServiceInstances extends AbstractRestHandler { protected void setCloudConfigurationCurrentActiveRequest(CloudConfiguration cloudConfiguration, InfraActiveRequests currentActiveRequest) { if (cloudConfiguration.getLcpCloudRegionId() != null) { - currentActiveRequest.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); + currentActiveRequest.setCloudRegion(cloudConfiguration.getLcpCloudRegionId()); } if (cloudConfiguration.getTenantId() != null) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoCadiFilter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoCadiFilter.java new file mode 100644 index 0000000000..6510440991 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoCadiFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP SO + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ +package org.onap.so.apihandlerinfra; + +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("aaf") +public class SoCadiFilter extends CadiFilter { + + protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class); + + private static String AFT_ENVIRONMENT_VAR = "AFT_ENVIRONMENT"; + private static String AAF_API_VERSION = "aaf_api_version"; + + @Value("${mso.config.cadi.cadiLoglevel:#{null}}") + private String cadiLoglevel; + + @Value("${mso.config.cadi.cadiKeyFile:#{null}}") + private String cadiKeyFile; + + @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}") + private String cadiTrustStorePassword; + + @Value("${mso.config.cadi.cadiTrustStore:#{null}}") + private String cadiTrustStore; + + @Value("${mso.config.cadi.cadiLatitude:#{null}}") + private String cadiLatitude; + + @Value("${mso.config.cadi.cadiLongitude:#{null}}") + private String cadiLongitude; + + @Value("${mso.config.cadi.aafEnv:#{null}}") + private String aafEnv; + + @Value("${mso.config.cadi.aafApiVersion:#{null}}") + private String aafApiVersion; + + @Value("${mso.config.cadi.aafRootNs:#{null}}") + private String aafRootNs; + + @Value("${mso.config.cadi.aafId:#{null}}") + private String aafMechId; + + @Value("${mso.config.cadi.aafPassword:#{null}}") + private String aafMechIdPassword; + + @Value("${mso.config.cadi.aafLocateUrl:#{null}}") + private String aafLocateUrl; + + @Value("${mso.config.cadi.aafUrl:#{null}}") + private String aafUrl; + + @Value("${mso.config.cadi.apiEnforcement:#{null}}") + private String apiEnforcement; + + private void checkIfNullProperty(String key, String value) { + /* + * When value is null, it is not defined in application.yaml set nothing in System properties + */ + if (value != null) { + System.setProperty(key, value); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel); + checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword); + checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude); + checkIfNullProperty(Config.AAF_ENV, aafEnv); + checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion); + checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs); + checkIfNullProperty(Config.AAF_APPID, aafMechId); + checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword); + checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl); + checkIfNullProperty(Config.AAF_URL, aafUrl); + checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement); + // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv); + logger.debug(" *** init Filter Config *** "); + super.init(filterConfig); + } + + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java index 632f371af5..a0f4615f87 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java @@ -24,33 +24,57 @@ package org.onap.so.apihandlerinfra; import org.onap.so.security.MSOSpringFirewall; import org.onap.so.security.WebSecurityConfig; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; +import org.springframework.context.annotation.Profile; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.firewall.StrictHttpFirewall; import org.springframework.util.StringUtils; @EnableWebSecurity @Configuration("att-security-config") -@Order(2) +// @Order(2) public class WebSecurityConfigImpl extends WebSecurityConfig { + @Profile({"basic", "test"}) + @Bean + public WebSecurityConfigurerAdapter basicAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() + .httpBasic(); + } - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and() - .httpBasic(); + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(WebSecurityConfigImpl.this.userDetailsService()) + .passwordEncoder(WebSecurityConfigImpl.this.passwordEncoder()); + } + }; } - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); + @Profile("aaf") + @Bean + public WebSecurityConfigurerAdapter noAuth() { + return new WebSecurityConfigurerAdapter() { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers("/**").permitAll(); + } + }; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java index 01e3de99ec..c05ef98fbb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -35,13 +35,13 @@ public class CustomWorkflowValidation implements ValidationRule { CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); if (cloudConfiguration == null) { - throw new ValidationException("cloudConfiguration"); + // throw new ValidationException("cloudConfiguration"); } else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner()))) { - throw new ValidationException("cloudOwner"); + // throw new ValidationException("cloudOwner"); } else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId()))) { - throw new ValidationException("lcpCloudRegionId"); + // throw new ValidationException("lcpCloudRegionId"); } else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId()))) { - throw new ValidationException("tenantId"); + // throw new ValidationException("tenantId"); } if (requestParameters == null) { throw new ValidationException("requestParameters"); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-aaf.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-aaf.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-aaf.yaml diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-basic.yaml b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-basic.yaml new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/resources/application-basic.yaml diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java index 0ce8113dcb..979aa8fbb1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java @@ -62,7 +62,7 @@ public class E2EServiceInstancesTest extends BaseTest { wireMockServer.stubFor(post(urlPathEqualTo("/testOrchestrationUri")).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson( - "{\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"tenantId\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")) + "{\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"tenantId\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"cloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); Service defaultService = new Service(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java index 276f891eb2..5c78af3601 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -31,7 +31,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; import java.io.File; import java.io.IOException; @@ -85,7 +85,7 @@ public class InstanceManagementTest extends BaseTest { headers.set(TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); headers.set(REQUESTOR_ID, "xxxxxx"); try { // generate one-time port number to avoid RANDOM port number later. initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); @@ -172,4 +172,32 @@ public class InstanceManagementTest extends BaseTest { ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + + @Test + public void executePNFCustomWorkflow() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingPNFWorkflow")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/workflow/search/findByArtifactUUID[?]artifactUUID=81526781-e55c-4cb7-adb3-97e09d9c76bf")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("workflow_pnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response + ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); + RequestReferences requestReferences = new RequestReferences(); + requestReferences.setInstanceId("1882939"); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d")); + expectedResponse.setRequestReferences(requestReferences); + uri = instanceManagementUri + "v1" + + "/serviceInstances/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testpnfcId/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf"; + ResponseEntity<String> response = + sendRequest(inputStream("/ExecutePNFCustomWorkflow.json"), uri, HttpMethod.POST, headers); + + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java index 8881a08ff3..b8d1e56cf7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java @@ -26,24 +26,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static org.onap.logging.filter.base.Constants.HttpHeaders.ECOMP_REQUEST_ID; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.INVOCATION_ID; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.PARTNER_NAME; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_CODE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.LOG_TIMESTAMP; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; -import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; import java.io.IOException; -import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.junit.Test; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.tasksbeans.RequestDetails; import org.onap.so.apihandlerinfra.tasksbeans.RequestInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference; @@ -59,7 +48,6 @@ import org.springframework.web.util.UriComponentsBuilder; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; -import ch.qos.logback.classic.spi.ILoggingEvent; public class ManualTasksTest extends BaseTest { @@ -89,7 +77,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); UriComponentsBuilder builder = @@ -108,34 +96,6 @@ public class ManualTasksTest extends BaseTest { // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(LOG_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("202", mdc.get(RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); - assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); - assertEquals("COMPLETE", mdc.get(RESPONSE_STATUS_CODE)); - assertNotNull(mdc.get(RESPONSE_DESCRIPTION)); - assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } } @Test @@ -152,7 +112,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<String> entity = new HttpEntity<String>(invalidRequest, headers); UriComponentsBuilder builder = @@ -188,7 +148,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); UriComponentsBuilder builder = @@ -228,7 +188,7 @@ public class ManualTasksTest extends BaseTest { headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); headers.set(ECOMP_REQUEST_ID, "987654321"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); UriComponentsBuilder builder = diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index e64f689624..aa6a3836c1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -45,6 +45,7 @@ import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; @@ -64,7 +65,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -143,6 +143,7 @@ public class OrchestrationRequestsTest extends BaseTest { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "1e45215d-b7b3-4c5a-9316-65bdddaf649f"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); UriComponentsBuilder builder = UriComponentsBuilder @@ -158,7 +159,41 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-1a18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("1e45215d-b7b3-4c5a-9316-65bdddaf649f", response.getHeaders().get("X-TransactionID").get(0)); + assertNotNull(response.getBody().getRequest().getFinishTime()); + } + + @Test + public void getOrchestrationRequestSimpleTest() throws Exception { + setupTestGetOrchestrationRequest(); + // TEST VALID REQUEST + GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); + + Request request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); + request.setRequestProcessingData(null); + testResponse.setRequest(request); + + String testRequestId = request.getRequestId(); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "e5e3c007-9fe9-4a20-8691-bdd20e14504d"); + HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder + .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)) + .queryParam("format", "simple"); + + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") + .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); + assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); + assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); + assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); + assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); + assertEquals("e5e3c007-9fe9-4a20-8691-bdd20e14504d", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } @@ -230,6 +265,7 @@ public class OrchestrationRequestsTest extends BaseTest { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set(ONAPLogConstants.Headers.REQUEST_ID, "0321e28d-3dde-4b31-9b28-1e0f07231b93"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( @@ -246,7 +282,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - assertEquals("00032ab7-3fb3-42e5-965d-8ea592502017", response.getHeaders().get("X-TransactionID").get(0)); + assertEquals("0321e28d-3dde-4b31-9b28-1e0f07231b93", response.getHeaders().get("X-TransactionID").get(0)); } @Test @@ -448,6 +484,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertThat(actualProcessingData, sameBeanAs(expectedDataList)); } + public void setupTestGetOrchestrationRequest() throws Exception { // For testGetOrchestrationRequest wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-1a18-42e5-965d-8ea592502018")) diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java index d0561a4518..abdf38dfa6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java @@ -32,7 +32,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; import java.io.IOException; import java.net.MalformedURLException; @@ -99,7 +99,7 @@ public class RequestHandlerUtilsTest extends BaseTest { headers.set(TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); headers.set(REQUESTOR_ID, "xxxxxx"); try { // generate one-time port number to avoid RANDOM port number later. initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java index d0b16cffe6..557771d298 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -104,7 +104,7 @@ public class RequestHandlerUtilsUnitTest { private void setInfraActiveRequest() throws IOException { infraActiveRequest.setTenantId("tenant-id"); infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); - infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setCloudRegion("cloudRegion"); infraActiveRequest.setRequestScope("service"); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); @@ -119,7 +119,7 @@ public class RequestHandlerUtilsUnitTest { currentActiveRequest.setStartTime(startTimeStamp); currentActiveRequest.setTenantId("tenant-id"); currentActiveRequest.setRequestBody(getRequestBody("/RequestBodyNewRequestorId.json")); - currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setCloudRegion("cloudRegion"); currentActiveRequest.setRequestScope("service"); currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); @@ -446,7 +446,7 @@ public class RequestHandlerUtilsUnitTest { @Test public void checkForDuplicateRequestsTest() throws ApiException { InfraActiveRequests currentActiveReq = new InfraActiveRequests(); - currentActiveReq.setAicCloudRegion("testRegion"); + currentActiveReq.setCloudRegion("testRegion"); currentActiveReq.setRequestId("792a3158-d9a3-49fd-b3ac-ab09842d6a1a"); Action action = Action.createInstance; String requestScope = ModelType.service.toString(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java index 7f5f0dc931..7191e297ec 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -149,7 +149,7 @@ public class ResumeOrchestrationRequestTest { private void setInfraActiveRequest() throws IOException { infraActiveRequest.setTenantId("tenant-id"); infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); - infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setCloudRegion("cloudRegion"); infraActiveRequest.setRequestScope(SERVICE); infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); @@ -173,7 +173,7 @@ public class ResumeOrchestrationRequestTest { currentActiveRequest.setStartTime(startTimeStamp); currentActiveRequest.setTenantId("tenant-id"); currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); - currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setCloudRegion("cloudRegion"); currentActiveRequest.setRequestScope(SERVICE); currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); 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 39308058b5..006b82ac58 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 @@ -29,14 +29,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_PARTNER_NAME; import static org.onap.logging.filter.base.Constants.HttpHeaders.ONAP_REQUEST_ID; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; import static org.onap.logging.filter.base.Constants.HttpHeaders.TRANSACTION_ID; -import static org.onap.logging.filter.base.Constants.HttpHeaders.CLIENT_ID; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -81,7 +80,6 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; -import ch.qos.logback.classic.spi.ILoggingEvent; public class ServiceInstancesTest extends BaseTest { @@ -113,7 +111,7 @@ public class ServiceInstancesTest extends BaseTest { headers.set(TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); - headers.set(CLIENT_ID, "VID"); + headers.set(ONAP_PARTNER_NAME, "VID"); headers.set(REQUESTOR_ID, "xxxxxx"); try { // generate one-time port number to avoid RANDOM port number later. initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); @@ -214,37 +212,6 @@ public class ServiceInstancesTest extends BaseTest { assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); - - - - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", - mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("202", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", - mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETE", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); - assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); - assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); - assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } } @Test @@ -397,15 +364,6 @@ public class ServiceInstancesTest extends BaseTest { .withStatus(HttpStatus.SC_NOT_FOUND))); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); - - for (ILoggingEvent logEvent : TestAppender.events) { - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertNotNull(mdc.get("PartnerName")); - } - } } @Test @@ -1419,7 +1377,7 @@ public class ServiceInstancesTest extends BaseTest { @Test public void replaceVfModuleInstanceNoCloudConfigurationTest() throws IOException { wireMockServer.stubFor( - get(urlPathEqualTo("/aai/v17/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) + get(urlPathEqualTo("/aai/v19/network/generic-vnfs/generic-vnf/ff305d54-75b4-431b-adb2-eb6b9e5ff000")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("infra/Vnf.json").withStatus(org.apache.http.HttpStatus.SC_OK))); wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) @@ -2645,15 +2603,6 @@ public class ServiceInstancesTest extends BaseTest { ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertEquals(response.getHeaders().get(TRANSACTION_ID).get(0), "32807a28-1a14-4b88-b7b3-2950918aa76d"); - - for (ILoggingEvent logEvent : TestAppender.events) { - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertEquals("VID", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - } - } } @Test diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java index 5c3ac0f461..d399de0b7a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesUnitTest.java @@ -95,6 +95,6 @@ public class ServiceInstancesUnitTest { serviceInstances.setCloudConfigurationCurrentActiveRequest(cloudConfiguration, currentActiveRequest); assertEquals("tenantId", currentActiveRequest.getTenantId()); - assertEquals("lcpCloudRegionId", currentActiveRequest.getAicCloudRegion()); + assertEquals("lcpCloudRegionId", currentActiveRequest.getCloudRegion()); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java index cfb865c9e1..2e9576cf7c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java @@ -28,12 +28,9 @@ 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.urlPathEqualTo; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import java.io.File; import java.nio.file.Files; import java.util.List; -import java.util.Map; import javax.ws.rs.core.MediaType; import org.junit.BeforeClass; import org.junit.Rule; @@ -48,7 +45,6 @@ import org.onap.so.client.grm.beans.ServiceEndPointLookupRequest; import org.onap.so.client.grm.beans.ServiceEndPointRequest; import org.onap.so.client.grm.exceptions.GRMClientCallFailed; import org.slf4j.MDC; -import ch.qos.logback.classic.spi.ILoggingEvent; public class GRMClientTest extends BaseTest { @@ -79,36 +75,10 @@ public class GRMClientTest extends BaseTest { List<ServiceEndPoint> list = sel.getServiceEndPointList(); assertEquals(3, list.size()); - boolean foundInvoke = false; - boolean foundInvokeReturn = false; - for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOMetricLogClientFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("GRM", mdc.get("TargetEntity")); - assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvoke = true; - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOMetricLogClientFilter") - && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE-RETURN")) { - Map<String, String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvokeReturn = true; - } - - if (!foundInvoke) - fail("INVOKE Marker not found"); - - if (!foundInvokeReturn) - fail("INVOKE RETURN Marker not found"); - wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) .withHeader(ONAPLogConstants.Headers.INVOCATION_ID.toString(), matching(uuidRegex)) .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); - TestAppender.events.clear(); + .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO.APIH"))); } @Test diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json new file mode 100644 index 0000000000..63021b611f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json @@ -0,0 +1,20 @@ +{ + "requestDetails": { + "requestParameters": { + "userParams": [{ + "nrmObj": { + "EUtranGenericCell" : [ + {"cellLocalId":1, "pci":5}, + {"cellLocalId":2, "pci":6} + ], + "ExternalEUtranCell" : [ + {"cellLocalId":3, "eNBId": "x"}, + {"cellLocalId":4, "eNBId": "y"} + ], + "EUtranRelation": [{"scellLocalId":5, "tcellLocalId":6}] + } + }], + "payload": "[{\"GNBDUFunction\":{\"gNBId\":1,\"gNBDUId\":5}}]" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json index 81b574285c..c79900a15d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json @@ -22,7 +22,7 @@ "vfModuleId":null, "vfModuleName":null, "vfModuleModelName":null, - "aicCloudRegion":"n6", + "cloudRegion":"n6", "callBackUrl":null, "correlator":null, "serviceInstanceId":"9e15a443-af65-4f05-9000-47ae495e937d", @@ -41,4 +41,4 @@ }, "requestURI":"http://localhost:8087/infraActiveRequests/%1$s" -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json index 8d52acbe0d..db33df4d76 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json @@ -21,7 +21,7 @@ "vfModuleId": null, "vfModuleName": null, "vfModuleModelName": null, - "aicCloudRegion": "n6", + "cloudRegion": "n6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "9e15a443-af65-4f05-9000-47ae495e937d", @@ -45,4 +45,4 @@ "href": "http://localhost:8087/infraActiveRequests/%1$s" } } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json index 539851ce57..f36ae0f9da 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json @@ -22,7 +22,7 @@ "vfModuleId": null, "vfModuleName": null, "vfModuleModelName": null, - "aicCloudRegion": "n6", + "cloudRegion": "n6", "callBackUrl": null, "correlator": null, "serviceInstanceId": "9e15a443-af65-4f05-9000-47ae495e937d", @@ -46,4 +46,4 @@ "href": "http://localhost:8087/infraActiveRequests/%1$s" } } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json new file mode 100644 index 0000000000..133d8bed9b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_pnf_Response.json @@ -0,0 +1,5 @@ +{ + "artifactUUID": "81526781-e55c-4cb7-adb3-97e09d9c76bf", + "artifactName": "testingPNFWorkflow.bpmn", + "name": "testingPNFWorkflow" +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json index a0a4c14c10..eef0776f5d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/VnfLookup.json @@ -16,7 +16,7 @@ "requestBody":"{\"requestDetails\": {\"relatedInstanceList\": [{\"relatedInstance\": {\"instanceId\": \"f5435110-b276-4920-9261-a18a5582d357\", \"modelInfo\": {\"modelVersionId\": \"bad955c3-29b2-4a27-932e-28e942cc6480\", \"modelVersion\": \"1\", \"modelName\": \"Vf zrdm5bpxmc02092017-Service\", \"modelInvariantId\": \"b16a9398-ffa3-4041-b78c-2956b8ad9c7b\", \"modelType\": \"service\"}}}], \"requestParameters\": {\"userParams\": [], \"enforceValidNfValues\": false, \"testApi\": \"GR_API\"}, \"lineOfBusiness\": {\"lineOfBusinessName\": \"vSAMP12_14-2XXX-Aug18-9001 - LOB\"}, \"requestInfo\": {\"source\": \"VID\", \"requestorId\": \"az2016\", \"instanceName\": \"Robot_VNF_For_Volume_Group\", \"suppressRollback\": false, \"productFamilyId\": \"06f76284-8710-11e6-ae22-56b6b6499611\"}, \"platform\": {\"platformName\": \"vSAMP12_14-2XXX-Aug18-9001 - Platform\"}, \"modelInfo\": {\"modelName\": \"Vf zrdm5bpxmc02092017-VF\", \"modelVersion\": \"1\", \"modelInvariantId\": \"23122c9b-dd7f-483f-bf0a-e069303db2f7\", \"modelType\": \"vnf\", \"modelCustomizationName\": \"Vf zrdm5bpxmc02092017-VF 0\", \"modelVersionId\": \"d326f424-2312-4dd6-b7fe-364fadbd1ef5\", \"modelCustomizationId\": \"96c23a4a-6887-4b2c-9cce-1e4ea35eaade\"}, \"cloudConfiguration\": {\"cloudOwner\": \"cloudOwner\", \"tenantId\": \"0422ffb57ba042c0800a29dc85ca70f8\", \"lcpCloudRegionId\": \"regionOne\"}}}", "lastModifiedBy":"CamundaBPMN", "modifyTime":"2019-11-11T19:29:15.000+0000", - "aicCloudRegion":"regionOne", + "cloudRegion":"regionOne", "serviceInstanceId":"f5435110-b276-4920-9261-a18a5582d357", "requestScope":"vnf", "requestAction":"createInstance", 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 a93ffd46a8..050780c9a2 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 @@ -809,6 +809,10 @@ CREATE TABLE `service` ( `OVERALL_DISTRIBUTION_STATUS` varchar(45), `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, `NAMING_POLICY` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -963,6 +967,7 @@ CREATE TABLE `vf_module_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`ID`), KEY `fk_vf_module_customization__vf_module1_idx` (`VF_MODULE_MODEL_UUID`), KEY `fk_vf_module_customization__heat_env__heat_environment1_idx` (`HEAT_ENVIRONMENT_ARTIFACT_UUID`), @@ -1113,6 +1118,7 @@ CREATE TABLE `vnf_resource_customization` ( `SERVICE_MODEL_UUID` varchar(200) NOT NULL, `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1193,6 +1199,7 @@ CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( `RESOURCE_INPUT` varchar(2000) DEFAULT NULL, `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -1255,6 +1262,7 @@ CREATE TABLE `infra_active_requests` ( `END_TIME` datetime DEFAULT NULL, `SOURCE` varchar(45) DEFAULT NULL, `VNF_ID` varchar(45) DEFAULT NULL, + `PNF_ID` varchar(45) DEFAULT NULL, `VNF_NAME` varchar(80) DEFAULT NULL, `VNF_TYPE` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(45) DEFAULT NULL, diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java index 257e319ce5..927477e146 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepository.java @@ -41,7 +41,7 @@ public interface InfraActiveRequestsRepository List<InfraActiveRequests> findByStartTimeLessThanAndEndTime(Date startTime, Date endTime, Pageable request); - @Query(value = "SELECT * FROM infra_active_requests WHERE request_status = 'IN_PROGRESS' AND (request_scope = 'volumeGroup' OR request_scope = 'vfModule') AND start_time < (NOW() - INTERVAL 2 MINUTE)", - nativeQuery = true) + @Query(value = "SELECT * FROM infra_active_requests WHERE request_status = 'IN_PROGRESS' AND (request_scope = 'volumeGroup' OR request_scope = 'vfModule') AND start_time < (NOW() - INTERVAL 2 MINUTE)" + + " ORDER BY start_time DESC", nativeQuery = true) List<InfraActiveRequests> getInProgressVolumeGroupsAndVfModules(); } diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java index 445fd6355f..bba0ad4696 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java @@ -245,6 +245,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep mapKey = "serviceInstanceName"; } else if ("vnfInstanceId".equalsIgnoreCase(mapKey)) { mapKey = "vnfId"; + } else if ("pnfId".equalsIgnoreCase(mapKey)) { + mapKey = "pnfId"; } else if ("vnfInstanceName".equalsIgnoreCase(mapKey)) { mapKey = "vnfName"; } else if ("vfModuleInstanceId".equalsIgnoreCase(mapKey)) { @@ -264,7 +266,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep } else if (mapKey.equalsIgnoreCase("configurationInstanceName")) { mapKey = "configurationName"; } else if ("lcpCloudRegionId".equalsIgnoreCase(mapKey)) { - mapKey = "aicCloudRegion"; + mapKey = "cloudRegion"; } else if ("tenantId".equalsIgnoreCase(mapKey)) { mapKey = "tenantId"; } else if ("modelType".equalsIgnoreCase(mapKey)) { 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 feda0338a6..d2b3a71cad 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 @@ -64,6 +64,7 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( END_TIME VARCHAR, SOURCE VARCHAR SELECTIVITY 2, VNF_ID VARCHAR SELECTIVITY 15, + PNF_ID VARCHAR SELECTIVITY 15, VNF_NAME VARCHAR SELECTIVITY 11, VNF_TYPE VARCHAR SELECTIVITY 5, SERVICE_TYPE VARCHAR SELECTIVITY 1, diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java index 2d44eebacd..8c4d0718b1 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/ArchivedInfraRequests.java @@ -70,7 +70,7 @@ public class ArchivedInfraRequests extends InfraRequests { .append("lastModifiedBy", getLastModifiedBy()).append("modifyTime", getModifyTime()) .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName()) .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName()) - .append("vfModuleModelName", getVfModuleModelName()).append("aicCloudRegion", getAicCloudRegion()) + .append("vfModuleModelName", getVfModuleModelName()).append("cloudRegion", getCloudRegion()) .append("callBackUrl", getCallBackUrl()).append("correlator", getCorrelator()) .append("serviceInstanceId", getServiceInstanceId()) .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope()) 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 9d76e289ab..5848f3b3d9 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 @@ -72,13 +72,13 @@ public class InfraActiveRequests extends InfraRequests { .append("statusMessage", getStatusMessage()).append("progress", getProgress()) .append("startTime", getStartTime()).append("endTime", getEndTime()).append("source", getSource()) .append("vnfId", getVnfId()).append("vnfName", getVnfName()).append("vnfType", getVnfType()) - .append("serviceType", getServiceType()).append("tenantId", getTenantId()) + .append("pnfId", getPnfId()).append("serviceType", getServiceType()).append("tenantId", getTenantId()) .append("vnfParams", getVnfParams()).append("vnfOutputs", getVnfOutputs()) .append("requestBody", getRequestBody()).append("responseBody", getResponseBody()) .append("lastModifiedBy", getLastModifiedBy()).append("modifyTime", getModifyTime()) .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName()) .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName()) - .append("vfModuleModelName", getVfModuleModelName()).append("aicCloudRegion", getAicCloudRegion()) + .append("vfModuleModelName", getVfModuleModelName()).append("CloudRegion", getCloudRegion()) .append("callBackUrl", getCallBackUrl()).append("correlator", getCorrelator()) .append("serviceInstanceId", getServiceInstanceId()) .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope()) 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 f36bf9058c..8f798a207c 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 @@ -74,6 +74,8 @@ public abstract class InfraRequests implements java.io.Serializable { private String source; @Column(name = "VNF_ID", length = 45) private String vnfId; + @Column(name = "PNF_ID", length = 45) + private String pnfId; @Column(name = "VNF_NAME", length = 80) private String vnfName; @Column(name = "VNF_TYPE", length = 200) @@ -106,7 +108,7 @@ public abstract class InfraRequests implements java.io.Serializable { @Column(name = "VF_MODULE_MODEL_NAME", length = 200) private String vfModuleModelName; @Column(name = "CLOUD_REGION", length = 11) - private String aicCloudRegion; + private String cloudRegion; @Column(name = "CALLBACK_URL", length = 200) private String callBackUrl; @Column(name = "CORRELATOR", length = 80) @@ -247,6 +249,14 @@ public abstract class InfraRequests implements java.io.Serializable { this.vnfId = vnfId; } + public String getPnfId() { + return this.pnfId; + } + + public void setPnfId(String pnfId) { + this.pnfId = pnfId; + } + public String getVnfName() { return this.vnfName; } @@ -363,12 +373,12 @@ public abstract class InfraRequests implements java.io.Serializable { this.vfModuleModelName = vfModuleModelName; } - public String getAicCloudRegion() { - return this.aicCloudRegion; + public String getCloudRegion() { + return this.cloudRegion; } - public void setAicCloudRegion(String aicCloudRegion) { - this.aicCloudRegion = aicCloudRegion; + public void setCloudRegion(String cloudRegion) { + this.cloudRegion = cloudRegion; } public String getCallBackUrl() { @@ -582,14 +592,14 @@ public abstract class InfraRequests implements java.io.Serializable { .append("flowStatus", getFlowStatus()).append("retryStatusMessage", getRetryStatusMessage()) .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime()) .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName()) - .append("vnfType", getVnfType()).append("serviceType", getServiceType()) + .append("pnfId", getPnfId()).append("vnfType", getVnfType()).append("serviceType", getServiceType()) .append("tenantId", getTenantId()).append("vnfParams", getVnfParams()) .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody()) .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy()) .append("modifyTime", getModifyTime()).append("volumeGroupId", getVolumeGroupId()) .append("volumeGroupName", getVolumeGroupName()).append("vfModuleId", getVfModuleId()) .append("vfModuleName", getVfModuleName()).append("vfModuleModelName", getVfModuleModelName()) - .append("aicCloudRegion", getAicCloudRegion()).append("callBackUrl", getCallBackUrl()) + .append("cloudRegion", getCloudRegion()).append("callBackUrl", getCallBackUrl()) .append("correlator", getCorrelator()).append("serviceInstanceId", getServiceInstanceId()) .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope()) .append("requestAction", getRequestAction()).append("networkId", getNetworkId()) diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java index 655ae60f47..334eb73da4 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java @@ -371,6 +371,41 @@ public class RequestsDbClient { String.class); } + public InfraActiveRequests getInfraActiveRequests(String requestId, String basicAuth, String host) { + RestTemplate template = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.AUTHORIZATION, basicAuth); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + URI uri = getUri(host + "/infraActiveRequests/" + requestId); + try { + InfraActiveRequests infraActiveRequests = template + .exchange(uri, HttpMethod.GET, new HttpEntity<>(headers), InfraActiveRequests.class).getBody(); + if (infraActiveRequests != null) { + infraActiveRequests.setRequestId(requestId); + } + return infraActiveRequests; + } catch (HttpClientErrorException e) { + if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) { + return null; + } + throw e; + } + } + + public void updateInfraActiveRequests(InfraActiveRequests request, String basicAuth, String host) { + RestTemplate template = new RestTemplate(); + template.getInterceptors().add(new SOSpringClientFilter()); + template.getInterceptors().add(new SpringClientPayloadFilter()); + HttpHeaders headers = new HttpHeaders(); + headers.set(HttpHeaders.AUTHORIZATION, basicAuth); + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + URI uri = getUri(host + "/infraActiveRequests/" + request.getRequestId()); + HttpEntity<InfraActiveRequests> entity = new HttpEntity<>(request, headers); + template.put(uri, entity); + } + protected URI getUri(String uri) { return URI.create(uri); } diff --git a/mso-catalog-db/pom.xml b/mso-catalog-db/pom.xml index 08e9719f50..610ed25096 100644 --- a/mso-catalog-db/pom.xml +++ b/mso-catalog-db/pom.xml @@ -102,5 +102,22 @@ <artifactId>asm-xml</artifactId> <version>6.1</version> </dependency> + <dependency> + <groupId>org.glassfish.jersey.core</groupId> + <artifactId>jersey-common</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>2.28.2</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito2</artifactId> + <version>2.0.4</version> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java index fabbc5007f..db0e0abd3c 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceCustomization.java @@ -83,6 +83,9 @@ public class PnfResourceCustomization implements Serializable { @Column(name = "SKIP_POST_INSTANTIATION_CONFIGURATION") private Boolean skipPostInstConf; + @Column(name = "CONTROLLER_ACTOR") + private String controllerActor; + @Override public String toString() { return new ToStringBuilder(this).append("modelCustomizationUUID", modelCustomizationUUID) @@ -90,7 +93,7 @@ public class PnfResourceCustomization implements Serializable { .append("nfFunction", nfFunction).append("nfType", nfType).append("nfRole", nfRole) .append("nfNamingCode", nfNamingCode).append("multiStageDesign", multiStageDesign) .append("pnfResources", pnfResources).append("blueprintName", blueprintName) - .append("blueprintVersion", blueprintVersion).toString(); + .append("blueprintVersion", blueprintVersion).append("controllerActor", controllerActor).toString(); } @Override @@ -222,4 +225,11 @@ public class PnfResourceCustomization implements Serializable { this.skipPostInstConf = skipPostInstConf; } + public String getControllerActor() { + return controllerActor; + } + + public void setControllerActor(String controllerActor) { + this.controllerActor = controllerActor; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceWorkflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceWorkflow.java new file mode 100644 index 0000000000..6e48938f19 --- /dev/null +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/PnfResourceWorkflow.java @@ -0,0 +1,91 @@ +package org.onap.so.db.catalog.beans; + +import java.io.Serializable; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; +import com.openpojo.business.annotation.BusinessKey; +import uk.co.blackpepper.bowman.annotation.LinkedResource; + +@Entity +@Table(name = "pnf_resource_to_workflow") +public class PnfResourceWorkflow implements Serializable { + + private static final long serialVersionUID = 4897166645148426088L; + + @Id + @Column(name = "ID", nullable = false, updatable = false) + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer ID; + + @BusinessKey + @Column(name = "PNF_RESOURCE_MODEL_UUID") + private String pnfResourceModelUUID; + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "PNF_RESOURCE_MODEL_UUID", updatable = false, insertable = false) + private PnfResource pnfResource; + + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @JoinColumn(name = "WORKFLOW_ID") + private Workflow workflow; + + @Override + public String toString() { + return new ToStringBuilder(this).append("pnfResourceModelUUID", pnfResourceModelUUID).toString(); + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof PnfResourceWorkflow)) { + return false; + } + PnfResourceWorkflow castOther = (PnfResourceWorkflow) other; + return new EqualsBuilder().append(pnfResourceModelUUID, castOther.pnfResourceModelUUID).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(pnfResourceModelUUID).toHashCode(); + } + + public Integer getID() { + return ID; + } + + public String getPnfResourceModelUUID() { + return pnfResourceModelUUID; + } + + public void setPnfResourceModelUUID(String pnfResourceModelUUID) { + this.pnfResourceModelUUID = pnfResourceModelUUID; + } + + @LinkedResource + public PnfResource getPnfResource() { + return pnfResource; + } + + public void setPnfResource(PnfResource pnfResource) { + this.pnfResource = pnfResource; + } + + @LinkedResource + public Workflow getWorkflow() { + return workflow; + } + + public void setWorkflow(Workflow workflow) { + this.workflow = workflow; + } +} diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java index e591552ebf..ab40cefb4e 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Service.java @@ -142,6 +142,18 @@ public class Service implements Serializable { @Column(name = "ONAP_GENERATED_NAMING") private Boolean onapGeneratedNaming; + @Column(name = "CDS_BLUEPRINT_NAME") + private String blueprintName; + + @Column(name = "CDS_BLUEPRINT_VERSION") + private String blueprintVersion; + + @Column(name = "SKIP_POST_INSTANTIATION_CONFIGURATION") + private Boolean skipPostInstConf; + + @Column(name = "CONTROLLER_ACTOR") + private String controllerActor; + @Override public String toString() { return new ToStringBuilder(this).append("modelName", modelName).append("description", description) @@ -399,4 +411,35 @@ public class Service implements Serializable { this.onapGeneratedNaming = onapGeneratedNaming; } + public String getBlueprintName() { + return blueprintName; + } + + public void setBlueprintName(String blueprintName) { + this.blueprintName = blueprintName; + } + + public String getBlueprintVersion() { + return blueprintVersion; + } + + public void setBlueprintVersion(String blueprintVersion) { + this.blueprintVersion = blueprintVersion; + } + + public Boolean isSkipPostInstConf() { + return skipPostInstConf; + } + + public void setSkipPostInstConf(Boolean skipPostInstConf) { + this.skipPostInstConf = skipPostInstConf; + } + + public String getControllerActor() { + return controllerActor; + } + + public void setControllerActor(String controllerActor) { + this.controllerActor = controllerActor; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java index 29f8bcece5..3420682900 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VfModuleCustomization.java @@ -100,6 +100,9 @@ public class VfModuleCustomization implements Serializable { @OneToMany(cascade = CascadeType.ALL, mappedBy = "vfModuleCustomization") private Set<CvnfcCustomization> cvnfcCustomization; + @Column(name = "SKIP_POST_INSTANTIATION_CONFIGURATION") + private Boolean skipPostInstConf; + @Override public boolean equals(final Object other) { if (!(other instanceof VfModuleCustomization)) { @@ -239,4 +242,12 @@ public class VfModuleCustomization implements Serializable { public void setCvnfcCustomization(Set<CvnfcCustomization> cvnfcCustomization) { this.cvnfcCustomization = cvnfcCustomization; } + + public Boolean isSkipPostInstConf() { + return skipPostInstConf; + } + + public void setSkipPostInstConf(Boolean skipPostInstConf) { + this.skipPostInstConf = skipPostInstConf; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java index aec1c7fb22..094a1f0bf3 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java @@ -124,6 +124,9 @@ public class VnfResourceCustomization implements Serializable { @Column(name = "NF_DATA_VALID") private Boolean nfDataValid; + @Column(name = "CONTROLLER_ACTOR") + private String controllerActor; + @Override public boolean equals(final Object other) { if (!(other instanceof VnfResourceCustomization)) { @@ -152,7 +155,8 @@ public class VnfResourceCustomization implements Serializable { .append("multiStageDesign", multiStageDesign).append("vnfResources", vnfResources) .append("vfModuleCustomizations", vfModuleCustomizations) .append("vnfcInstanceGroupOrder", vnfcInstanceGroupOrder) - .append("vnfcInstanceGroupCustomizations", vnfcInstanceGroupCustomizations).toString(); + .append("vnfcInstanceGroupCustomizations", vnfcInstanceGroupCustomizations) + .append("controllerActor", controllerActor).toString(); } @PrePersist @@ -345,5 +349,11 @@ public class VnfResourceCustomization implements Serializable { this.nfDataValid = nfDataValid; } + public String getControllerActor() { + return controllerActor; + } + public void setControllerActor(String controllerActor) { + this.controllerActor = controllerActor; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java index 6bd0713085..fc1c753e85 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/Workflow.java @@ -74,6 +74,9 @@ public class Workflow implements Serializable { private List<VnfResourceWorkflow> vnfResourceWorkflow; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "workflow") + private List<PnfResourceWorkflow> pnfResourceWorkflow; + + @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "workflow") private List<WorkflowActivitySpecSequence> workflowActivitySpecSequence; @PrePersist @@ -191,6 +194,15 @@ public class Workflow implements Serializable { } @LinkedResource + public List<PnfResourceWorkflow> getPnfResourceWorkflow() { + return pnfResourceWorkflow; + } + + public void setPnfResourceWorkflow(List<PnfResourceWorkflow> pnfResourceWorkflow) { + this.pnfResourceWorkflow = pnfResourceWorkflow; + } + + @LinkedResource public List<WorkflowActivitySpecSequence> getWorkflowActivitySpecSequence() { return workflowActivitySpecSequence; } @@ -207,6 +219,7 @@ public class Workflow implements Serializable { .append("resourceTarget", resourceTarget).append("source", source) .append("timeoutMinutes", timeoutMinutes).append("artifactChecksum", artifactChecksum) .append("created", created).append("vnfResourceWorkflow", vnfResourceWorkflow) + .append("pnfResourceWorkflow", pnfResourceWorkflow) .append("WorkflowActivitySpecSequence", workflowActivitySpecSequence).toString(); } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java index b74ade1e1f..91b74d4d6a 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/OrchestrationFlow.java @@ -34,7 +34,6 @@ import javax.persistence.Table; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; -import org.onap.so.db.catalog.beans.BuildingBlockDetail; import com.openpojo.business.annotation.BusinessKey; import uk.co.blackpepper.bowman.annotation.LinkedResource; @@ -65,6 +64,14 @@ public class OrchestrationFlow implements Serializable { @Column(name = "FLOW_VERSION") private Double flowVersion; + @BusinessKey + @Column(name = "ACTION") + private String bpmnAction; + + @BusinessKey + @Column(name = "SCOPE") + private String bpmnScope; + @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "NB_REQ_REF_LOOKUP_ID") private NorthBoundRequest northBoundRequest; @@ -73,7 +80,8 @@ public class OrchestrationFlow implements Serializable { public String toString() { return new ToStringBuilder(this).append("id", id).append("action", action) .append("sequenceNumber", sequenceNumber).append("flowName", flowName) - .append("flowVersion", flowVersion).toString(); + .append("flowVersion", flowVersion).append("bpmnAction", bpmnAction).append("bpmnScope", bpmnScope) + .toString(); } @Override @@ -83,13 +91,14 @@ public class OrchestrationFlow implements Serializable { } OrchestrationFlow castOther = (OrchestrationFlow) other; return new EqualsBuilder().append(action, castOther.action).append(sequenceNumber, castOther.sequenceNumber) - .append(flowName, castOther.flowName).append(flowVersion, castOther.flowVersion).isEquals(); + .append(flowName, castOther.flowName).append(flowVersion, castOther.flowVersion) + .append(bpmnAction, castOther.bpmnAction).append(bpmnScope, castOther.bpmnScope).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder().append(action).append(sequenceNumber).append(flowName).append(flowVersion) - .toHashCode(); + .append(bpmnAction).append(bpmnScope).toHashCode(); } public String getAction() { @@ -132,6 +141,22 @@ public class OrchestrationFlow implements Serializable { this.id = id; } + public String getBpmnAction() { + return bpmnAction; + } + + public void setBpmnAction(String bpmnAction) { + this.bpmnAction = bpmnAction; + } + + public String getBpmnScope() { + return bpmnScope; + } + + public void setBpmnScope(String bpmnScope) { + this.bpmnScope = bpmnScope; + } + @LinkedResource public NorthBoundRequest getNorthBoundRequest() { return northBoundRequest; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java index 8754673f40..7873d70bd4 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java @@ -133,6 +133,7 @@ public class CatalogDbClient { private static final String MODEL_VERSION = "modelVersion"; private static final String MODEL_INVARIANT_UUID = "modelInvariantUUID"; private static final String VNF_RESOURCE_MODEL_UUID = "vnfResourceModelUUID"; + private static final String PNF_RESOURCE_MODEL_UUID = "pnfResourceModelUUID"; private static final String NF_ROLE = "nfRole"; private static final String VF_MODULE_MODEL_UUID = "vfModuleModelUUID"; private static final String VNF_COMPONENT_TYPE = "vnfComponentType"; @@ -201,6 +202,7 @@ public class CatalogDbClient { private String findPnfResourceCustomizationByModelUuid = "/findPnfResourceCustomizationByModelUuid"; private String findWorkflowByArtifactUUID = "/findByArtifactUUID"; private String findWorkflowByModelUUID = "/findWorkflowByModelUUID"; + private String findWorkflowByPnfModelUUID = "/findWorkflowByPnfModelUUID"; private String findWorkflowBySource = "/findBySource"; private String findVnfResourceCustomizationByModelUuid = "/findVnfResourceCustomizationByModelUuid"; @@ -338,6 +340,7 @@ public class CatalogDbClient { findWorkflowByArtifactUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByArtifactUUID; findWorkflowByModelUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByModelUUID; + findWorkflowByPnfModelUUID = endpoint + WORKFLOW + SEARCH + findWorkflowByPnfModelUUID; findWorkflowBySource = endpoint + WORKFLOW + SEARCH + findWorkflowBySource; findVnfResourceCustomizationByModelUuid = @@ -998,6 +1001,11 @@ public class CatalogDbClient { .queryParam(VNF_RESOURCE_MODEL_UUID, vnfResourceModelUUID).build().toString())); } + public List<Workflow> findWorkflowByPnfModelUUID(String pnfResourceModelUUID) { + return this.getMultipleResources(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByPnfModelUUID) + .queryParam(PNF_RESOURCE_MODEL_UUID, pnfResourceModelUUID).build().toString())); + } + public List<Workflow> findWorkflowBySource(String source) { return this.getMultipleResources(workflowClient, getUri(UriBuilder.fromUri(findWorkflowBySource).queryParam(SOURCE, source).build().toString())); diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java index 8bcc60c8be..f1b399325e 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/WorkflowRepository.java @@ -39,10 +39,23 @@ public interface WorkflowRepository extends JpaRepository<Workflow, Integer> { * This operation is required by {@link org.onap.so.db.catalog.client.CatalogDbClient} to provide Workflow based on * model UUID without projection. * - * @param vnfResourceModelUUIDmodel UUID + * @param vnfResourceModelUUID UUID * @return List of Workflow */ @Query(value = "select b.* from vnf_resource_to_workflow a join workflow b where a.WORKFLOW_ID = b.ID and a.VNF_RESOURCE_MODEL_UUID = ?1", nativeQuery = true) List<Workflow> findWorkflowByModelUUID(String vnfResourceModelUUID); + + /** + * Used to fetch the @{link Workflow} by the Pnf Model UUID. + * + * This operation is required by {@link org.onap.so.db.catalog.client.CatalogDbClient} to provide Workflow based on + * pnf model UUID without projection. + * + * @param pnfResourceModelUUID UUID + * @return List of Workflow + */ + @Query(value = "select b.* from pnf_resource_to_workflow a join workflow b where a.WORKFLOW_ID = b.ID and a.PNF_RESOURCE_MODEL_UUID = ?1", + nativeQuery = true) + List<Workflow> findWorkflowByPnfModelUUID(String pnfResourceModelUUID); } diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java index b82c17dc84..d87ed517f4 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -20,23 +20,39 @@ package org.onap.so.db.catalog.client; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; +import java.util.List; import javax.persistence.EntityNotFoundException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.ArgumentMatchers; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import org.onap.so.db.catalog.beans.CvnfcCustomization; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResourceCustomization; +import uk.co.blackpepper.bowman.Client; +import org.onap.so.db.catalog.beans.Workflow; +@RunWith(PowerMockRunner.class) +@PrepareForTest(CatalogDbClient.class) public class CatalogDbClientTest { private CatalogDbClient catalogDbClient; + private CatalogDbClient mockedCatalogDbClient; + @Before public void init() { catalogDbClient = new CatalogDbClient(); + mockedCatalogDbClient = PowerMockito.spy(catalogDbClient); } @Rule @@ -171,4 +187,22 @@ public class CatalogDbClientTest { assertTrue(aCvnfc.getModelCustomizationUUID().equals("a123")); } + @Test + public final void testFindWorkflowByPnfModelUUID() throws Exception { + String pnfResourceModelUUID = "f2d1f2b2-88bb-49da-b716-36ae420ccbff"; + Workflow wf = new Workflow(); + wf.setArtifactUUID("b2fd5627-55e4-4f4f-8064-9e6f443e9152"); + wf.setArtifactName("DummyPnfWorkflow"); + wf.setVersion(1.0); + List<Workflow> wfList = new ArrayList<Workflow>(); + wfList.add(wf); + + PowerMockito.doReturn(wfList).when(mockedCatalogDbClient, "getMultipleResources", + ArgumentMatchers.<Client<Workflow>>any(), ArgumentMatchers.anyObject()); + List<Workflow> results = mockedCatalogDbClient.findWorkflowByPnfModelUUID(pnfResourceModelUUID); + assertEquals(wf.getArtifactUUID(), results.get(0).getArtifactUUID()); + assertEquals(wf.getArtifactName(), results.get(0).getArtifactName()); + assertEquals(wf.getVersion(), results.get(0).getVersion()); + } + } diff --git a/mso-catalog-db/src/test/resources/data.sql b/mso-catalog-db/src/test/resources/data.sql index eaad15ca57..e5963c183f 100644 --- a/mso-catalog-db/src/test/resources/data.sql +++ b/mso-catalog-db/src/test/resources/data.sql @@ -768,10 +768,15 @@ insert into pnf_resource_customization_to_service(service_model_uuid, resource_m insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values ('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow.bpmn', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); +insert into workflow(artifact_uuid, artifact_name, name, operation_name, version, description, body, resource_target, source) values +('b2fd5627-55e4-4f4f-8064-9e6f443e9152','DummyPnfWorkflow','Dummy Pnf Workflow','DummyPnfWorkflow',1.0,'Dummy Pnf Workflow to test custom Pnf workflow',null,'pnf','native'); insert into vnf_resource_to_workflow(vnf_resource_model_uuid, workflow_id) values ('ff2ae348-214a-11e7-93ae-92361f002671', '1'); +Insert into pnf_resource_to_workflow (`PNF_RESOURCE_MODEL_UUID`,`WORKFLOW_ID`) values +("ff2ae348-214a-11e7-93ae-92361f002680", 2); + insert into activity_spec(name, description, version) values ('testActivity1', 'Test Activity 1', 1); diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index 73370e1078..9037e431d4 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -736,6 +736,8 @@ CREATE TABLE `orchestration_flow_reference` ( `SEQ_NO` int(11) NOT NULL, `FLOW_NAME` varchar(200) NOT NULL, `FLOW_VERSION` double NOT NULL, + `SCOPE` varchar(200) DEFAULT NULL, + `ACTION` varchar(200) DEFAULT NULL, `NB_REQ_REF_LOOKUP_ID` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UK_orchestration_flow_reference` (`COMPOSITE_ACTION`,`FLOW_NAME`,`SEQ_NO`,`NB_REQ_REF_LOOKUP_ID`), @@ -807,6 +809,10 @@ CREATE TABLE `service` ( `OVERALL_DISTRIBUTION_STATUS` varchar(45), `ONAP_GENERATED_NAMING` TINYINT(1) DEFAULT NULL, `NAMING_POLICY` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`MODEL_UUID`), KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -961,6 +967,7 @@ CREATE TABLE `vf_module_customization` ( `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, PRIMARY KEY (`ID`), KEY `fk_vf_module_customization__vf_module1_idx` (`VF_MODULE_MODEL_UUID`), KEY `fk_vf_module_customization__heat_env__heat_environment1_idx` (`HEAT_ENVIRONMENT_ARTIFACT_UUID`), @@ -1112,6 +1119,7 @@ CREATE TABLE `vnf_resource_customization` ( `SERVICE_MODEL_UUID` varchar(200) NOT NULL, `NF_DATA_VALID` tinyint(1) DEFAULT '0', `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`ID`), UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), @@ -1193,6 +1201,7 @@ CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, `SKIP_POST_INSTANTIATION_CONFIGURATION` boolean default true, + `CONTROLLER_ACTOR` varchar(200) DEFAULT NULL, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE @@ -1234,6 +1243,18 @@ CREATE TABLE IF NOT EXISTS `vnf_resource_to_workflow` ( CONSTRAINT `fk_vnf_resource_to_workflow__workflow1` FOREIGN KEY (`WORKFLOW_ID`) REFERENCES `workflow` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `pnf_resource_to_workflow` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `PNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `WORKFLOW_ID` int(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE KEY `UK_pnf_resource_to_workflow` (`PNF_RESOURCE_MODEL_UUID`,`WORKFLOW_ID`), + KEY `fk_pnf_resource_to_workflow__workflow1_idx` (`WORKFLOW_ID`), + KEY `fk_pnf_resource_to_workflow__pnf_res_mod_uuid_idx` (`PNF_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_pnf_resource_to_workflow__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_pnf_resource_to_workflow__workflow1` FOREIGN KEY (`WORKFLOW_ID`) REFERENCES `workflow` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + CREATE TABLE IF NOT EXISTS `activity_spec` ( `ID` INT(11) NOT NULL AUTO_INCREMENT, `NAME` VARCHAR(200) NOT NULL, diff --git a/packages/docker/pom.xml b/packages/docker/pom.xml index 3f033574c5..f1d5b53ace 100644 --- a/packages/docker/pom.xml +++ b/packages/docker/pom.xml @@ -64,7 +64,7 @@ <plugin> <groupId>io.fabric8</groupId> <artifactId>docker-maven-plugin</artifactId> - <version>0.28.0</version> + <version>0.31.0</version> <configuration> <verbose>true</verbose> @@ -331,6 +331,31 @@ </assembly> </build> </image> + <image> + <name>${docker.image.prefix}/so-simulator</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:so-simulator</include> + </includes> + <outputFileNameMapping>app.jar</outputFileNameMapping> + </dependencySet> + </dependencySets> + </inline> + </assembly> + </build> + </image> </images> </configuration> @@ -362,7 +387,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</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</image> </configuration> </execution> </executions> @@ -430,5 +455,10 @@ <artifactId>so-monitoring-service</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>so-simulator</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/packages/docker/src/main/docker/docker-files/Dockerfile.so-app b/packages/docker/src/main/docker/docker-files/Dockerfile.so-app index e8f02f12c6..90f0a6627d 100644 --- a/packages/docker/src/main/docker/docker-files/Dockerfile.so-app +++ b/packages/docker/src/main/docker/docker-files/Dockerfile.so-app @@ -14,6 +14,7 @@ COPY configs/logging/logback-spring.xml /app COPY scripts/start-app.sh /app COPY scripts/wait-for.sh /app COPY ca-certificates/onap-ca.crt /app/ca-certificates/onap-ca.crt +COPY certs/* /app/ RUN chown -R so:so /app && chmod 700 /app/*.sh diff --git a/packages/docker/src/main/docker/docker-files/certs/org.onap.so.jks b/packages/docker/src/main/docker/docker-files/certs/org.onap.so.jks Binary files differnew file mode 100644 index 0000000000..1e849afb5e --- /dev/null +++ b/packages/docker/src/main/docker/docker-files/certs/org.onap.so.jks diff --git a/packages/docker/src/main/docker/docker-files/certs/org.onap.so.keyfile b/packages/docker/src/main/docker/docker-files/certs/org.onap.so.keyfile new file mode 100644 index 0000000000..9000ed29fb --- /dev/null +++ b/packages/docker/src/main/docker/docker-files/certs/org.onap.so.keyfile @@ -0,0 +1,27 @@ +xVdhDotWIx2RB3f8RxAFQb9mkHVVdIzv8eiij9cDjg_5ea5HWPS7OzLR5lv4NA0vStrAMfSAaS2e +j4rzvrlserM9bTRco3JHb-i6ZGYMoTL6kuFJ9JMveSqg-fkwvrm7VcYQJBs1FIE3hRLNqiGJ34ud +hDRp-cGUvNRLIImksKT2fmUyEawLLuE0Lo5aX46y0ibjIMe7clMxLHIS5-WggvkgIOPkVDcxqLT2 +OteGptqW1cjrm1ydbTkLYN6dd7ZmRsT3ULPYLEtPTlZ2vCh7bFBBvP_tjp2cZf4uSPM6EClYAikn +dnTqivOfCZn25r0xeXuectoXbq12fws_jaCH05ZK1wJwAF_cQNfpvaiM457rE672YV3Ev4yhXCyM +1jVL2P9Chl1sSBkZujCftvaj1rlippP9P_eohcLv84mtApEyV49rBFRMtkX9ZVdPyb8shFSoXJxk +M6DentRzY1g37mVJ1B1YMKPNQj95nOD4gLvjbUZ7dATuroENsG7oUWkfaV6dokfTmh504ZbyeqGh +xa7yfr3326fMQBhQMpsyqD2o_Obe5wN57p-vb469w65pUmK7iJDa0Fgxaxy8XNNnw6gCurbbsvyU +nB8UdfhTvL5mJew_tKUvtq_KH9ajnA8giSxuFd9KM6YHJWiFMXIROEQT7hKjTJka1ghERBjcH_pY +hbKtHdvbrS7T2hGwY_MQEUXYQBirtjaEwAvI960hXQt1K-MC8PNLRYtdLKE2Aq3amMt7ZKtrHSeN +33I1MjXc3wRUeOi5A6qImge1Q_Wmn1SURAn9KbEv9eoMUbQUkN1z2iyw4x94BZpBk5GjDypKKOyg +guec0UY3y9wqm5gGW7XvT3v1lZqo5180VgK49iFgA4IhWZ7dnDFQmq6IHTr1pM4kuvJ9dka9saIh +9xCk_KINPp5_dqJ2Lhak2IeRg_Zm3belm1jvYGCyRRqfoi9WGrDh3LLZeK8MHrrfzLI4Toy_n6DG +UNXPrXqrZPREfW2lhYLRfrivOBYWPq9JidQXn1UctSmWdNoMH7XuikBpAwmlInNA_5j9J-L-gf9D +cw2zoby3_wvcm5vxndnocEdhqVVdo7uMmXasQqphuyJP8rgCJf_I1v0Qe5F-JXsj6xDvarOUPOTj +Z93a64EO0KI0OznolRyBqHpIXffbGh7e1EpAE0LMESKJC3Mjmsgz1ld3s7WfdeDK-IxUEHJLHlhY +IjBlY6q3OJDrgvPLkwoWPbI48tmRUJX1BCafvDU6W8crl4VQKhL_l5ANAX5oaKwh-0ZJAZ15tna5 +6fjWcWrtQSdNQxj0jXV7uEcBtRtyPyOk2uw4HJDBLQyyOglUUxcQZJFCFp2fCHmNyttmUJQ5U9cu +yw9lKhsyBJ5TB4psbp64_0EalITeAGrpuH1I1N2m1O5ZY8pmrpPtA1Mb5rQ4IJqiVbZgHTcvSiN5 +Z2SilurhI1vq4_aN_UZJQvEnw9U5WU3ysphsQk8RZKbFH4W9GDtmEGbAkRkTy17KrDIuMpe--XJF +SQHUd4tzxbiYVYHKdF6Ce1kfQ-DEFXEf7RddwuKbc7tw2pSjy1MVH4HSRoTOQQpewZRTfG-4d3MX +B99-QgufEk1OBkfemuDhdnPty5qkOLUEG_uQKPpD0QDVf-t4OxZqk_8G_dCJcXbmY4VT3V7pdN_I +qp2xP98wGcIPuLGlEB8px94jKdUolkqeV_UTmmkTGz-szLzgK_YhnnVJn8VeyNsPTwAFUlqiPTyT +n_7rCb_6nNKlriadaHu6IuJWehv03ZR9jS0P1Y3YLM286deCLFu93lN3nY4yf-SEguASdHJNCBFJ +RQViYm8Tfuim5F0KQGafheGcdZxTvBFihnDduQWNBR_bDB9zfD6OtvvkseyyWHt3gHkJm5QeCjWK +RzRvbjLpUnA31cJeEXmnmhB5qMAvjn8yORKcotn3u4MXdHEk-s8vR_SKykS6IcaYE1xxbowtg-UG +d1iaky1NFYa2VZ4pGx9lD93GDTDynmOSfzVeVsxhTu_5rAanpDkUYVuxOzajmRh55I8a6dRk
\ No newline at end of file diff --git a/packages/docker/src/main/docker/docker-files/certs/org.onap.so.trust.jks b/packages/docker/src/main/docker/docker-files/certs/org.onap.so.trust.jks Binary files differnew file mode 100644 index 0000000000..71c6e776a3 --- /dev/null +++ b/packages/docker/src/main/docker/docker-files/certs/org.onap.so.trust.jks diff --git a/packages/docker/src/main/docker/docker-files/scripts/start-app.sh b/packages/docker/src/main/docker/docker-files/scripts/start-app.sh index cb5586d61d..cea680c682 100644 --- a/packages/docker/src/main/docker/docker-files/scripts/start-app.sh +++ b/packages/docker/src/main/docker/docker-files/scripts/start-app.sh @@ -77,7 +77,11 @@ if [ ! -z "${TRUSTSTORE}" ]; then jksargs="$jksargs -Djavax.net.ssl.trustStorePassword=${TRUSTSTORE_PASSWORD}" fi -jvmargs="${JVM_ARGS} -Djava.security.egd=file:/dev/./urandom -Dlogs_dir=${LOG_PATH} -Dlogging.config=/app/logback-spring.xml $jksargs -Dspring.config.additional-location=$CONFIG_PATH ${SSL_DEBUG} ${DISABLE_SNI}" +if [ -z "${ACTIVE_PROFILE}" ]; then + export ACTIVE_PROFILE="basic" +fi + +jvmargs="${JVM_ARGS} -Dspring.profiles.active=${ACTIVE_PROFILE} -Djava.security.egd=file:/dev/./urandom -Dlogs_dir=${LOG_PATH} -Dlogging.config=/app/logback-spring.xml $jksargs -Dspring.config.additional-location=$CONFIG_PATH ${SSL_DEBUG} ${DISABLE_SNI}" echo "JVM Arguments: ${jvmargs}" @@ -33,6 +33,7 @@ <module>cxf-logging</module> <module>so-monitoring</module> <module>packages</module> + <module>so-simulator</module> </modules> <properties> <project.mso.base.folder>.</project.mso.base.folder> @@ -629,7 +630,7 @@ <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-slf4j</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>1.6.3-SNAPSHOT</version> </dependency> <dependency> <groupId>org.onap.logging-analytics</groupId> @@ -639,7 +640,7 @@ <dependency> <groupId>org.onap.logging-analytics</groupId> <artifactId>logging-filter-spring</artifactId> - <version>1.6.2-SNAPSHOT</version> + <version>1.6.3-SNAPSHOT</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> @@ -843,12 +844,12 @@ <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-spring</artifactId> - <version>0.18.2</version> + <version>4.0.0</version> </dependency> <dependency> <groupId>net.javacrumbs.shedlock</groupId> <artifactId>shedlock-provider-jdbc-template</artifactId> - <version>0.18.2</version> + <version>4.0.0</version> </dependency> <dependency> <groupId>org.flywaydb</groupId> diff --git a/so-simulator/.gitignore b/so-simulator/.gitignore new file mode 100644 index 0000000000..f22dbba7d7 --- /dev/null +++ b/so-simulator/.gitignore @@ -0,0 +1,22 @@ +target +**/.settings +**/.classpath +**/.project +**/.buildpath +**/.factorypath +**/.springBeans +.idea +.checkstyle +.DS_Store +.*~ +*.iml +**/logs/ +**/debug-logs/ +*.class +*.swp +*.log +*.tmp +**/bin/ +/tattletale/ +/.metadata/ + diff --git a/so-simulator/README.md b/so-simulator/README.md new file mode 100644 index 0000000000..e059a97956 --- /dev/null +++ b/so-simulator/README.md @@ -0,0 +1,62 @@ +SO Citrus REST Simulator ![Logo][1] +================ + +This is a standalone simulator application for REST messaging. + +Clients are able to access the simulator endpoints and the simulator responds with predefined response +messages according to its scenarios. The simulator response logic is very powerful and enables us to simulate +any kind of server interface. + +Read the simulator [user manual](https://citrusframework.org/citrus-simulator/) for more information. + +Message processing +--------- + +First of all the simulator identifies the simulator scenario based on a mapping key that is extracted from the incoming request. Based +on that operation key the respective simulator scenario is executed. + +There are multiple ways to identify the simulator scenario from incoming request messages: + +* Message-Type: Each request message type (XML root QName) results in a separate simulator scenario +* REST request mappings: Identifies the scenario based on Http method and resource path on server +* SOAP Action: Each SOAP action value defines a simulator scenario +* Message Header: Any SOAP or Http message header value specifies a new simulator scenario +* XPath payload: An XPath expression is evaluated on the message payload to identify the scenario + +Once the simulator scenario is identified the respective test logic builder is executed. The Citrus test logic provides +proper response messages as a result to the calling client. The response messages can hold dynamic values and the +simulator is able to perform complex response generating logic. The test logic is built in Java classes that use the Citrus test +DSL for defining the simulator scenario steps. + +Quick start +--------- + +You can build the simulator application locally with Maven: + +``` +mvn clean install +``` + +This will compile and package all resources for you. Also some prepared Citrus integration tests are executed during the build. +After the successful build you are able to run the simulator with: + +``` +mvn spring-boot:run +``` + +Open your browser and point to [http://localhost:8080](http://localhost:8080). You will see the simulator user interface with all available scenarios and +latest activities. + +You can execute the Citrus integration tests now in order to get some interaction with the simulator. Open the Maven project in your favorite IDE and +run the tests with TestNG plugins. You should see the tests calling operations on the simulator in order to receive proper responses. The simulator user interface should track those +interactions accordingly. + +Information +--------- + +Read the [user manual](https://citrusframework.org/citrus-simulator/) for detailed instructions and features. +For more information on Citrus see [citrusframework.org][2], including a complete [reference manual][3]. + + [1]: https://citrusframework.org/img/brand-logo.png "Citrus" + [2]: https://citrusframework.org + [3]: https://citrusframework.org/reference/html/ diff --git a/so-simulator/pom.xml b/so-simulator/pom.xml new file mode 100644 index 0000000000..49e02e3d68 --- /dev/null +++ b/so-simulator/pom.xml @@ -0,0 +1,91 @@ +<?xml version="1.0" encoding="UTF-8"?> +<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"> + + <parent> + <groupId>org.onap.so</groupId> + <artifactId>so</artifactId> + <version>1.4.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>so-simulator</artifactId> + <groupId>org.onap.so</groupId> + <packaging>jar</packaging> + + <properties> + <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> + </properties> + + <dependencies> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-web</artifactId> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter</artifactId> + </dependency> + <!-- Citrus Simulator --> + <dependency> + <groupId>com.consol.citrus</groupId> + <artifactId>citrus-simulator-starter</artifactId> + <version>${citrus.simulator.version}</version> + </dependency> + <dependency> + <groupId>com.consol.citrus</groupId> + <artifactId>citrus-simulator-ui</artifactId> + <version>${citrus.simulator.version}</version> + </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>common</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>com.consol.citrus</groupId> + <artifactId>citrus-ws</artifactId> + <version>2.7.8</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <artifactId>maven-compiler-plugin</artifactId> + <version>3.7.0</version> + <configuration> + <encoding>${project.build.sourceEncoding}</encoding> + <source>1.8</source> + <target>1.8</target> + </configuration> + </plugin> + <plugin> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-maven-plugin</artifactId> + <version>${springboot.version}</version> + <configuration> + <mainClass>org.onap.so.simulator.Simulator</mainClass> + </configuration> + <executions> + <execution> + <goals> + <goal>repackage</goal> + </goals> + </execution> + </executions> + </plugin> + <plugin> + <groupId>io.fabric8</groupId> + <artifactId>fabric8-maven-plugin</artifactId> + <executions> + <execution> + <id>start</id> + </execution> + </executions> + </plugin> + </plugins> + </build> + +</project> diff --git a/so-simulator/src/main/docker/Dockerfile b/so-simulator/src/main/docker/Dockerfile new file mode 100644 index 0000000000..8fa8dc75e9 --- /dev/null +++ b/so-simulator/src/main/docker/Dockerfile @@ -0,0 +1,24 @@ +FROM docker.io/openjdk:8-jdk-alpine + +#Create User so +RUN addgroup -g 1000 so && adduser -S -u 1000 -G so so + +ARG project_version=1.1.0-SNAPSHOT +ARG artifact_id +ARG docker_repository +ENV docker_repository $docker_repository +ENV project_version $project_version +ENV artifact_id $artifact_id + +ENV no_proxy localhost + +VOLUME /tmp +WORKDIR /app + +ADD /maven/${artifact_id}-${project_version}.jar /app/app.jar +RUN chown -R so:so /app + +USER so + + +ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app/app.jar"]
\ No newline at end of file diff --git a/so-simulator/src/main/java/org/onap/so/simulator/AAIPropertiesImpl.java b/so-simulator/src/main/java/org/onap/so/simulator/AAIPropertiesImpl.java new file mode 100644 index 0000000000..a0c0007927 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/AAIPropertiesImpl.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.simulator; + +import java.net.MalformedURLException; +import java.net.URL; +import org.onap.so.client.aai.AAIVersion; + + +public class AAIPropertiesImpl implements org.onap.so.client.aai.AAIProperties { + + public static final String AAI_ENDPOINT = "aai.endpoint"; + + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL("http://so-aai-resources-svc:9900"); + } + + @Override + public String getSystemName() { + return "SIMULATOR"; + } + + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } + + @Override + public String getAuth() { + return null; + } + + @Override + public String getKey() { + // TODO Auto-generated method stub + return null; + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/Simulator.java b/so-simulator/src/main/java/org/onap/so/simulator/Simulator.java new file mode 100644 index 0000000000..02032e485f --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/Simulator.java @@ -0,0 +1,46 @@ + +package org.onap.so.simulator; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpStatus; +import org.springframework.ws.soap.SoapVersion; +import org.springframework.ws.soap.saaj.SaajSoapMessageFactory; +import com.consol.citrus.endpoint.EndpointAdapter; +import com.consol.citrus.endpoint.adapter.StaticEndpointAdapter; +import com.consol.citrus.http.message.HttpMessage; +import com.consol.citrus.message.Message; +import com.consol.citrus.simulator.http.SimulatorRestAdapter; +import com.consol.citrus.simulator.http.SimulatorRestConfigurationProperties; + + +@SpringBootApplication +public class Simulator extends SimulatorRestAdapter { + + public static void main(String[] args) { + SpringApplication.run(Simulator.class, args); + } + + @Override + public String urlMapping(SimulatorRestConfigurationProperties simulatorRestConfiguration) { + return "/sim/**"; + } + + @Override + public EndpointAdapter fallbackEndpointAdapter() { + return new StaticEndpointAdapter() { + @Override + protected Message handleMessageInternal(Message message) { + return new HttpMessage().status(HttpStatus.INTERNAL_SERVER_ERROR); + } + }; + } + + @Bean + public SaajSoapMessageFactory messageFactory() { + SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory(); + messageFactory.setSoapVersion(SoapVersion.SOAP_12); + return messageFactory; + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/DeleteVServers.java b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/DeleteVServers.java new file mode 100644 index 0000000000..064556da00 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/DeleteVServers.java @@ -0,0 +1,34 @@ +package org.onap.so.simulator.actions.aai; + +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.consol.citrus.actions.AbstractTestAction; +import com.consol.citrus.context.TestContext; + +public class DeleteVServers extends AbstractTestAction { + + private static final Logger logger = LoggerFactory.getLogger(DeleteVServers.class); + + @Override + public void doExecute(TestContext context) { + + try { + logger.info("Deleting Vservers in A&AI"); + AAIResourcesClient aaiResourceClient = new AAIResourcesClient(); + String vserverId = context.getVariable("vServerId"); + String cloudRegion = context.getVariable("cloudRegion"); + String cloudOwner = context.getVariable("cloudOwner"); + String tenantId = context.getVariable("tenantId"); + AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, + tenantId, vserverId); + aaiResourceClient.delete(vserverURI); + } catch (Exception e) { + logger.error("Error Deleting VServer in A&AI", e); + } + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessNetwork.java b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessNetwork.java new file mode 100644 index 0000000000..075a5b7a6b --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessNetwork.java @@ -0,0 +1,42 @@ +package org.onap.so.simulator.actions.aai; + +import org.onap.aai.domain.yang.L3Network; +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 com.consol.citrus.actions.AbstractTestAction; +import com.consol.citrus.context.TestContext; + + +public class ProcessNetwork extends AbstractTestAction { + + @Override + public void doExecute(TestContext context) { + + try { + int random = (int) (Math.random() * 50 + 1); + + AAIResourcesClient aaiResourceClient = new AAIResourcesClient(); + + if (context.getVariable("action").equals("assign")) { + String networkId = context.getVariable("generatedNetworkId"); + AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId); + L3Network network = new L3Network(); + network.setNetworkId(networkId); + network.setNetworkName(context.getVariable("networkName")); + network.setNetworkType(context.getVariable("networkType")); + network.setNetworkTechnology("SR_IOV"); + network.setPhysicalNetworkName("PhysicalNetwork" + random); + aaiResourceClient.create(networkURI, network); + } else if (context.getVariable("action").equals("delete")) { + String networkId = context.getVariable("networkId"); + AAIResourceUri networkURI = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId); + aaiResourceClient.delete(networkURI); + } + } catch (Exception e) { + e.printStackTrace(); + } + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java new file mode 100644 index 0000000000..e061d2b79d --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/actions/aai/ProcessVnfc.java @@ -0,0 +1,64 @@ +package org.onap.so.simulator.actions.aai; + +import org.onap.aai.domain.yang.Vnfc; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import com.consol.citrus.actions.AbstractTestAction; +import com.consol.citrus.context.TestContext; + +public class ProcessVnfc extends AbstractTestAction { + + @Override + public void doExecute(TestContext context) { + + final Logger logger = LoggerFactory.getLogger(ProcessVnfc.class); + try { + logger.debug("running ProcessVnfc scenario"); + logger.debug("requestAction: " + context.getVariable("requestAction")); + logger.debug("serviceAction: " + context.getVariable("serviceAction")); + logger.debug("cloudOwner: " + context.getVariable("cloudOwner")); + logger.debug("cloundRegion: " + context.getVariable("cloudRegion")); + logger.debug("tenant: " + context.getVariable("tenant")); + logger.debug("vfModuleId: " + context.getVariable("vfModuleId")); + logger.debug("vnfId: " + context.getVariable("vnfId")); + + AAIResourcesClient aaiResourceClient = new AAIResourcesClient(); + + if (context.getVariable("requestAction").equals("CreateVfModuleInstance") + && context.getVariable("serviceAction").equals("activate")) { + + AAIResourceUri vnfcURI = AAIUriFactory.createResourceUri(AAIObjectType.VNFC, "zauk51bfrwl09oam001"); + Vnfc vnfc = new Vnfc(); + vnfc.setVnfcName("zauk51bfrwl09oam001"); + vnfc.setNfcNamingCode("oamfw"); + vnfc.setNfcFunction("EPC-OAM-FIREWALL"); + vnfc.setProvStatus("PREPROV"); + vnfc.setOrchestrationStatus("Active"); + vnfc.setInMaint(false); + vnfc.setIsClosedLoopDisabled(false); + + vnfc.setModelInvariantId("b214d2e9-73d9-49d7-b7c4-a9ae7f06e244"); + vnfc.setModelVersionId("9e314c37-2258-4572-a399-c0dd7d5f1aec"); + vnfc.setModelCustomizationId("2bd95cd4-d7ff-4af0-985d-2adea0339921"); + + if (!aaiResourceClient.exists(vnfcURI)) + aaiResourceClient.create(vnfcURI, vnfc); + AAIResourceUri vfModuleURI = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, + context.getVariable("vnfId"), context.getVariable("vfModuleId")); + AAIResourceUri pserverURI = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "test"); + AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, + context.getVariable("cloudOwner"), context.getVariable("cloudRegion"), + context.getVariable("tenant"), "d29f3151-592d-4011-9356-ad047794e236"); + aaiResourceClient.connect(vnfcURI, vserverURI); + aaiResourceClient.connect(vserverURI, pserverURI); + aaiResourceClient.connect(vfModuleURI, vnfcURI); + } + } catch (Exception e) { + logger.debug(e.getMessage()); + } + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/DefaultScenario.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/DefaultScenario.java new file mode 100644 index 0000000000..cb9c7873a9 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/DefaultScenario.java @@ -0,0 +1,34 @@ +/* + * Copyright 2006-2017 the original author or authors. + * + * 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. + */ + +package org.onap.so.simulator.scenarios; + +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioRunner; +import org.springframework.http.HttpStatus; + +/** + * @author Christoph Deppisch + */ +@Scenario("Default") +public class DefaultScenario extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioRunner scenario) { + scenario.http().receive((builder -> builder.get())); + + scenario.http().send((builder -> builder.response(HttpStatus.BAD_REQUEST))); + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateAAInventory.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateAAInventory.java new file mode 100644 index 0000000000..eae5ef2135 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateAAInventory.java @@ -0,0 +1,38 @@ +package org.onap.so.simulator.scenarios.openstack; + +import java.io.InputStream; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.client.aai.AAICommonObjectMapperProvider; +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.springframework.core.io.ClassPathResource; +import com.consol.citrus.actions.AbstractTestAction; +import com.consol.citrus.context.TestContext; + +public class CreateAAInventory extends AbstractTestAction { + + @Override + public void doExecute(TestContext context) { + try { + String stackName = context.getVariable("stackName"); + + if (stackName != null && stackName.equals("replace_module")) { + String vServerId = "92272b67-d23f-42ca-87fa-7b06a9ec81f3"; + AAIResourcesClient aaiResourceClient = new AAIResourcesClient(); + AAICommonObjectMapperProvider aaiMapper = new AAICommonObjectMapperProvider(); + InputStream vserverFile = + new ClassPathResource("openstack/gr_api/CreateAAIInventory.json").getInputStream(); + Vserver vserver = aaiMapper.getMapper().readValue(vserverFile, Vserver.class); + AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, "cloudOwner", + "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", vServerId); + aaiResourceClient.create(vserverURI, vserver); + } + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateStack.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateStack.java new file mode 100644 index 0000000000..2c0c4aff09 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateStack.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-CreateStack") +@RequestMapping(value = "/sim/mockPublicUrl/stacks", method = RequestMethod.POST) +public class CreateStack extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().post().extractFromPayload("$.stack_name", "stackName"); + + scenario.action(new CreateAAInventory()); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Create.json")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateStackAudit.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateStackAudit.java new file mode 100644 index 0000000000..35e0571b14 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/CreateStackAudit.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-CreateStackAudit") +@RequestMapping(value = "/sim/mockPublicUrlThree/stacks", method = RequestMethod.POST) +public class CreateStackAudit extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().post().extractFromPayload("$.stack_name", "stackName"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/ModuleCreateDelete.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/ModuleCreateDelete.java new file mode 100644 index 0000000000..25bb87c8bc --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/ModuleCreateDelete.java @@ -0,0 +1,53 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-ModuleCreateDelete") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/dummy_id/stackId") +public class ModuleCreateDelete extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "dummy_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionOne"); + scenario.variable("tenantId", "0422ffb57ba042c0800a29dc85ca70f8"); + scenario.variable("vServerId", "92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Initial Get from Openstack Adapter prior to deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Final Get from Openstack Adapter after the deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/ModuleCreateDeleteAudit.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/ModuleCreateDeleteAudit.java new file mode 100644 index 0000000000..1365fa04c8 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/ModuleCreateDeleteAudit.java @@ -0,0 +1,52 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-ModuleCreateDeleteAudit") +@RequestMapping(value = "/sim/mockPublicUrlThree/stacks/nc_dummy_id/stackId") +public class ModuleCreateDeleteAudit extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "nc_dummy_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionThree"); + scenario.variable("tenantId", "0422ffb57ba042c0800a29dc85ca70a3"); + scenario.variable("vServerId", "92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Initial Get from Openstack Adapter prior to deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete of the stack + scenario.http().receive().delete(); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Final Get from Openstack Adapter after the deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/NetworkCreateDeleteCloud.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/NetworkCreateDeleteCloud.java new file mode 100644 index 0000000000..712f377f4e --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/NetworkCreateDeleteCloud.java @@ -0,0 +1,48 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.onap.so.simulator.actions.aai.DeleteVServers; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-NetworkCreateDeleteCloud") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/network_dummy_id/stackId") +public class NetworkCreateDeleteCloud extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "network_dummy_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionOne"); + scenario.variable("tenantId", "0422ffb57ba042c0800a29dc85ca70f8"); + scenario.variable("vServerId", "92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Final Get from Openstack Adapter after the deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryBaseStack.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryBaseStack.java new file mode 100644 index 0000000000..25bd563e1a --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryBaseStack.java @@ -0,0 +1,35 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryBaseStackByName") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/base_module_id/*", method = RequestMethod.GET) +public class QueryBaseStack extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "base_module_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionTwo"); + scenario.variable("tenantId", "872f331350c54e59991a8de2cbffb40c"); + scenario.variable("vServerId", "d29f3151-592d-4011-9356-ad047794e236"); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryBaseVfModuleStackById.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryBaseVfModuleStackById.java new file mode 100644 index 0000000000..149794fb3c --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryBaseVfModuleStackById.java @@ -0,0 +1,48 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryBaseVfModuleStackById") +@RequestMapping(value = "/sim/v1/872f331350c54e59991a8de2cbffb40c/stacks/base_module_id/stackId") +public class QueryBaseVfModuleStackById extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "base_module_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionTwo"); + scenario.variable("tenantId", "872f331350c54e59991a8de2cbffb40c"); + scenario.variable("vServerId", "d29f3151-592d-4011-9356-ad047794e236"); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Initial Get from Openstack Adapter prior to deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Poll Deletion of stack for status + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameFailureId.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameFailureId.java new file mode 100644 index 0000000000..5659f309d1 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameFailureId.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Failure-ID-Name-Resources") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/failure_id/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameFailureId extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "failure_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplace.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplace.java new file mode 100644 index 0000000000..4c3b4b628e --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplace.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Replace-ID-Name-Resources") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/replace_module/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameModuleReplace extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "replace_module"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplaceVolume.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplaceVolume.java new file mode 100644 index 0000000000..5e4bb98926 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryResourcesByStackNameModuleReplaceVolume.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Replace-Volume-ID-Name-Resources") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/replace_module_volume_id/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameModuleReplaceVolume extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "replace_module_volume_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStack.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStack.java new file mode 100644 index 0000000000..8d36e567e4 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStack.java @@ -0,0 +1,23 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByName") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/*", method = RequestMethod.GET) +public class QueryStack extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.NOT_FOUND); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java new file mode 100644 index 0000000000..2311c4c44e --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java @@ -0,0 +1,49 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Double-Failure-Stack-Endpoint") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/double_failure_id/stackId") +public class QueryStackByIdDoubleFailure extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "double_failure_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionTwo"); + scenario.variable("tenantId", "872f331350c54e59991a8de2cbffb40c"); + scenario.variable("vServerId", "d29f3151-592d-4011-9356-ad047794e236"); + scenario.variable("stack_failure_message", "The Flavor ID (nd.c6r16d20) could not be found."); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Poll Deletion of stack for status + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java new file mode 100644 index 0000000000..4d0d578831 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java @@ -0,0 +1,49 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Failure-Stack-Endpoint") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/failure_id/stackId") +public class QueryStackByIdFailure extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "failure_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionTwo"); + scenario.variable("tenantId", "872f331350c54e59991a8de2cbffb40c"); + scenario.variable("vServerId", "d29f3151-592d-4011-9356-ad047794e236"); + scenario.variable("stack_failure_message", "The Flavor ID (nd.c6r16d20) could not be found."); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Poll Deletion of stack for status + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdNetworkMacro1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdNetworkMacro1.java new file mode 100644 index 0000000000..4001d1c972 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdNetworkMacro1.java @@ -0,0 +1,38 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByID-NetworkMacro1") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_network1/*", method = RequestMethod.GET) +public class QueryStackByIdNetworkMacro1 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "dummy_id"); + + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdNetworkMacro2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdNetworkMacro2.java new file mode 100644 index 0000000000..55d697aa69 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdNetworkMacro2.java @@ -0,0 +1,38 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByID-NetworkMacro2") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_network1/*", method = RequestMethod.GET) +public class QueryStackByIdNetworkMacro2 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "dummy_id"); + + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModule.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModule.java new file mode 100644 index 0000000000..c0302ad1eb --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModule.java @@ -0,0 +1,51 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Replace-VF-Module-Get") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/replace_module/*") +public class QueryStackByIdReplaceModule extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "replace_module"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionOne"); + scenario.variable("tenantId", "0422ffb57ba042c0800a29dc85ca70f8"); + scenario.variable("vServerId", "92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Initial Get from Openstack Adapter prior to deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Final Get from Openstack Adapter after the deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModuleVolume.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModuleVolume.java new file mode 100644 index 0000000000..170c3105b3 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdReplaceModuleVolume.java @@ -0,0 +1,51 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.onap.so.simulator.actions.aai.DeleteVServers; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Replace-VF-Module-Volume-Get") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/replace_module_volume_id/*") +public class QueryStackByIdReplaceModuleVolume extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + // Get to see if stack exists + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "replace_module_volume_id"); + scenario.variable("cloudOwner", "cloudOwner"); + scenario.variable("cloudRegion", "regionOne"); + scenario.variable("tenantId", "0422ffb57ba042c0800a29dc85ca70f8"); + scenario.variable("vServerId", "92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Initial Get from Openstack Adapter prior to deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete of the stack + scenario.http().receive().delete(); + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Final Get from Openstack Adapter after the deletion of the stack + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdVolumeGroup.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdVolumeGroup.java new file mode 100644 index 0000000000..75b1ecac81 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdVolumeGroup.java @@ -0,0 +1,40 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-VolumeGroup-Interactions") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/VolumeGroup/*") +public class QueryStackByIdVolumeGroup extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "VolumeGroup"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + scenario.http().receive().delete(); + + scenario.http().send().response(HttpStatus.NO_CONTENT); + + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByName.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByName.java new file mode 100644 index 0000000000..b51a608e6d --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByName.java @@ -0,0 +1,24 @@ +package org.onap.so.simulator.scenarios.openstack; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByName3") +@RequestMapping(value = "/sim/mockPublicUrlThree/stacks/*", method = RequestMethod.GET) +public class QueryStackByName extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.NOT_FOUND); + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro1.java new file mode 100644 index 0000000000..9413fab7df --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro1.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack.macro; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Query-Stack-Resources-Macro1") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_1/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameMacro1 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro2.java new file mode 100644 index 0000000000..8708dac438 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro2.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack.macro; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Query-Stack-Resources-Macro2") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_2/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameMacro2 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro3.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro3.java new file mode 100644 index 0000000000..a30115a63a --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryResourcesByStackNameMacro3.java @@ -0,0 +1,25 @@ +package org.onap.so.simulator.scenarios.openstack.macro; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Query-Stack-Resources-Macro3") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_3/resources", method = RequestMethod.GET) +public class QueryResourcesByStackNameMacro3 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/GetStackResourcesMacro.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java new file mode 100644 index 0000000000..ba6a1a1185 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java @@ -0,0 +1,36 @@ +package org.onap.so.simulator.scenarios.openstack.macro; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByID-Macro1") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_1/*", method = RequestMethod.GET) +public class QueryStackByIdMacro1 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "macro_module_1"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java new file mode 100644 index 0000000000..efd420486d --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java @@ -0,0 +1,37 @@ +package org.onap.so.simulator.scenarios.openstack.macro; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByID-Macro2") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_2/*", method = RequestMethod.GET) +public class QueryStackByIdMacro2 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "macro_module_2"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java new file mode 100644 index 0000000000..4d3ba8697a --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java @@ -0,0 +1,37 @@ +package org.onap.so.simulator.scenarios.openstack.macro; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-QueryStackByID-Macro3") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_3/*", method = RequestMethod.GET) +public class QueryStackByIdMacro3 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "correlationId"); + scenario.echo("${correlationId}"); + scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, + "${correlationId}"); + + scenario.variable("stackName", "macro_module_3"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/nova/NovaKeyPairDelete.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/nova/NovaKeyPairDelete.java new file mode 100644 index 0000000000..32b29f2ab8 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/nova/NovaKeyPairDelete.java @@ -0,0 +1,19 @@ +package org.onap.so.simulator.scenarios.openstack.nova; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Nova-Keypair-Delete") +@RequestMapping(value = "/sim/mockPublicUrl/os-keypairs/*", method = RequestMethod.DELETE) +public class NovaKeyPairDelete extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().delete(); + scenario.http().send().response(HttpStatus.NO_CONTENT); + } +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCHAPort0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCHAPort0.java new file mode 100644 index 0000000000..682ed9f03d --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCHAPort0.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryNeutronNetworkSSCHAPort0") +@RequestMapping(value = "/sim/mockPublicUrl/v2.0/ports/00bb8407-650e-48b5-b919-33b88d6f8fe3", + method = RequestMethod.GET) +public class QueryNeutronNetworkSSCHAPort0 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetNeutronNetworkSSCHAPort0.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCManagementPort0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCManagementPort0.java new file mode 100644 index 0000000000..26b2e1305e --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCManagementPort0.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryNeutronNetworkSSCManagementPort0") +@RequestMapping(value = "/sim/mockPublicUrl/v2.0/ports/8d93f63e-e972-48c7-ad98-b2122da47315", + method = RequestMethod.GET) +public class QueryNeutronNetworkSSCManagementPort0 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetNeutronNetworkSSCManagementPort0.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCManagementPort1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCManagementPort1.java new file mode 100644 index 0000000000..7269e54554 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCManagementPort1.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryNeutronNetworkSSCManagementPort1") +@RequestMapping(value = "/sim/mockPublicUrl/v2.0/ports/07f5b14c-147a-4d14-8c94-a9e94dbc097b", + method = RequestMethod.GET) +public class QueryNeutronNetworkSSCManagementPort1 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetNeutronNetworkSSCManagementPort1.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCRole1Port0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCRole1Port0.java new file mode 100644 index 0000000000..f7e677b158 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCRole1Port0.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryNeutronNetworkSSCRole1Port0") +@RequestMapping(value = "/sim/mockPublicUrl/v2.0/ports/0594a2f2-7ea4-42eb-abc2-48ea49677fca", + method = RequestMethod.GET) +public class QueryNeutronNetworkSSCRole1Port0 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetNeutronNetworkSSCRole1Port0.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCService1Port0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCService1Port0.java new file mode 100644 index 0000000000..0e5c7fd2b6 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCService1Port0.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryNeutronNetworkSSCservice1Port0") +@RequestMapping(value = "/sim/mockPublicUrl/v2.0/ports/27391d94-33af-474a-927d-d409249e8fd3", + method = RequestMethod.GET) +public class QueryNeutronNetworkSSCService1Port0 extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetNeutronNetworkSSCTservice1Port0.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCTrusted.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCTrusted.java new file mode 100644 index 0000000000..29f1df3e01 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryNeutronNetworkSSCTrusted.java @@ -0,0 +1,28 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryNeutronNetworkSSCTrusted") +@RequestMapping(value = "/sim/mockPublicUrl/v2.0/ports/d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + method = RequestMethod.GET) +public class QueryNeutronNetworkSSCTrusted extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("openstack/gr_api/GetNeutronNetworkSSCTrustedPort.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsRole1Sub1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsRole1Sub1.java new file mode 100644 index 0000000000..d9331e7e1a --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsRole1Sub1.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Resource-Details-Role1-Sub0") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources", + method = RequestMethod.GET) +public class QueryResourceDetailsRole1Sub1 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Role1SubInterface1Resources.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub0.java new file mode 100644 index 0000000000..9c42e489ee --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub0.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Resource-Details-service1-Sub0") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb/resources", + method = RequestMethod.GET) +public class QueryResourceDetailsService1Sub0 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/service1SubInterface0Resources.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub1.java new file mode 100644 index 0000000000..691879cfc8 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub1.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Resource-Details-service1-Sub1") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a/resources", + method = RequestMethod.GET) +public class QueryResourceDetailsService1Sub1 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/service1SubInterface1Resources.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub2.java new file mode 100644 index 0000000000..33b450a08c --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourceDetailsService1Sub2.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Resource-Details-service1-Sub2") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c/resources", + method = RequestMethod.GET) +public class QueryResourceDetailsService1Sub2 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/service1SubInterface2Resources.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourcesByBaseStackName.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourcesByBaseStackName.java new file mode 100644 index 0000000000..6dbd898154 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourcesByBaseStackName.java @@ -0,0 +1,27 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Query-Base-Stack-Resources") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/base_module_id/resources", method = RequestMethod.GET) +public class QueryResourcesByBaseStackName extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/GetStackResources.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourcesByStackName.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourcesByStackName.java new file mode 100644 index 0000000000..aff4d924e2 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryResourcesByStackName.java @@ -0,0 +1,27 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Openstack-Query-Stack-Resources") +@RequestMapping(value = "/sim/mockPublicUrl/stacks/dummy_id/resources", method = RequestMethod.GET) +public class QueryResourcesByStackName extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("stackName", "dummy_id"); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/GetStackResources.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryRole1StackResources.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryRole1StackResources.java new file mode 100644 index 0000000000..5372d2ad78 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryRole1StackResources.java @@ -0,0 +1,27 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryRole1StackResources-tsbc0005vm002ssc001") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c/resources", + method = RequestMethod.GET) +public class QueryRole1StackResources extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/StackResourcesRole1ResourceGroup.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryService1StackResources.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryService1StackResources.java new file mode 100644 index 0000000000..60a5ad8964 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryService1StackResources.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("QueryService1StackResources-tsbc0005vm002ssc001") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources", + method = RequestMethod.GET) +public class QueryService1StackResources extends AbstractSimulatorScenario { + + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/StackResourcesservice1ResourceGroup.json")); + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsRole1Sub0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsRole1Sub0.java new file mode 100644 index 0000000000..068bc26072 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsRole1Sub0.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Stack-Details-Role1-Sub0") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + method = RequestMethod.GET) +public class QueryStackDetailsRole1Sub0 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Role1SubInterface0.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub0.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub0.java new file mode 100644 index 0000000000..22fb263d5b --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub0.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Stack-Details-service1-Sub0") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a", + method = RequestMethod.GET) +public class QueryStackDetailsService1Sub0 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/service1SubInterface0.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub1.java new file mode 100644 index 0000000000..16688ffae8 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub1.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Stack-Details-service1-Sub1") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", + method = RequestMethod.GET) +public class QueryStackDetailsService1Sub1 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/service1SubInterface1.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub2.java new file mode 100644 index 0000000000..53bf966421 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/resources/QueryStackDetailsService1Sub2.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.openstack.resources; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Query-Stack-Details-service1-Sub2") +@RequestMapping( + value = "/sim/mockPublicUrl/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c", + method = RequestMethod.GET) +public class QueryStackDetailsService1Sub2 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/service1SubInterface2.json")); + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/AssignVFModule.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/AssignVFModule.java new file mode 100644 index 0000000000..e089f33aa3 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/AssignVFModule.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.sdnc; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-VNFAPI-AssignVFModule") +@RequestMapping(value = "/sim/restconf/operations/VNF-API:vnf-topology-operation", method = RequestMethod.POST) +public class AssignVFModule extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().post(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("sdnc/vnf-api/AssignResponseSuccess.xml")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/QueryVFModule.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/QueryVFModule.java new file mode 100644 index 0000000000..24bb671a06 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/QueryVFModule.java @@ -0,0 +1,24 @@ + +package org.onap.so.simulator.scenarios.sdnc; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-VNFAPI-QueryVFModule") +@RequestMapping(value = "/sim/restconf/config/VNF-API:vnfs/vnf-list/*", method = RequestMethod.GET) +public class QueryVFModule extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("sdnc/vnf-api/QueryResponseSuccess.xml")); + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/HealthCheck.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/HealthCheck.java new file mode 100644 index 0000000000..e7af44d261 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/HealthCheck.java @@ -0,0 +1,24 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("Health-Check-SDNC") +@RequestMapping(value = "/sim/restconf/operations/SLI-API:healthcheck", method = RequestMethod.POST) +public class HealthCheck extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().post(); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/HealthCheck.json")); + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/ProcessSDNCAssignService.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/ProcessSDNCAssignService.java new file mode 100644 index 0000000000..c1ba812513 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/ProcessSDNCAssignService.java @@ -0,0 +1,29 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import com.consol.citrus.actions.AbstractTestAction; +import com.consol.citrus.context.TestContext; + +public class ProcessSDNCAssignService extends AbstractTestAction { + + + @Override + public void doExecute(TestContext context) { + try { + String serviceName = context.getVariable("serviceName"); + String action = context.getVariable("action"); + if (("Robot_SI_For_Service_Failure".equals(serviceName) && "assign".equals(action)) + || ("Robot_SI_For_Service_Rollback_Failure".equals(serviceName))) { + context.setVariable("responseMessage", "SDNC is throwing errors"); + context.setVariable("responseCode", "500"); + } else { + context.setVariable("responseMessage", "Success"); + context.setVariable("responseCode", "200"); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR.java new file mode 100644 index 0000000000..4e6b15158c --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR.java @@ -0,0 +1,31 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-GRAPI-QueryVFModule") +@RequestMapping( + value = "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/*/service-data/vnfs/vnf/*/vnf-data/vf-modules/vf-module/dummy_id/vf-module-data/vf-module-topology/", + method = RequestMethod.GET) +public class QueryVFModuleGR extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + int random = (int) (Math.random() * 50 + 1); + + scenario.variable("vfModuleName", "vfModuleName" + random); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/gr-api/SDNC_Query_VfModule.json")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro1.java new file mode 100644 index 0000000000..6a6fbf191c --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro1.java @@ -0,0 +1,31 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-GRAPI-QueryVFModule-Macro1") +@RequestMapping( + value = "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/*/service-data/vnfs/vnf/*/vnf-data/vf-modules/vf-module/macro_module_1/vf-module-data/vf-module-topology/", + method = RequestMethod.GET) +public class QueryVFModuleGR_Macro1 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + + scenario.variable("vfModuleName", "macro_module_1"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/gr-api/SDNC_Query_VfModule.json")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro2.java new file mode 100644 index 0000000000..a63aa0f94f --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro2.java @@ -0,0 +1,30 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-GRAPI-QueryVFModule-Macro2") +@RequestMapping( + value = "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/*/service-data/vnfs/vnf/*/vnf-data/vf-modules/vf-module/macro_module_2/vf-module-data/vf-module-topology/", + method = RequestMethod.GET) +public class QueryVFModuleGR_Macro2 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("vfModuleName", "macro_module_2"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/gr-api/SDNC_Query_VfModule.json")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro3.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro3.java new file mode 100644 index 0000000000..0d4fb2adf3 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVFModuleGR_Macro3.java @@ -0,0 +1,30 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-GRAPI-QueryVFModule-Macro3") +@RequestMapping( + value = "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/*/service-data/vnfs/vnf/*/vnf-data/vf-modules/vf-module/macro_module_3/vf-module-data/vf-module-topology/", + method = RequestMethod.GET) +public class QueryVFModuleGR_Macro3 extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.variable("vfModuleName", "macro_module_3"); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/gr-api/SDNC_Query_VfModule.json")); + + + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVNF.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVNF.java new file mode 100644 index 0000000000..a891ea73e2 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/QueryVNF.java @@ -0,0 +1,26 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-GRAPI-QueryVnf") +@RequestMapping( + value = "/sim/restconf/config/GENERIC-RESOURCE-API:services/service/*/service-data/vnfs/vnf/*/vnf-data/vnf-topology/", + method = RequestMethod.GET) +public class QueryVNF extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().get(); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/gr-api/SDNC_Query_Vnf.json")); + } + + +} diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/ServiceInstance.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/ServiceInstance.java new file mode 100644 index 0000000000..4dd57d2b39 --- /dev/null +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/sdnc/grapi/ServiceInstance.java @@ -0,0 +1,35 @@ +package org.onap.so.simulator.scenarios.sdnc.grapi; + +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; +import com.consol.citrus.simulator.scenario.Scenario; +import com.consol.citrus.simulator.scenario.ScenarioDesigner; + +@Scenario("SDNC-GRAPI-ServiceInstance") +@RequestMapping(value = "/sim/restconf/operations/GENERIC-RESOURCE-API:service-topology-operation/", + method = RequestMethod.POST) +public class ServiceInstance extends AbstractSimulatorScenario { + + @Override + public void run(ScenarioDesigner scenario) { + scenario.http().receive().post().extractFromPayload("$.input.service-information.service-id", "serviceId") + .extractFromPayload("$.input.service-request-input.service-instance-name", "serviceName") + .extractFromPayload("$.input.sdnc-request-header.svc-action", "action"); + + scenario.createVariable("finalIndicator", "Y"); + scenario.createVariable("responseCode", "200"); + scenario.createVariable("responseMessage", "success"); + scenario.action(new ProcessSDNCAssignService()); + + scenario.http().send().response(HttpStatus.OK).header("ContentType", "application/json") + .payload(new ClassPathResource("sdnc/gr-api/SDNCSuccess.json")); + + + } + + +} diff --git a/so-simulator/src/main/resources/META-INF/citrus-simulator-context.xml b/so-simulator/src/main/resources/META-INF/citrus-simulator-context.xml new file mode 100644 index 0000000000..9e9311f6f3 --- /dev/null +++ b/so-simulator/src/main/resources/META-INF/citrus-simulator-context.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:citrus="http://www.citrusframework.org/schema/config" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + + http://www.citrusframework.org/schema/config http://www.citrusframework.org/schema/config/citrus-config.xsd"> + + + + <citrus:global-variables> + <citrus:variable name="simulator.name" value="Citrus REST Simulator"/> + </citrus:global-variables> + + + +</beans> diff --git a/so-simulator/src/main/resources/META-INF/services/org.onap.so.client.RestProperties b/so-simulator/src/main/resources/META-INF/services/org.onap.so.client.RestProperties new file mode 100644 index 0000000000..9f1dcba23b --- /dev/null +++ b/so-simulator/src/main/resources/META-INF/services/org.onap.so.client.RestProperties @@ -0,0 +1 @@ +org.onap.so.simulator.AAIPropertiesImpl
\ No newline at end of file diff --git a/so-simulator/src/main/resources/application.properties b/so-simulator/src/main/resources/application.properties new file mode 100644 index 0000000000..e2ab7af9c0 --- /dev/null +++ b/so-simulator/src/main/resources/application.properties @@ -0,0 +1,28 @@ +server.port: 10000 + +info.simulator.name=REST Simulator +logging.file=debug.log +logging.level.com.consol.citrus=DEBUG +logging.level.org.onap.so=DEBUG +logging.level.org.reflections.Reflections=ERROR + +# Enable Http REST support +citrus.simulator.rest.enabled=true +citrus.simulator.ws.enabled=true +citrus.simulator.ws.servlet.mapping=/services/ws/* + +# Default timeout setting +citrus.simulator.default.timeout=300000 +citrus.simulator.defaultTimeout=300000 +# Default message template path +citrus.simulator.templatePath=templates + +# Default scenario name +citrus.simulator.defaultScenario=Default + +# Should Citrus validate incoming messages on syntax and semantics +citrus.simulator.templateValidation=true + +#Actuator +management.endpoints.web.basePath=/manage +management.endpoints.web.exposure.include=info, health diff --git a/so-simulator/src/main/resources/logback-spring.xml b/so-simulator/src/main/resources/logback-spring.xml new file mode 100644 index 0000000000..2fcb7121dd --- /dev/null +++ b/so-simulator/src/main/resources/logback-spring.xml @@ -0,0 +1,58 @@ +<configuration scan="true" debug="false"> + <include resource="org/springframework/boot/logging/logback/base.xml" /> + + <property name="queueSize" value="256" /> + <property name="maxFileSize" value="20MB" /> + <property name="maxHistory" value="30" /> + <property name="totalSizeCap" value="20MB" /> + + <!-- log file names --> + <property name="debugLogName" value="debug" /> + + <property name="currentTimeStamp" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",UTC}"/> + + <property name="debugPattern" + value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%thread|%X{RequestID}| %logger{50} - %msg%n" /> + + <appender name="Debug" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>/app/logs/${debugLogName}.log</file> + <rollingPolicy + class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> + <fileNamePattern>${debugLogName}.%d{yyyy-MM-dd}.%i.log.zip + </fileNamePattern> + <maxFileSize>${maxFileSize}</maxFileSize> + <maxHistory>${maxHistory}</maxHistory> + <totalSizeCap>${totalSizeCap}</totalSizeCap> + </rollingPolicy> + <encoder> + <pattern>${debugPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncDebug" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>256</queueSize> + <appender-ref ref="Debug" /> + <includeCallerData>true</includeCallerData> + </appender> + + <!-- Sim Logs go here--> + <logger name="com.consol.citrus" level="DEBUG" additivity="false"> + <appender-ref ref="asyncDebug" /> + </logger> + + + <logger name="com.consol.citrus.simulator.http.HttpRequestAnnotationMatcher" level="WARN" additivity="false"> + <appender-ref ref="asyncDebug" /> + </logger> + + <logger name="org.onap.so" level="DEBUG" additivity="false"> + <appender-ref ref="asyncDebug" /> + </logger> + + + <root level="INFO"> + <appender-ref ref="asyncDebug" /> + </root> + +</configuration>
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/CreateAAIInventory.json b/so-simulator/src/main/resources/openstack/gr_api/CreateAAIInventory.json new file mode 100644 index 0000000000..6a541c50f1 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/CreateAAIInventory.json @@ -0,0 +1,170 @@ +{ + "vserver-id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "vserver-name": "tsbc0005vm002", + "vserver-name2": "tsbc0005vm002", + "vserver-selflink": "https://test.com:8774/v2/0422ffb57ba042c0800a29dc85ca70f8/servers/92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "in-maint": false, + "is-closed-loop-disabled": false, + "l-interfaces": { + "l-interface": [ + { + "interface-name": "tsbc0005v_tsbc0005vm002_mgmt_port_1", + "selflink": "https://test.com:9696/v2.0/ports/07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "interface-id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "macaddr": "02:07:f5:b1:4c:14", + "network-name": "GRP-27529-T-IST-05E-dyh3b_TIPFR_OAMP_NSD_TSBC0_net_1", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "1.2.2.2", + "l3-interface-ipv4-prefix-length": 28, + "is-floating": false, + "neutron-network-id": "cae2ade2-9f44-40fa-b124-18b101ff9aa0", + "neutron-subnet-id": "1f954922-6e9c-4a64-9d78-62e869ba8c77" + } + ] + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_role1_port_0", + "selflink": "https://test.com:9696/v2.0/ports/0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "interface-id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "macaddr": "02:05:94:a2:f2:7e", + "network-name": "GRP-27529-T-IST-05E-dyh3b_TIPFR-UNTR-Role1-PARNT_net_1", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false, + "l-interfaces": { + "l-interface": [ + { + "interface-name": "tsbc0005v_tsbc0005vm002_subint_untrusted_role1_81", + "interface-id": "2bbfa345-33bb-495a-94b2-fb514ee1cffc", + "macaddr": "02:05:94:a2:f2:7e", + "network-name": "GRP-27529-T-IST-05E-dyh3b_TIPFR_UNTR_VSE_Role10_net_1", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false + } + ] + }, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "172.26.0.36", + "l3-interface-ipv4-prefix-length": 27, + "is-floating": false, + "neutron-network-id": "49bd2c8c-808d-4783-a1c5-5d9ae0c6a9fa", + "neutron-subnet-id": "8d073a94-b1b9-493a-8fc1-cf92abcba466" + } + ] + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_service1_port_0", + "selflink": "https://test.com:9696/v2.0/ports/27391d94-33af-474a-927d-d409249e8fd3", + "interface-id": "27391d94-33af-474a-927d-d409249e8fd3", + "macaddr": "02:27:39:1d:94:33", + "network-name": "GRP-27529-T-IST-05E-dyh3b_TIPFR-UNTR-CUS-PARNT_net_1", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false, + "l-interfaces": { + "l-interface": [ + { + "interface-name": "tsbc0005v_tsbc0005vm002_subint_untrusted_service1_101", + "interface-id": "d54dfd09-75c6-4e04-b204-909455b8f933", + "macaddr": "02:27:39:1d:94:33", + "network-name": "GRP-27529-T-IST-05E_int_SUB-INTERFACE_net_006", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_subint_untrusted_service1_103", + "interface-id": "f7a998c0-8939-4b07-bf4a-0862e9c325e1", + "macaddr": "02:27:39:1d:94:33", + "network-name": "GRP-27529-T-IST-05E_int_SUB-INTERFACE_net_008", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_subint_untrusted_service1_102", + "interface-id": "621c1fea-60b8-44ee-aede-c01b8b1aaa70", + "macaddr": "02:27:39:1d:94:33", + "network-name": "GRP-27529-T-IST-05E_int_SUB-INTERFACE_net_007", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false + } + ] + }, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "172.26.0.5", + "l3-interface-ipv4-prefix-length": 27, + "is-floating": false, + "neutron-network-id": "7acdc0c3-eff2-4ecb-8722-a3451711027c", + "neutron-subnet-id": "4c4cc70a-7f31-41a6-a50f-5390d80fd127" + } + ] + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_int_ha_port_0", + "selflink": "https://test.com:9696/v2.0/ports/00bb8407-650e-48b5-b919-33b88d6f8fe3", + "interface-id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "macaddr": "02:00:bb:84:07:65", + "network-name": "tsbc0005v_int_ha_net", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "172.26.1.27", + "l3-interface-ipv4-prefix-length": 26, + "is-floating": false, + "neutron-network-id": "de0a1ec5-8685-4de5-999c-a791bd48c9d8", + "neutron-subnet-id": "1151932c-935d-4cdc-b134-f58bebed9bf1" + } + ] + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_mgmt_port_0", + "selflink": "https://test.com:9696/v2.0/ports/8d93f63e-e972-48c7-ad98-b2122da47315", + "interface-id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "macaddr": "02:8d:93:f6:3e:e9", + "network-name": "GRP-27529-T-IST-05E-dyh3b_TIPFR_OAMP_NSD_TSBC0_net_1", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "1.8.2.2", + "l3-interface-ipv4-prefix-length": 28, + "is-floating": false, + "neutron-network-id": "cae2ade2-9f44-40fa-b124-18b101ff9aa0", + "neutron-subnet-id": "1f954922-6e9c-4a64-9d78-62e869ba8c77" + } + ] + }, + { + "interface-name": "tsbc0005v_tsbc0005vm002_trusted_port", + "selflink": "https://test.com:9696/v2.0/ports/d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + "interface-id": "d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + "macaddr": "02:d2:f5:1f:82:0e", + "network-name": "GRP-27529-T-IST-05E-dyh3b_TIPFR_TRST_VIF_TSBC0_net_1", + "is-port-mirrored": false, + "in-maint": false, + "is-ip-unnumbered": false, + "l3-interface-ipv4-address-list": [ + { + "l3-interface-ipv4-address": "1.6.2.1", + "l3-interface-ipv4-prefix-length": 28, + "is-floating": false, + "neutron-network-id": "4f35d575-a4f2-4020-8322-3eb138e7f258", + "neutron-subnet-id": "d476da9d-bf9b-49e1-aec9-fee99b863f30" + } + ] + } + ] + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork1.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork1.json new file mode 100644 index 0000000000..5c23c4594a --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork1.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "e80bec21-4b4b-42b0-ae17-20e736b8a82a", + "security_groups": [], + "device_id": "d29f3151-592d-4011-9356-ad047794e236", + "name": "ssc_1_int_ha_port_0", + "admin_state_up": true, + "network_id": "b7ebec8e-d572-4dbf-ab4c-fc140b1e699a", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json new file mode 100644 index 0000000000..725c896b8d --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetwork2.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "e80bec21-4b4b-42b0-ae17-20e736b8a82b", + "security_groups": [], + "device_id": "d29f3151-592d-4011-9356-ad047794e236", + "name": "ssc_1_mgmt_port_0", + "admin_state_up": true, + "network_id": "b7ebec8e-d572-4dbf-ab4c-fc140b1e699a", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "normal", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCHAPort0.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCHAPort0.json new file mode 100644 index 0000000000..b775baeee4 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCHAPort0.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "security_groups": [], + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "name": "tsbc0005v_tsbc0005vm002_int_ha_port_0", + "admin_state_up": true, + "network_id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCManagementPort0.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCManagementPort0.json new file mode 100644 index 0000000000..f451d44351 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCManagementPort0.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "security_groups": [], + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "name": "tsbc0005v_tsbc0005vm002_mgmt_port_0", + "admin_state_up": true, + "network_id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCManagementPort1.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCManagementPort1.json new file mode 100644 index 0000000000..bdb12be613 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCManagementPort1.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "security_groups": [], + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "name": "tsbc0005v_tsbc0005vm002_mgmt_port_1", + "admin_state_up": true, + "network_id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCRole1Port0.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCRole1Port0.json new file mode 100644 index 0000000000..e576ab7639 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCRole1Port0.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "security_groups": [], + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "name": "tsbc0005v_tsbc0005vm002_role1_port_0", + "admin_state_up": true, + "network_id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCTrustedPort.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCTrustedPort.json new file mode 100644 index 0000000000..b16f70611d --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCTrustedPort.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + "security_groups": [], + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "name": "tsbc0005v_tsbc0005vm002_trusted_port", + "admin_state_up": true, + "network_id": "b7ebec8e-d572-4dbf-ab4c-fc140b1e699a", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCTservice1Port0.json b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCTservice1Port0.json new file mode 100644 index 0000000000..2fbfc58902 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNeutronNetworkSSCTservice1Port0.json @@ -0,0 +1,52 @@ +{ + "port": { + "status": "ACTIVE", + "binding:host_id": "auk51r07c002", + "description": "", + "allowed_address_pairs": [], + "tags": [], + "extra_dhcp_opts": [], + "updated_at": "2019-02-11T19:12:50Z", + "device_owner": "compute:auk51b-kvm-az01", + "revision_number": 10, + "port_security_enabled": false, + "binding:profile": { + "public_vlans": [ + "" + ], + "pf_pci_slot": "0000:5e:01.0", + "fabric_config": true, + "vlan_filter": [ + "181" + ], + "private_vlans": [ + "181" + ], + "physical_network": "sriovnet1", + "pci_slot": "0000:5e:05.6", + "pci_vendor_info": "8086:154c" + }, + "fixed_ips": [ + { + "subnet_id": "2849cc67-a616-4384-9ffc-eadfb1df2a44", + "ip_address": "1.2.1.3" + } + ], + "id": "27391d94-33af-474a-927d-d409249e8fd3", + "security_groups": [], + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "name": "tsbc0005v_tsbc0005vm002_service1_port_0", + "admin_state_up": true, + "network_id": "27391d94-33af-474a-927d-d409249e8fd3", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "binding:vif_details": { + "port_filter": false, + "vlan": "181" + }, + "binding:vnic_type": "direct", + "binding:vif_type": "hw_veb", + "mac_address": "fa:16:3e:0c:29:94", + "project_id": "872f331350c54e59991a8de2cbffb40c", + "created_at": "2019-02-11T19:11:39Z" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json b/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json new file mode 100644 index 0000000000..622bf8e3ef --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetNovaServer.json @@ -0,0 +1,75 @@ +{ + "server": { + "OS-EXT-STS:task_state": null, + "addresses": { + }, + "links": [ + { + "href": "https://test.com/v2.1/872f331350c54e59991a8de2cbffb40c/servers/d29f3151-592d-4011-9356-ad047794e236", + "rel": "self" + }, + { + "href": "https://test.com/872f331350c54e59991a8de2cbffb40c/servers/d29f3151-592d-4011-9356-ad047794e236", + "rel": "bookmark" + } + ], + "image": { + "id": "d46a5dfb-bf63-49db-b9eb-c7519bf46017", + "links": [ + { + "href": "https://test.com/872f331350c54e59991a8de2cbffb40c/images/d46a5dfb-bf63-49db-b9eb-c7519bf46017", + "rel": "bookmark" + } + ] + }, + "OS-EXT-STS:vm_state": "active", + "OS-EXT-SRV-ATTR:instance_name": "instance-00000183", + "OS-SRV-USG:launched_at": "2019-02-11T19:12:51.000000", + "flavor": { + "id": "10259b47-bf17-4343-b885-32a68b1c4ba8", + "links": [ + { + "href": "https://test.com/872f331350c54e59991a8de2cbffb40c/flavors/10259b47-bf17-4343-b885-32a68b1c4ba8", + "rel": "bookmark" + } + ] + }, + "id": "d29f3151-592d-4011-9356-ad047794e236", + "security_groups": [ + { + "name": "zauk51bcgwy09_oam_security_group" + } + ], + "user_id": "3344345757302c88cf9f4ac7e9805c7073af90bce2e4c186ff1806fe867610b5", + "OS-DCF:diskConfig": "MANUAL", + "accessIPv4": "", + "accessIPv6": "", + "progress": 0, + "OS-EXT-STS:power_state": 1, + "OS-EXT-AZ:availability_zone": "auk51b-kvm-az01", + "metadata": { + "stack-root-id": "", + "vf_module_id": "26dd34cf-6b9b-485d-90e9-6101ff917516", + "vnf_id": "921662e3-eac6-446d-9573-ac377827c74f", + "workload_context": "Production", + "stack-name": "zauk51bcgwy01_base11", + "environment_context": "General_Revenue-Bearing", + "vf_module_name": "zauk51bcgwy01_base11", + "vnf_name": "zauk51bcgwy09", + "stack-root-name": "", + "stack-id": "0009693a-2fb1-4e91-80b8-70cc0a4e3f0f" + }, + "status": "ACTIVE", + "updated": "2019-02-11T19:12:46Z", + "hostId": "50197c55fc934e7b3947e17db762f0839320f94983df774d84991ad2", + "OS-EXT-SRV-ATTR:host": "test", + "OS-SRV-USG:terminated_at": null, + "key_name": null, + "OS-EXT-SRV-ATTR:hypervisor_hostname": "test.com", + "name": "zauk51bfrwl09oam001", + "created": "2019-02-11T19:11:58Z", + "tenant_id": "872f331350c54e59991a8de2cbffb40c", + "os-extended-volumes:volumes_attached": [], + "config_drive": "True" + } +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetStackResources.json b/so-simulator/src/main/resources/openstack/gr_api/GetStackResources.json new file mode 100644 index 0000000000..b50645b62f --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetStackResources.json @@ -0,0 +1,206 @@ +{ + "resources": [ + { + "resource_name": "ssc_1_trusted_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_trusted_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_trusted_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_service1_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service1_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_service1_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_1_subint_service1_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "27391d94-33af-474a-927d-d409249e8fd3", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_subint_role1_port_0_subinterfaces", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_role1_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "rel": "nested" + } + ], + "logical_resource_id": "ssc_1_subint_role1_port_0_subinterfaces", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "resource_type": "OS::Heat::ResourceGroup" + }, + { + "resource_name": "ssc_1_mgmt_port_1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_1", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_mgmt_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_role1_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_role1_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_role1_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_1_subint_role1_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_int_ha_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_int_ha_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_int_ha_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_server_1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_server_1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_server_1", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "resource_type": "OS::Nova::Server" + }, + { + "resource_name": "ssc_1_subint_service1_port_0_subinterfaces", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service1_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "nested" + } + ], + "logical_resource_id": "ssc_1_subint_service1_port_0_subinterfaces", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "31d0647a-6043-49a4-81b6-ccab29380672", + "resource_type": "OS::Heat::ResourceGroup" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetStackResourcesKeyPairFailure.json b/so-simulator/src/main/resources/openstack/gr_api/GetStackResourcesKeyPairFailure.json new file mode 100644 index 0000000000..650fb6b11d --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetStackResourcesKeyPairFailure.json @@ -0,0 +1,230 @@ +{ + "resources": [ + { + "resource_name": "ssc_1_trusted_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_trusted_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_trusted_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_service1_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service1_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_service1_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_1_subint_service1_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "27391d94-33af-474a-927d-d409249e8fd3", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_subint_role1_port_0_subinterfaces", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_role1_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "rel": "nested" + } + ], + "logical_resource_id": "ssc_1_subint_role1_port_0_subinterfaces", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "resource_type": "OS::Heat::ResourceGroup" + }, + { + "resource_name": "ssc_1_mgmt_port_1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_1", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_mgmt_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_role1_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_role1_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_role1_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_1_subint_role1_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_int_ha_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_int_ha_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_int_ha_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_server_1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_server_1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_server_1", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "resource_type": "OS::Nova::Server" + }, + { + "resource_name": "ssc_1_subint_service1_port_0_subinterfaces", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service1_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "nested" + } + ], + "logical_resource_id": "ssc_1_subint_service1_port_0_subinterfaces", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "31d0647a-6043-49a4-81b6-ccab29380672", + "resource_type": "OS::Heat::ResourceGroup" + }, + { + "resource_name": "ssc_1_subint_service1_port_0_subinterfaces", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service1_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "nested" + } + ], + "logical_resource_id": "kepair_name", + "resource_status": "CREATE_FAILED", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": null, + "resource_type": "OS::Nova::KeyPair" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/GetStackResourcesMacro.json b/so-simulator/src/main/resources/openstack/gr_api/GetStackResourcesMacro.json new file mode 100644 index 0000000000..ae317deab2 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/GetStackResourcesMacro.json @@ -0,0 +1,157 @@ +{ + "resources": [ + { + "resource_name": "ssc_1_trusted_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_trusted_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_trusted_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "d2f51f82-0ec2-4581-bd1a-d2a82073e52b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_service1_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service1_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_service1_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_1_subint_service1_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "27391d94-33af-474a-927d-d409249e8fd3", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_mgmt_port_1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_1", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_mgmt_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_role1_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_role1_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_role1_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_1_int_ha_port_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_int_ha_port_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_int_ha_port_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [ + "ssc_server_1" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "ssc_server_1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_server_1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_server_1", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:15Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "resource_type": "OS::Nova::Server" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Role1SubInterface0.json b/so-simulator/src/main/resources/openstack/gr_api/Role1SubInterface0.json new file mode 100644 index 0000000000..98639d0b8b --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Role1SubInterface0.json @@ -0,0 +1,41 @@ +{ + "stack": { + "parent": "447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "disable_rollback": true, + "description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "self" + } + ], + "stack_status_reason": "Stack CREATE completed successfully", + "stack_name": "tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y", + "stack_user_project_id": "dfffe8b2401b45368ca6e21f19796ce1", + "stack_owner": "m08699", + "creation_time": "2019-01-23T19:34:56Z", + "capabilities": [], + "notification_topics": [], + "updated_time": null, + "timeout_mins": 120, + "stack_status": "CREATE_COMPLETE", + "parameters": { + "OS::project_id": "0422ffb57ba042c0800a29dc85ca70f8", + "port_interface": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "OS::stack_id": "f711be16-2654-4a09-b89d-0511fda20e81", + "OS::stack_name": "tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y", + "vip_v6_address": "2001:1890:1001:4a32::3", + "network_id": "8be20e92-68d6-4aec-ae66-0fc0fc933546", + "subinterface_name_prefix": "tsbc0005v_tsbc0005vm002_subint_untruste_role1", + "counter": "0", + "mac_address": "02:05:94:a2:f2:7e", + "vip_address": "1.2.1.9", + "vlan_tag": "81", + "ip_address": "1.2.1.9", + "ip_v6_address": "2001:1890:1001:4a32::4" + }, + "id": "f711be16-2654-4a09-b89d-0511fda20e81", + "outputs": [], + "template_description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Role1SubInterface1Resources.json b/so-simulator/src/main/resources/openstack/gr_api/Role1SubInterface1Resources.json new file mode 100644 index 0000000000..a8e27655d1 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Role1SubInterface1Resources.json @@ -0,0 +1,70 @@ +{ + "resources": [ + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [ + "ssc_subint_role1_vmi_0_v6_ip_0", + "ssc_subint_role1_vmi_0_ip_0" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "2bbfa345-33bb-495a-94b2-fb514ee1cffc", + "resource_type": "OS::ContrailV2::VirtualMachineInterface" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_v6_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_v6_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_v6_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "e7f25707-12fd-454f-95ac-6a05cd70806f", + "resource_type": "OS::ContrailV2::InstanceIp" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "6d23f4d3-8f7b-42c5-bb9e-4aee5797d506", + "resource_type": "OS::ContrailV2::InstanceIp" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/SampleRequest.json b/so-simulator/src/main/resources/openstack/gr_api/SampleRequest.json new file mode 100644 index 0000000000..27bf79e0de --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/SampleRequest.json @@ -0,0 +1 @@ +{type: string, description: Unique name for this VF instance}f5_ssh_key: {type: string, description: SSH public key}f5_int_ha_net_prefix_v4: {type: string, description: IPv4 subnet prefixfor internal HA network} f5_int_ha_net_prefix_len_v4: type: number description: Prefix length of subnet associated withinternal HA network constraints: - range: {min: 0, max: 31} description: int_ha_net_plen must be between 0 and 31\nresources:f5_secgroup: type: OS::Neutron::SecurityGroup properties: description: Security Group for BIGIP networks name: str_replace: template: $VNF_NAME_f5_secgroup_0 params: $VNF_NAME: {get_param: vnf_name} rules: - {direction: egress, remote_ip_prefix: 0.0.0.0/0, protocol: tcp,ethertype: IPv4, port_range_max: 65535, port_range_min: 1} - {direction: egress, remote_ip_prefix: 0.0.0.0/0, protocol: udp,ethertype: IPv4, port_range_max: 65535, port_range_min: 1} - {direction: egress, remote_ip_prefix: 0.0.0.0/0, protocol: icmp,ethertype: IPv4} - {direction: egress, remote_ip_prefix: '::/0',protocol: icmp, ethertype: IPv6} - {direction: egress,remote_ip_prefix: '::/0', protocol: tcp, ethertype: IPv6, port_range_max: 65535, port_range_min: 1} - {direction: egress,remote_ip_prefix: '::/0', protocol: udp, ethertype: IPv6, port_range_max: 65535, port_range_min: 1} - {direction: ingress,remote_ip_prefix: 0.0.0.0/0, protocol: tcp, ethertype: IPv4, port_range_max: 65535, port_range_min: 1} - {direction: ingress,remote_ip_prefix: 0.0.0.0/0, protocol: udp, ethertype: IPv4, port_range_max: 65535, port_range_min: 1} - {direction: ingress,remote_ip_prefix: 0.0.0.0/0, protocol: icmp, ethertype: IPv4} -{direction: ingress, remote_ip_prefix: '::/0', protocol: icmp,ethertype: IPv6} - {direction: ingress, remote_ip_prefix: '::/0',protocol: tcp, ethertype: IPv6, port_range_max: 65535,port_range_min: 1} - {direction: ingress, remote_ip_prefix:'::/0', protocol: udp, ethertype: IPv6, port_range_max: 65535,port_range_min: 1} f5_keypair: type: OS::Nova::KeyPair properties: name: str_replace: template:$VNF_NAME_f5_key_pair_0 params: $VNF_NAME:{get_param: vnf_name} public_key: {get_param: f5_ssh_key} save_private_key: false f5_server_group: type:OS::Nova::ServerGroup properties: name: str_replace: template: $VNF_NAME_f5_server_group_0 params: $VNF_NAME: {get_param: vnf_name} policies:[anti-affinity] f5_internal_ha_ipam_net_0: type:OS::ContrailV2::NetworkIpam properties: name: str_replace: template: $VF_NAME_f5_int_ha_ipam_net_0 params: $VF_NAME: {get_param: vnf_name}f5_internal_ha_net_0: type: OS::ContrailV2::VirtualNetwork depends_on: [f5_internal_ha_ipam_net_0] properties: name: str_replace: template: $VF_NAME_f5_int_ha_net_0 params: $VF_NAME: {get_param: vnf_name} virtual_network_properties: {virtual_network_properties_rpf: enable} is_shared: false flood_unknown_unicast: true network_ipam_refs: - {get_resource: f5_internal_ha_ipam_net_0} network_ipam_refs_data: -network_ipam_refs_data_ipam_subnets: -network_ipam_refs_data_ipam_subnets_subnet: network_ipam_refs_data_ipam_subnets_subnet_ip_prefix: {get_param:f5_int_ha_net_prefix_v4} network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len: {get_param:f5_int_ha_net_prefix_len_v4} network_ipam_refs_data_ipam_subnets_enable_dhcp: false\noutputs:f5_server_group: description: BIGIP F5 Server group value:{get_resource: f5_server_group} f5_keypair: description: SSHkeypair for deployment value: {get_resource: f5_keypair}f5_sec_groups: description: List of security groups to use for allnetwork interfaces value: {get_resource: f5_secgroup}f5_int_ha_net_id: description: HA internal network for deployment value: {get_resource:f5_internal_ha_net_0}\n","stack_name":"dummy_id","parameters":{"vnf_name":"SO-DEV-VNF-vSAMP12_14-1806HF1-Aug18-GR_API-2XXX-9002"},"timeout_mins":120,"environment":"parameters: f5_int_ha_net_prefix_len_v4: 24f5_int_ha_net_prefix_v4: \"172.26.0.0\" f5_ssh_key: vnf_name:\n","disable_rollback":true}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/StackResourcesRole1ResourceGroup.json b/so-simulator/src/main/resources/openstack/gr_api/StackResourcesRole1ResourceGroup.json new file mode 100644 index 0000000000..0c68fd4524 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/StackResourcesRole1ResourceGroup.json @@ -0,0 +1,29 @@ +{ + "resources": [ + { + "parent_resource": "ssc_1_subint_role1_port_0_subinterfaces", + "resource_name": "0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c/resources/0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "nested" + } + ], + "logical_resource_id": "0", + "resource_status_reason": "state changed", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "f711be16-2654-4a09-b89d-0511fda20e81", + "resource_type": "vlan_subinterface_ssc_role1.yaml" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/StackResourcesservice1ResourceGroup.json b/so-simulator/src/main/resources/openstack/gr_api/StackResourcesservice1ResourceGroup.json new file mode 100644 index 0000000000..ce929e6753 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/StackResourcesservice1ResourceGroup.json @@ -0,0 +1,79 @@ +{ + "resources": [ + { + "parent_resource": "ssc_1_subint_service1_port_0_subinterfaces", + "resource_name": "1", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources/1", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", + "rel": "nested" + } + ], + "logical_resource_id": "1", + "resource_status_reason": "state changed", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", + "resource_type": "vlan_subinterface_ssc_service1.yaml" + }, + { + "parent_resource": "ssc_1_subint_service1_port_0_subinterfaces", + "resource_name": "0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources/0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a", + "rel": "nested" + } + ], + "logical_resource_id": "0", + "resource_status_reason": "state changed", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "b7019dd0-2ee9-4447-bdef-ac25676b205a", + "resource_type": "vlan_subinterface_ssc_service1.yaml" + }, + { + "parent_resource": "ssc_1_subint_service1_port_0_subinterfaces", + "resource_name": "2", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources/2", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "stack" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c", + "rel": "nested" + } + ], + "logical_resource_id": "2", + "resource_status_reason": "state changed", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "bd0fc728-cbde-4301-a581-db56f494675c", + "resource_type": "vlan_subinterface_ssc_service1.yaml" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Stack_Create.json b/so-simulator/src/main/resources/openstack/gr_api/Stack_Create.json new file mode 100644 index 0000000000..47d1063c5e --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Stack_Create.json @@ -0,0 +1,11 @@ +{ + "stack": { + "id": "stackId", + "links": [ + { + "href": "https://test.com/v1/e2a6af59d1cb43b2874e943bbbf8470a/stacks/zauk51bmcir02_base/20f2cad7-4626-476a-9279-4bd81ca62e4b", + "rel": "self" + } + ] + } +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/Stack_Created.json b/so-simulator/src/main/resources/openstack/gr_api/Stack_Created.json new file mode 100644 index 0000000000..6bbaf3e06e --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Stack_Created.json @@ -0,0 +1,17 @@ +{ + "stack": { + "description": null, + "links": null, + "stack_status_reason": null, + "stack_name": "${stackName}", + "updated_time": null, + "creation_time": null, + "stack_status": "CREATE_COMPLETE", + "id": "stackId", + "files": null, + "outputs": null, + "parameters": { + + } + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Stack_Deleted.json b/so-simulator/src/main/resources/openstack/gr_api/Stack_Deleted.json new file mode 100644 index 0000000000..ede10c99cc --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Stack_Deleted.json @@ -0,0 +1,17 @@ +{ + "stack": { + "description": null, + "links": null, + "stack_status_reason": "Stack DELETE completed successfully", + "stack_name": "${stackName}", + "updated_time": null, + "creation_time": null, + "stack_status": "DELETE_COMPLETE", + "id": "stackId", + "files": null, + "outputs": null, + "parameters": { + + } + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Stack_Failure.json b/so-simulator/src/main/resources/openstack/gr_api/Stack_Failure.json new file mode 100644 index 0000000000..12bdbef9f8 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Stack_Failure.json @@ -0,0 +1,17 @@ +{ + "stack": { + "description": null, + "links": null, + "stack_status_reason": "${stack_failure_message}", + "stack_name": "${stackName}", + "updated_time": null, + "creation_time": null, + "stack_status": "CREATE_FAILED", + "id": "stackId", + "files": null, + "outputs": null, + "parameters": { + + } + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Stack_In_Progress.json b/so-simulator/src/main/resources/openstack/gr_api/Stack_In_Progress.json new file mode 100644 index 0000000000..e17323e1ed --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Stack_In_Progress.json @@ -0,0 +1,17 @@ +{ + "stack": { + "description": null, + "links": null, + "stack_status_reason": null, + "stack_name": "${stackName}", + "updated_time": null, + "creation_time": null, + "stack_status": "CREATE_IN_PROGRESS", + "id": "stackId", + "files": null, + "outputs": null, + "parameters": { + + } + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/Stack_KeyPair_Failure.json b/so-simulator/src/main/resources/openstack/gr_api/Stack_KeyPair_Failure.json new file mode 100644 index 0000000000..f75669d1a5 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Stack_KeyPair_Failure.json @@ -0,0 +1,44 @@ +{ + "stack": { + "capabilities": [], + "creation_time": "2019-04-22T19:36:00Z", + "description": "BroadWorks NFM Template with Data and OAMP Interfaces - Version 13DEC2017", + "disable_rollback": true, + "id": "stackId", + "links": [ + ], + "notification_topics": [], + "outputs": [], + "parameters": { + "HostnameWithDomain": "test.com", + "OS::project_id": "efb9b00711a64eb087e3cca9767f7909", + "OS::stack_id": "8a2470c3-5fc0-479a-8849-5f38f5eeed35", + "OS::stack_name": "hst3bbfnm0011v_base", + "availability_zone_0": "hst3b-kvm-az01", + "bfnm_cinder_volume_id_0": "0659b195-1bf9-4def-8d15-fffee392131f", + "bfnm_cinder_volume_id_1": "c193ef62-128c-4bd5-9d7d-af7e91af36c0", + "bfnm_flavor_name": "nd.c4r8d0", + "bfnm_key_name": "hst3bbfnm0011vm001", + "bfnm_names": "hst3bbfnm0011vm001", + "bfnm_nsdnet_ips": "1.3.1.7", + "bfnm_nsdnet_net_security_group": "default", + "ifcfg-eth0_content_0": "DEVICE=\"eth0\" NEWLINE\nBOOTPROTO=static NEWLINE\nONBOOT=yes NEWLINE\nTYPE=\"Ethernet\" NEWLINE\nIPADDR=135.63.139.74 NEWLINE\nNETMASK=255.255.255.0 NEWLINE\nGATEWAY=135.63.139.65 NEWLINE\nIPV6INIT=no NEWLINE\nIPV6_AUTOCONF=no NEWLINE\nMTU=1450", + "mech_id": "m04137", + "nsdnet_net_id": "53f5c3f5-ae22-48b3-a476-c48d9fe46a75", + "ntp_servers": "server 135.190.235.222 iburst NEWLINE \nserver 135.191.235.222 iburst NEWLINE \nserver 135.193.235.222 iburst NEWLINE \noptions timeout:1 attempts:2", + "resolv_conf_content": "search test.com NEWLINE nameserver 135.190.235.222 NEWLINE nameserver 135.193.235.222 NEWLINE nameserver 135.191.235.222 NEWLINE options timeout:1 attempts:2", + "vf_module_id": "d117fdf9-bcba-4c92-b3da-af538615b63d", + "vnf_id": "8faf7e17-de35-4d9e-a731-1e463e94261a", + "vnf_name": "hst3bbfnm" + }, + "parent": null, + "stack_name": "${stackName}", + "stack_owner": "m95682", + "stack_status": "CREATE_FAILED", + "stack_status_reason": "Resource CREATE failed: Conflict: resources.bfnm_my_keypair: Key pair 'hst3bbfnm0011vm001' already exists. (HTTP 409) (Request-ID: req-941b0af6-63ae-4d6a-afbc-90b728bacf82)", + "stack_user_project_id": "2399d381718342edaff3d7daae2f2003", + "template_description": "BroadWorks NFM Template with Data and OAMP Interfaces - Version 13DEC2017", + "timeout_mins": 120, + "updated_time": null + } +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/Sync_Stack_Failure.json b/so-simulator/src/main/resources/openstack/gr_api/Sync_Stack_Failure.json new file mode 100644 index 0000000000..121da48a4a --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/Sync_Stack_Failure.json @@ -0,0 +1,10 @@ +{ + "explanation": "The resource could not be found.", + "code": 404, + "error": { + "message": "The Stack (Stability_Tools-27525-T-01-DPA2a_test_net_0) could not be found.", + "traceback": "Traceback (most recent call last):\n\n File \"/usr/lib/python2.7/dist-packages/heat/common/context.py\", line 300, in wrapped\n return func(self, ctx, *args, **kwargs)\n\n File \"/usr/lib/python2.7/dist-packages/heat/engine/service.py\", line 422, in identify_stack\n raise exception.StackNotFound(stack_name=stack_name)\n\nStackNotFound: The Stack (Stability_Tools-27525-T-01-DPA2a_test_net_0) could not be found.\n", + "type": "StackNotFound" + }, + "title": "Not Found" +} diff --git a/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface0.json b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface0.json new file mode 100644 index 0000000000..776a731cf6 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface0.json @@ -0,0 +1,41 @@ +{ + "stack": { + "parent": "31d0647a-6043-49a4-81b6-ccab29380672", + "disable_rollback": true, + "description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", + "rel": "self" + } + ], + "stack_status_reason": "Stack CREATE completed successfully", + "stack_name": "tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m", + "stack_user_project_id": "dfffe8b2401b45368ca6e21f19796ce1", + "stack_owner": "m08699", + "creation_time": "2019-01-23T19:34:57Z", + "capabilities": [], + "notification_topics": [], + "updated_time": null, + "timeout_mins": 120, + "stack_status": "CREATE_COMPLETE", + "parameters": { + "OS::project_id": "0422ffb57ba042c0800a29dc85ca70f8", + "port_interface": "27391d94-33af-474a-927d-d409249e8fd3", + "OS::stack_id": "b7019dd0-2ee9-4447-bdef-ac25676b205a", + "OS::stack_name": "tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m", + "vip_v6_address": "2001:1890:e005:1403::", + "network_id": "1bc1c5fe-896f-4629-b499-a5a36ece4253,c2f4ad4a-0089-41fa-aba7-a80963def29b,70bc637c-ea0f-4452-8aca-01e90c842ff1", + "subinterface_name_prefix": "tsbc0005v_tsbc0005vm002_subint_untrusted_service1", + "counter": "0", + "mac_address": "02:27:39:1d:94:33", + "vip_address": "1.1.1.8", + "vlan_tag": "101,102,103", + "ip_address": "1.1.1.5", + "ip_v6_address": "2001:1890:e005:1402:8000::" + }, + "id": "0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", + "outputs": [], + "template_description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface0Resources.json b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface0Resources.json new file mode 100644 index 0000000000..f98854ae2b --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface0Resources.json @@ -0,0 +1,72 @@ + + +{ + "resources": [ + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [ + "ssc_subint_role1_vmi_0_v6_ip_0", + "ssc_subint_role1_vmi_0_ip_0" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "d54dfd09-75c6-4e04-b204-909455b8f933", + "resource_type": "OS::ContrailV2::VirtualMachineInterface" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_v6_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_v6_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_v6_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "e7f25707-12fd-454f-95ac-6a05cd70806f", + "resource_type": "OS::ContrailV2::InstanceIp" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "6d23f4d3-8f7b-42c5-bb9e-4aee5797d506", + "resource_type": "OS::ContrailV2::InstanceIp" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface1.json b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface1.json new file mode 100644 index 0000000000..995a9d9c49 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface1.json @@ -0,0 +1,43 @@ + + +{ + "stack": { + "parent": "31d0647a-6043-49a4-81b6-ccab29380672", + "disable_rollback": true, + "description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a", + "rel": "self" + } + ], + "stack_status_reason": "Stack CREATE completed successfully", + "stack_name": "tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m", + "stack_user_project_id": "dfffe8b2401b45368ca6e21f19796ce1", + "stack_owner": "m08699", + "creation_time": "2019-01-23T19:34:57Z", + "capabilities": [], + "notification_topics": [], + "updated_time": null, + "timeout_mins": 120, + "stack_status": "CREATE_COMPLETE", + "parameters": { + "OS::project_id": "0422ffb57ba042c0800a29dc85ca70f8", + "port_interface": "27391d94-33af-474a-927d-d409249e8fd3", + "OS::stack_id": "b7019dd0-2ee9-4447-bdef-ac25676b205a", + "OS::stack_name": "tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m", + "vip_v6_address": "2001:1890:e005:1403::", + "network_id": "1bc1c5fe-896f-4629-b499-a5a36ece4253,c2f4ad4a-0089-41fa-aba7-a80963def29b,70bc637c-ea0f-4452-8aca-01e90c842ff1", + "subinterface_name_prefix": "tsbc0005v_tsbc0005vm002_subint_untrusted_service1", + "counter": "1", + "mac_address": "02:27:39:1d:94:33", + "vip_address": "1.1.1.8", + "vlan_tag": "101,102,103", + "ip_address": "1.1.1.5", + "ip_v6_address": "2001:1890:e005:1402:8000::" + }, + "id": "b7019dd0-2ee9-4447-bdef-ac25676b205a", + "outputs": [], + "template_description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface1Resources.json b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface1Resources.json new file mode 100644 index 0000000000..59f9dadc12 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface1Resources.json @@ -0,0 +1,72 @@ + + +{ + "resources": [ + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [ + "ssc_subint_role1_vmi_0_v6_ip_0", + "ssc_subint_role1_vmi_0_ip_0" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "f7a998c0-8939-4b07-bf4a-0862e9c325e1", + "resource_type": "OS::ContrailV2::VirtualMachineInterface" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_v6_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_v6_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_v6_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "e7f25707-12fd-454f-95ac-6a05cd70806f", + "resource_type": "OS::ContrailV2::InstanceIp" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "6d23f4d3-8f7b-42c5-bb9e-4aee5797d506", + "resource_type": "OS::ContrailV2::InstanceIp" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface2.json b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface2.json new file mode 100644 index 0000000000..2f8c3f4528 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface2.json @@ -0,0 +1,41 @@ +{ + "stack": { + "parent": "31d0647a-6043-49a4-81b6-ccab29380672", + "disable_rollback": true, + "description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbtsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675cc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c", + "rel": "self" + } + ], + "stack_status_reason": "Stack CREATE completed successfully", + "stack_name": "tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv", + "stack_user_project_id": "dfffe8b2401b45368ca6e21f19796ce1", + "stack_owner": "m08699", + "creation_time": "2019-01-23T19:34:57Z", + "capabilities": [], + "notification_topics": [], + "updated_time": null, + "timeout_mins": 120, + "stack_status": "CREATE_COMPLETE", + "parameters": { + "OS::project_id": "0422ffb57ba042c0800a29dc85ca70f8", + "port_interface": "27391d94-33af-474a-927d-d409249e8fd3", + "OS::stack_id": "bd0fc728-cbde-4301-a581-db56f494675c", + "OS::stack_name": "tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv", + "vip_v6_address": "2001:1890:e005:1403::", + "network_id": "1bc1c5fe-896f-4629-b499-a5a36ece4253,c2f4ad4a-0089-41fa-aba7-a80963def29b,70bc637c-ea0f-4452-8aca-01e90c842ff1", + "subinterface_name_prefix": "tsbc0005v_tsbc0005vm002_subint_untrusted_service1", + "counter": "2", + "mac_address": "02:27:39:1d:94:33", + "vip_address": "1.1.1.8", + "vlan_tag": "101,102,103", + "ip_address": "1.1.1.5", + "ip_v6_address": "2001:1890:e005:1402:8000::" + }, + "id": "bd0fc728-cbde-4301-a581-db56f494675c", + "outputs": [], + "template_description": "HOT template to instantiate a single Contrail VLAN sub-interface with associated instance IP addresses and allowed address pairs\n" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface2Resources.json b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface2Resources.json new file mode 100644 index 0000000000..7b9d27dd07 --- /dev/null +++ b/so-simulator/src/main/resources/openstack/gr_api/service1SubInterface2Resources.json @@ -0,0 +1,72 @@ + + +{ + "resources": [ + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [ + "ssc_subint_role1_vmi_0_v6_ip_0", + "ssc_subint_role1_vmi_0_ip_0" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "621c1fea-60b8-44ee-aede-c01b8b1aaa70", + "resource_type": "OS::ContrailV2::VirtualMachineInterface" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_v6_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_v6_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_v6_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "e7f25707-12fd-454f-95ac-6a05cd70806f", + "resource_type": "OS::ContrailV2::InstanceIp" + }, + { + "parent_resource": "0", + "resource_name": "ssc_subint_role1_vmi_0_ip_0", + "links": [ + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources/ssc_subint_role1_vmi_0_ip_0", + "rel": "self" + }, + { + "href": "https://test.com:8004/v1/0422ffb57ba042c0800a29dc85ca70f8/stacks/tsbc0005vm002ssc001-ssc_1_subint_role1_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_subint_role1_vmi_0_ip_0", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2019-01-23T19:34:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "6d23f4d3-8f7b-42c5-bb9e-4aee5797d506", + "resource_type": "OS::ContrailV2::InstanceIp" + } + ] +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/properties/aai-client.properties b/so-simulator/src/main/resources/properties/aai-client.properties new file mode 100644 index 0000000000..9acf198888 --- /dev/null +++ b/so-simulator/src/main/resources/properties/aai-client.properties @@ -0,0 +1,3 @@ +aai.endpoint=http://localhost:8443 +system.name=SO-Simulator +aai.auth=dGVzdDp0ZXN0dGVzdA==
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/HealthCheck.json b/so-simulator/src/main/resources/sdnc/HealthCheck.json new file mode 100644 index 0000000000..730fba2649 --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/HealthCheck.json @@ -0,0 +1,7 @@ +{ + "output": { + "ack-final-indicator": "Y", + "response-code": "200", + "response-message": "SDN-C is healthy" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/gr-api/AsyncRequest.xml b/so-simulator/src/main/resources/sdnc/gr-api/AsyncRequest.xml new file mode 100644 index 0000000000..3bce5bc20d --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/gr-api/AsyncRequest.xml @@ -0,0 +1,10 @@ +<input> + <service-information> + <service-type>useless-trash</service-type> + <service-instance-id>useless-trash</service-instance-id> + </service-information> + <svc-request-id>${responseCode}</svc-request-id> + <response-code>${responseCode}</response-code> + <response-message>${responseMessage}</response-message> + <ack-final-indicator>Y</ack-final-indicator> +</input>
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/gr-api/Network_Assign_Success.json b/so-simulator/src/main/resources/sdnc/gr-api/Network_Assign_Success.json new file mode 100644 index 0000000000..cd77c44c8e --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/gr-api/Network_Assign_Success.json @@ -0,0 +1,20 @@ +{ + "output": { + "response-code": "200", + "response-message": "Success in US746794 DG", + "ack-final-indicator": "Y", + "svc-request-id": "248783176134150", + "response-parameters": [ + { + "sequence-number": 2, + "tag-value": "DEBES0MDABE0207URWX01", + "tag-name": "vnf-host-name" + }, + { + "sequence-number": 1, + "tag-value": "911ce7a0-3852-4786-9f3b-41fa1adda63a", + "tag-name": "vnf-id" + } + ] + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/gr-api/SDNCFailure.json b/so-simulator/src/main/resources/sdnc/gr-api/SDNCFailure.json new file mode 100644 index 0000000000..05b49b44df --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/gr-api/SDNCFailure.json @@ -0,0 +1,8 @@ +{ + "output": { + "svc-request-id": "service-request-id-902112066", + "response-code": "500", + "response-message": "Error updating selflink in generic-vnf in AAI", + "ack-final-indicator": "Y" + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/gr-api/SDNCSuccess.json b/so-simulator/src/main/resources/sdnc/gr-api/SDNCSuccess.json new file mode 100644 index 0000000000..4c7360afab --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/gr-api/SDNCSuccess.json @@ -0,0 +1,20 @@ +{ + "output": { + "response-code": "${responseCode}", + "response-message": "${responseMessage}", + "ack-final-indicator": "${finalIndicator}", + "svc-request-id": "248783176134150", + "response-parameters": [ + { + "sequence-number": 2, + "tag-value": "DEBES0MDABE0207URWX01", + "tag-name": "vnf-host-name" + }, + { + "sequence-number": 1, + "tag-value": "911ce7a0-3852-4786-9f3b-41fa1adda63a", + "tag-name": "vnf-id" + } + ] + } +}
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/vnf-api/AssignResponseSuccess.xml b/so-simulator/src/main/resources/sdnc/vnf-api/AssignResponseSuccess.xml new file mode 100644 index 0000000000..e43dfbff64 --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/vnf-api/AssignResponseSuccess.xml @@ -0,0 +1,13 @@ + <output xmlns="com:att:sdnctl:vnf"> + <vnf-information> + <vnf-id>123123123123</vnf-id> + </vnf-information> + <response-code>200</response-code> + <svc-request-id>123123123123</svc-request-id> + <ack-final-indicator>Y</ack-final-indicator> + <service-information> + <subscriber-name>dontcare</subscriber-name> + <service-instance-id>0</service-instance-id> + <service-type>SDN-MOBILITY</service-type> + </service-information> + </output>
\ No newline at end of file diff --git a/so-simulator/src/main/resources/sdnc/vnf-api/NetworkAssignResponse.xml b/so-simulator/src/main/resources/sdnc/vnf-api/NetworkAssignResponse.xml new file mode 100644 index 0000000000..5b2d14275d --- /dev/null +++ b/so-simulator/src/main/resources/sdnc/vnf-api/NetworkAssignResponse.xml @@ -0,0 +1,14 @@ +<output xmlns="org:onap:sdnctl:vnf"> + <svc-request-id>${requestId}</svc-request-id> + <service-information> + <service-id>${serviceId}</service-id> + <service-type>${serviceType}</service-type> + <service-instance-id>${serviceInstanceId}</service-instance-id> + <subscriber-name>${subscriberName}</subscriber-name> + </service-information> + <response-code>200</response-code> + <network-information> + <network-id>${networkId}</network-id> + </network-information> + <ack-final-indicator>Y</ack-final-indicator> +</output>
\ No newline at end of file diff --git a/so-simulator/src/test/resources/citrus-context.xml b/so-simulator/src/test/resources/citrus-context.xml new file mode 100644 index 0000000000..f491dbcb7e --- /dev/null +++ b/so-simulator/src/test/resources/citrus-context.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:citrus="http://www.citrusframework.org/schema/config" + xmlns:citrus-http="http://www.citrusframework.org/schema/http/config" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + + http://www.citrusframework.org/schema/http/config http://www.citrusframework.org/schema/http/config/citrus-http-config.xsd + http://www.citrusframework.org/schema/config http://www.citrusframework.org/schema/config/citrus-config.xsd"> + + <citrus:schema-repository id="schemaRepository"> + <citrus:locations> + <citrus:location path="classpath:xsd/HelloService.xsd"/> + </citrus:locations> + </citrus:schema-repository> + + <!-- Test Http REST client --> + <citrus-http:client + id="simulatorClient" + request-url="http://localhost:8080/services/rest/simulator" + timeout="5000"/> + +</beans>
\ No newline at end of file diff --git a/so-simulator/src/test/resources/log4j.properties b/so-simulator/src/test/resources/log4j.properties new file mode 100644 index 0000000000..bbf07d9f49 --- /dev/null +++ b/so-simulator/src/test/resources/log4j.properties @@ -0,0 +1,12 @@ +# +# The logging properties used +# +log4j.rootLogger=INFO, out + +log4j.logger.com.consol.citrus=DEBUG +log4j.logger.org.springframework=INFO + +# CONSOLE appender not used by default +log4j.appender.out=org.apache.log4j.ConsoleAppender +log4j.appender.out.layout=org.apache.log4j.PatternLayout +log4j.appender.out.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5.5p %20.20c{2}| %m%n |