Merge "add junit coverage for SvnfmService"
authorSteve Smokowski <ss835w@att.com>
Fri, 16 Aug 2019 13:59:29 +0000 (13:59 +0000)
committerGerrit Code Review <gerrit@onap.org>
Fri, 16 Aug 2019 13:59:29 +0000 (13:59 +0000)
193 files changed:
adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/CinderClientImpl.java
adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java
adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java
adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java
adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java
adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudQueryResponse.java
adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java
adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/sdncrest/SDNCServiceRequest.java
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java [new file with mode: 0644]
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java [new file with mode: 0644]
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceMapper.java
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java [new file with mode: 0644]
adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java [new file with mode: 0644]
adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql
adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1.1__AddServiceRoleToRainyDayHandling.sql [new file with mode: 0644]
adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql [new file with mode: 0644]
adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.3__AlterColumnActionCategoryControllerSelectionCategory.sql [moved from adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1__AlterColumnActionCategoryControllerSelectionCategory.sql with 100% similarity]
adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/ServiceMapperTest.java
adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java
adapters/mso-catalog-db-adapter/src/test/resources/ExpectedService.json
adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql
adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java
adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java
adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java [deleted file]
adapters/mso-openstack-adapters/src/test/resources/schema.sql
adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt [new file with mode: 0644]
adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/WebSecurityConfigImpl.java
adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java
adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java
adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java
asdc-controller/src/main/java/org/onap/so/asdc/activity/DeployActivitySpecs.java
asdc-controller/src/main/java/org/onap/so/asdc/client/ASDCController.java
asdc-controller/src/main/java/org/onap/so/asdc/installer/ResourceStructure.java
asdc-controller/src/main/java/org/onap/so/asdc/installer/bpmn/WorkflowResource.java
asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java
asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java
asdc-controller/src/test/java/org/onap/so/asdc/installer/heat/ToscaResourceInputTest.java
asdc-controller/src/test/resources/schema.sql
bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy
bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtilFactory.groovy
bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapter.groovy
bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy
bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/db/RequestsDbListenerRunner.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/flowmanipulator/FlowManipulatorListenerRunner.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/validation/FlowValidatorRunner.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/resource/InstanceResourceList.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java [deleted file]
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/Metadata.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/LInterface.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/PServer.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceInstance.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/ServiceSubscription.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/Vlan.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/VpnBondingLink.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/generalobjects/License.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupMapperLayer.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java
bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/BuildingBlockValidatorRunnerTest.java
bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/WorkflowValidatorRunnerTest.java
bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/MyDisabledValidator.java
bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/listener/validation/ValidationConfig.java
bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java [deleted file]
bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java
bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/aaiL3NetworkInputWithSubnets.json
bpmn/MSOCommonBPMN/src/test/resources/__files/ExecuteBuildingBlock/l3NetworkExpectedWithSubnet.json
bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java [deleted file]
bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/WorkflowException.java
bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java [deleted file]
bpmn/mso-infrastructure-bpmn/pom.xml
bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java
bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.p12 [new file with mode: 0644]
bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.trust.jks [new file with mode: 0644]
bpmn/so-bpmn-building-blocks/src/main/java/org/onap/so/bpmn/infrastructure/bpmn/activity/DeployActivitySpecs.java
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy
bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HandlePNF.groovy
bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/ConfigCheckerDelegate.java
bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/dmaap/PnfEventReadyDmaapClient.java
bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java
bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java
bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/serviceTask/SdncUnderlayVpnPreprocessTask.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/activity/ExecuteActivity.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/validations/CloudRegionOrchestrationValidator.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterVfModuleObjectMapper.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java [new file with mode: 0644]
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIServiceInstanceResources.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIVnfResources.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java
bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java
bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java
bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java
bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java
bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIVnfResourcesTest.java
bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnf.json [new file with mode: 0644]
bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnfWithVservers.json [new file with mode: 0644]
bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverFullQueryResponse.json [new file with mode: 0644]
bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverQueryResponse.json [new file with mode: 0644]
cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyClient.java
cloudify-client/src/main/java/org/onap/so/cloudify/base/client/CloudifyRequest.java
common/pom.xml
common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
common/src/main/java/org/onap/so/listener/ListenerRunner.java [moved from bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/ListenerRunner.java with 89% similarity]
common/src/main/java/org/onap/so/listener/Skip.java [moved from bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/listener/Skip.java with 96% similarity]
common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
common/src/main/java/org/onap/so/utils/TargetEntities.java
common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/Actions.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiException.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ApiExceptionMapper.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/DuplicateRequestException.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/RequestDbFailureException.java
mso-api-handlers/mso-api-handler-common/src/main/java/org/onap/so/apihandlerinfra/exceptions/ValidateException.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckResponse.java [moved from bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/ICryptoHandler.java with 63% similarity]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckStatus.java [moved from mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java with 93% similarity]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java [deleted file]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SoSubsystems.java [moved from mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java with 91% similarity]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilder.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/handler/AbstractRestHandler.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/infra/rest/BpmnRequestBuilderTest.java
mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json [new file with mode: 0644]
mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/infra/Vnf.json
mso-api-handlers/mso-api-handler-infra/src/test/resources/application-test.yaml
mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql
mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryCustom.java
mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java
mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java
mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/data/controller/InstanceNameDuplicateCheckRequest.java
mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfResourceCustomization.java
mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/macro/RainyDayHandlerStatus.java
mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java
mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/RainyDayHandlerStatusRepository.java
mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java [new file with mode: 0644]
mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Service.java
mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/VfModule.java
mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Vnf.java
mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfcCustomizationRepositoryTest.java
mso-catalog-db/src/test/resources/schema.sql
version.properties
vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/config/ApplicationConfig.java
vnfm-simulator/vnfm-service/src/main/java/org/onap/svnfm/simulator/services/OperationProgressor.java

index b0c2d94..71cdcf6 100644 (file)
@@ -22,7 +22,6 @@
 package org.onap.so.openstack.utils;
 
 import org.onap.so.cloud.authentication.KeystoneAuthHolder;
-import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
 import org.onap.so.openstack.exceptions.MsoException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -42,7 +41,7 @@ public class CinderClientImpl extends MsoCommonUtils {
     /**
      * Gets the Cinder client.
      *
-     * @param cloudSite the cloud site
+     * @param cloudSiteId the cloud site
      * @param tenantId the tenant id
      * @return the glance client
      * @throws MsoException the mso exception
@@ -62,15 +61,12 @@ public class CinderClientImpl extends MsoCommonUtils {
      * @param cloudSiteId the cloud site id
      * @param tenantId the tenant id
      * @param limit limits the number of records returned
-     * @param visibility visibility in the image in openstack
      * @param marker the last viewed record
-     * @param name the image names
      * @return the list of images in openstack
-     * @throws MsoCloudSiteNotFound the mso cloud site not found
      * @throws CinderClientException the glance client exception
      */
     public Volumes queryVolumes(String cloudSiteId, String tenantId, int limit, String marker)
-            throws MsoCloudSiteNotFound, CinderClientException {
+            throws CinderClientException {
         try {
             Cinder cinderClient = getCinderClient(cloudSiteId, tenantId);
             // list is set to false, otherwise an invalid URL is appended
@@ -78,22 +74,23 @@ public class CinderClientImpl extends MsoCommonUtils {
                     cinderClient.volumes().list(false).queryParam("limit", limit).queryParam("marker", marker);
             return executeAndRecordOpenstackRequest(request, false);
         } catch (MsoException e) {
-            logger.error("Error building Cinder Client", e);
-            throw new CinderClientException("Error building Cinder Client", e);
+            String errorMsg = "Error building Cinder Client";
+            logger.error(errorMsg, e);
+            throw new CinderClientException(errorMsg, e);
         }
     }
 
 
-    public Volume queryVolume(String cloudSiteId, String tenantId, String volumeId)
-            throws MsoCloudSiteNotFound, CinderClientException {
+    public Volume queryVolume(String cloudSiteId, String tenantId, String volumeId) throws CinderClientException {
         try {
             Cinder cinderClient = getCinderClient(cloudSiteId, tenantId);
             // list is set to false, otherwise an invalid URL is appended
             OpenStackRequest<Volume> request = cinderClient.volumes().show(volumeId);
             return executeAndRecordOpenstackRequest(request, false);
         } catch (MsoException e) {
-            logger.error("Error building Cinder Client", e);
-            throw new CinderClientException("Error building Cinder Client", e);
+            String errorMsg = "Error building Cinder Client";
+            logger.error(errorMsg, e);
+            throw new CinderClientException(errorMsg, e);
         }
     }
 
index 8cacf85..47ba076 100644 (file)
@@ -132,14 +132,14 @@ public class MsoHeatEnvironmentEntry {
     }
 
     public boolean hasResources() {
-        if (this.resources != null && this.resources.size() > 0) {
+        if (this.resources != null && !this.resources.isEmpty()) {
             return true;
         }
         return false;
     }
 
     public boolean hasParameters() {
-        if (this.parameters != null && this.parameters.size() > 0) {
+        if (this.parameters != null && !this.parameters.isEmpty()) {
             return true;
         }
         return false;
@@ -147,7 +147,7 @@ public class MsoHeatEnvironmentEntry {
 
     public boolean containsParameter(String paramName) {
         boolean contains = false;
-        if (this.parameters == null || this.parameters.size() < 1) {
+        if (this.parameters == null || this.parameters.isEmpty()) {
             return false;
         }
         if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) {
@@ -246,22 +246,4 @@ public class MsoHeatEnvironmentEntry {
         sb.append(this.rawEntry.substring(indexOf));
         return sb;
     }
-
-    public void setHPAParameters(StringBuilder hpasb) {
-        try {
-            MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(hpasb.toString().getBytes());
-            Set<MsoHeatEnvironmentParameter> hpaParams = yaml.getParameterListFromEnvt();
-            for (MsoHeatEnvironmentParameter hpaparam : hpaParams) {
-                for (MsoHeatEnvironmentParameter param : this.parameters) {
-                    if (param.getName() == hpaparam.getName()) {
-                        param.setValue(hpaparam.getValue());
-                    }
-                }
-            }
-        } catch (Exception e) {
-            logger.debug("Exception:", e);
-            this.errorString = e.getMessage();
-            // e.printStackTrace();
-        }
-    }
 }
index 1d75892..6565db7 100644 (file)
@@ -44,7 +44,6 @@ import org.onap.so.adapters.vdu.VduModelInfo;
 import org.onap.so.adapters.vdu.VduPlugin;
 import org.onap.so.adapters.vdu.VduStateType;
 import org.onap.so.adapters.vdu.VduStatus;
-import org.onap.so.cloud.CloudConfig;
 import org.onap.so.cloud.authentication.KeystoneAuthHolder;
 import org.onap.so.db.catalog.beans.CloudIdentity;
 import org.onap.so.db.catalog.beans.CloudSite;
@@ -108,10 +107,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
             "{} Create Stack: Nested exception rolling back stack: {} ";
     public static final String IN_PROGRESS = "in_progress";
 
-    // Fetch cloud configuration each time (may be cached in CloudConfig class)
-    @Autowired
-    protected CloudConfig cloudConfig;
-
     @Autowired
     private Environment environment;
 
@@ -134,7 +129,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
 
     protected static final String CREATE_POLL_INTERVAL_DEFAULT = "15";
     private static final String DELETE_POLL_INTERVAL_DEFAULT = "15";
-    private static final String pollingMultiplierDefault = "60";
+    private static final String POLLING_MULTIPLIER_DEFAULT = "60";
 
     private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
 
@@ -200,7 +195,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
      * @param cloudOwner the cloud owner of the cloud site in which to create the stack
      * @param tenantId The Openstack ID of the tenant in which to create the Stack
      * @param stackName The name of the stack to create
-     * @param vduModelInfo contains information about the vdu model (added for plugin adapter)
+     * @param vduModel contains information about the vdu model (added for plugin adapter)
      * @param heatTemplate The Heat template
      * @param stackInputs A map of key/value inputs
      * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client
@@ -287,42 +282,41 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
             String cloudSiteId, String tenantId, CreateStackParam stackCreate) throws MsoException {
         if (stack == null) {
             throw new StackCreationException("Unknown Error in Stack Creation");
-        } else {
-            logger.info("Performing post processing backout: {} cleanUpKeyPair: {}, stack {}", backout, cleanUpKeyPair,
-                    stack);
-            if (!CREATE_COMPLETE.equals(stack.getStackStatus())) {
-                if (cleanUpKeyPair && !Strings.isNullOrEmpty(stack.getStackStatusReason())
-                        && isKeyPairFailure(stack.getStackStatusReason())) {
-                    return handleKeyPairConflict(cloudSiteId, tenantId, stackCreate, timeoutMinutes, backout, stack);
-                }
-                if (!backout) {
-                    logger.info("Status is not CREATE_COMPLETE, stack deletion suppressed");
-                    throw new StackCreationException("Stack rollback suppressed, stack not deleted");
-                } else {
-                    logger.info("Status is not CREATE_COMPLETE, stack deletion will be executed");
-                    String errorMessage = "Stack Creation Failed Openstack Status: " + stack.getStackStatus()
-                            + " Status Reason: " + stack.getStackStatusReason();
-                    try {
-                        Stack deletedStack =
-                                handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId);
-                        errorMessage = errorMessage + " , Rollback of Stack Creation completed with status: "
-                                + deletedStack.getStackStatus() + " Status Reason: "
-                                + deletedStack.getStackStatusReason();
-                    } catch (MsoException e) {
-                        logger.error("Sync Error Deleting Stack during rollback", e);
-                        if (e instanceof StackRollbackException) {
-                            errorMessage = errorMessage + e.getMessage();
-                        } else {
-                            errorMessage = errorMessage + " , Rollback of Stack Creation failed with sync error: "
-                                    + e.getMessage();
-                        }
-                    }
-                    throw new StackCreationException(errorMessage);
-                }
+        }
+
+        logger.info("Performing post processing backout: {} cleanUpKeyPair: {}, stack {}", backout, cleanUpKeyPair,
+                stack);
+        if (!CREATE_COMPLETE.equals(stack.getStackStatus())) {
+            if (cleanUpKeyPair && !Strings.isNullOrEmpty(stack.getStackStatusReason())
+                    && isKeyPairFailure(stack.getStackStatusReason())) {
+                return handleKeyPairConflict(cloudSiteId, tenantId, stackCreate, timeoutMinutes, backout, stack);
+            }
+            if (!backout) {
+                logger.info("Status is not CREATE_COMPLETE, stack deletion suppressed");
+                throw new StackCreationException("Stack rollback suppressed, stack not deleted");
             } else {
-                return stack;
+                logger.info("Status is not CREATE_COMPLETE, stack deletion will be executed");
+                String errorMessage = "Stack Creation Failed Openstack Status: " + stack.getStackStatus()
+                        + " Status Reason: " + stack.getStackStatusReason();
+                try {
+                    Stack deletedStack = handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId);
+                    errorMessage = errorMessage + " , Rollback of Stack Creation completed with status: "
+                            + deletedStack.getStackStatus() + " Status Reason: " + deletedStack.getStackStatusReason();
+                } catch (StackRollbackException se) {
+                    logger.error("Sync Error Deleting Stack during rollback process", se);
+                    errorMessage = errorMessage + se.getMessage();
+                } catch (MsoException e) {
+                    logger.error("Sync Error Deleting Stack during rollback", e);
+
+                    errorMessage =
+                            errorMessage + " , Rollback of Stack Creation failed with sync error: " + e.getMessage();
+                }
+                throw new StackCreationException(errorMessage);
             }
+        } else {
+            return stack;
         }
+
     }
 
     protected Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId,
@@ -330,7 +324,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin {
         int pollingFrequency =
                 Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT));
         int pollingMultiplier =
-                Integer.parseInt(this.environment.getProperty(pollingMultiplierProp, pollingMultiplierDefault));
+                Integer.parseInt(this.environment.getProperty(pollingMultiplierProp, POLLING_MULTIPLIER_DEFAULT));
         int numberOfPollingAttempts = Math.floorDiv((timeoutMinutes * pollingMultiplier), pollingFrequency);
         Heat heatClient = getHeatClient(cloudSiteId, tenantId);
         Stack latestStack = null;
index 49ba336..c75aa9a 100644 (file)
 
 package org.onap.so.openstack.utils;
 
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.woorea.openstack.heat.model.CreateStackParam;
-import com.woorea.openstack.heat.model.Stack;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.HashMap;
@@ -52,7 +48,6 @@ import org.onap.so.logger.MessageEnum;
 import org.onap.so.openstack.beans.HeatStatus;
 import org.onap.so.openstack.beans.StackInfo;
 import org.onap.so.openstack.exceptions.MsoAdapterException;
-import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound;
 import org.onap.so.openstack.exceptions.MsoException;
 import org.onap.so.openstack.exceptions.MsoOpenstackException;
 import org.onap.so.openstack.mappers.StackInfoMapper;
@@ -62,7 +57,11 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.stereotype.Component;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.collect.ImmutableSet;
+import com.woorea.openstack.heat.model.CreateStackParam;
+import com.woorea.openstack.heat.model.Stack;
 
 @Component
 public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
@@ -299,7 +298,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                 responseBody = getQueryBody((java.io.InputStream) response.getEntity());
                 if (responseBody != null) {
                     if (logger.isDebugEnabled()) {
-                        logger.debug("Multicloud Create Response Body: " + responseBody.toString());
+                        logger.debug("Multicloud Create Response Body: {}", responseBody);
                     }
                     Stack workloadStack = getWorkloadStack(responseBody.getWorkloadStatusReason());
                     if (workloadStack != null && !responseBody.getWorkloadStatus().equals("GET_FAILED")
@@ -354,7 +353,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
             }
         }
         if (workloadStack != null)
-            logger.debug("Multicloud getWorkloadStack() returning Stack Object: {} ", workloadStack.toString());
+            logger.debug("Multicloud getWorkloadStack() returning Stack Object: {} ", workloadStack);
         return workloadStack;
     }
 
@@ -457,8 +456,8 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
         Response response = multicloudClient.post(multicloudRequest);
         if (response.getStatus() != Response.Status.ACCEPTED.getStatusCode()) {
             if (logger.isDebugEnabled())
-                logger.debug(
-                        "Multicloud AAI update request failed: " + response.getStatus() + response.getStatusInfo());
+                logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
+                        response.getStatusInfo());
             return;
         }
 
@@ -470,14 +469,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                 Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT));
         int pollTimeout = (timeoutMinutes * 60) + updatePollInterval;
         boolean updateTimedOut = false;
-        logger.debug("updatePollInterval=" + updatePollInterval + ", pollTimeout=" + pollTimeout);
+        logger.debug("updatePollInterval={}, pollTimeout={}", updatePollInterval, pollTimeout);
 
         StackInfo stackInfo = null;
         while (true) {
             try {
                 stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, workloadId);
                 if (logger.isDebugEnabled())
-                    logger.debug(stackInfo.getStatus() + " (" + workloadId + ")");
+                    logger.debug("{} ({})", stackInfo.getStatus(), workloadId);
 
                 if (HeatStatus.UPDATING.equals(stackInfo.getStatus())) {
                     if (pollTimeout <= 0) {
@@ -494,7 +493,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
 
                     pollTimeout -= updatePollInterval;
                     if (logger.isDebugEnabled())
-                        logger.debug("pollTimeout remaining: " + pollTimeout);
+                        logger.debug("pollTimeout remaining: {}", pollTimeout);
                 } else {
                     break;
                 }
@@ -508,15 +507,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
         if (updateTimedOut) {
             if (logger.isDebugEnabled())
                 logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
-                        response.getStatusInfo().toString());
+                        response.getStatusInfo());
         } else if (!HeatStatus.UPDATED.equals(stackInfo.getStatus())) {
             if (logger.isDebugEnabled())
                 logger.debug("Multicloud AAI update request failed: {} {}", response.getStatus(),
-                        response.getStatusInfo().toString());
+                        response.getStatusInfo());
         } else {
             if (logger.isDebugEnabled())
-                logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(),
-                        response.getStatusInfo().toString());
+                logger.debug("Multicloud AAI update successful: {} {}", response.getStatus(), response.getStatusInfo());
         }
     }
 
@@ -543,12 +541,12 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
             int deletePollTimeout = pollTimeout;
             boolean createTimedOut = false;
             StringBuilder stackErrorStatusReason = new StringBuilder("");
-            logger.debug("createPollInterval=" + createPollInterval + ", pollTimeout=" + pollTimeout);
+            logger.debug("createPollInterval={}, pollTimeout={} ", createPollInterval, pollTimeout);
 
             while (true) {
                 try {
                     stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
-                    logger.debug(stackInfo.getStatus() + " (" + instanceId + ")");
+                    logger.debug("{} ({})", stackInfo.getStatus(), instanceId);
 
                     if (HeatStatus.BUILDING.equals(stackInfo.getStatus())) {
                         // Stack creation is still running.
@@ -567,7 +565,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                         sleep(createPollInterval * 1000L);
 
                         pollTimeout -= createPollInterval;
-                        logger.debug("pollTimeout remaining: " + pollTimeout);
+                        logger.debug("pollTimeout remaining: {}", pollTimeout);
                     } else {
                         // save off the status & reason msg before we attempt delete
                         stackErrorStatusReason
@@ -596,7 +594,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                             while (!deleted) {
                                 try {
                                     StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
-                                    logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
+                                    logger.debug("Deleting {}, status: {}", instanceId, queryInfo.getStatus());
                                     if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
                                         if (deletePollTimeout <= 0) {
                                             logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
@@ -610,7 +608,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                                             deletePollTimeout -= deletePollInterval;
                                         }
                                     } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) {
-                                        logger.debug("DELETE_COMPLETE for " + instanceId);
+                                        logger.debug("DELETE_COMPLETE for {}", instanceId);
                                         deleted = true;
                                         continue;
                                     } else {
@@ -664,7 +662,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                         while (!deleted) {
                             try {
                                 StackInfo queryInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
-                                logger.debug("Deleting " + instanceId + ", status: " + queryInfo.getStatus());
+                                logger.debug("Deleting {}, status: {}", instanceId, queryInfo.getStatus());
                                 if (HeatStatus.DELETING.equals(queryInfo.getStatus())) {
                                     if (deletePollTimeout <= 0) {
                                         logger.error(String.format("%s %s %s %s %s %s %s %s %d %s",
@@ -678,7 +676,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                                         deletePollTimeout -= deletePollInterval;
                                     }
                                 } else if (HeatStatus.NOTFOUND.equals(queryInfo.getStatus())) {
-                                    logger.debug("DELETE_COMPLETE for " + instanceId);
+                                    logger.debug("DELETE_COMPLETE for {}", instanceId);
                                     deleted = true;
                                     continue;
                                 } else {
@@ -730,7 +728,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
         } else {
             // Get initial status, since it will have been null after the create.
             stackInfo = queryStack(cloudSiteId, cloudOwner, tenantId, instanceId);
-            logger.debug("Multicloud stack query status is: " + stackInfo.getStatus());
+            logger.debug("Multicloud stack query status is: {}", stackInfo.getStatus());
         }
         return stackInfo;
     }
@@ -769,7 +767,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
         try {
             return new ObjectMapper().readerFor(MulticloudCreateResponse.class).readValue(body);
         } catch (Exception e) {
-            logger.debug("Exception retrieving multicloud vfModule POST response body " + e);
+            logger.debug("Exception retrieving multicloud vfModule POST response body ", e);
         }
         return null;
     }
@@ -786,7 +784,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
         try {
             return new ObjectMapper().readerFor(MulticloudQueryResponse.class).readValue(body);
         } catch (Exception e) {
-            logger.debug("Exception retrieving multicloud workload query response body " + e);
+            logger.debug("Exception retrieving multicloud workload query response body ", e);
         }
         return null;
     }
@@ -828,14 +826,11 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
                 client.addAdditionalHeader("Project", tenantId);
             }
         } catch (MalformedURLException e) {
-            logger.debug(
-                    String.format("Encountered malformed URL error getting multicloud rest client %s", e.getMessage()));
+            logger.debug("Encountered malformed URL error getting multicloud rest client ", e);
         } catch (IllegalArgumentException e) {
-            logger.debug(
-                    String.format("Encountered illegal argument getting multicloud rest client %s", e.getMessage()));
+            logger.debug("Encountered illegal argument getting multicloud rest client ", e);
         } catch (UriBuilderException e) {
-            logger.debug(
-                    String.format("Encountered URI builder error getting multicloud rest client %s", e.getMessage()));
+            logger.debug("Encountered URI builder error getting multicloud rest client ", e);
         }
         return client;
     }
@@ -989,7 +984,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin {
         // There are lots of HeatStatus values, so this is a bit long...
         HeatStatus heatStatus = stackInfo.getStatus();
         String statusMessage = stackInfo.getStatusMessage();
-        logger.debug("HeatStatus = " + heatStatus + " msg = " + statusMessage);
+        logger.debug("HeatStatus = {} msg = {}", heatStatus, statusMessage);
 
         if (logger.isDebugEnabled()) {
             logger.debug(String.format("Stack Status: %s", heatStatus.toString()));
index 069c6c7..44fc620 100644 (file)
@@ -130,13 +130,13 @@ public class MsoNeutronUtils extends MsoCommonUtils {
         network.setAdminStateUp(true);
 
         if (type == NetworkType.PROVIDER) {
-            if (provider != null && vlans != null && vlans.size() > 0) {
+            if (provider != null && vlans != null && !vlans.isEmpty()) {
                 network.setProviderPhysicalNetwork(provider);
                 network.setProviderNetworkType("vlan");
                 network.setProviderSegmentationId(vlans.get(0));
             }
         } else if (type == NetworkType.MULTI_PROVIDER) {
-            if (provider != null && vlans != null && vlans.size() > 0) {
+            if (provider != null && vlans != null && !vlans.isEmpty()) {
                 List<Segment> segments = new ArrayList<>(vlans.size());
                 for (int vlan : vlans) {
                     Segment segment = new Segment();
index ad37b39..c575304 100644 (file)
@@ -40,7 +40,7 @@ public class MulticloudQueryResponse implements Serializable {
     @JsonProperty("workload_status")
     private String workloadStatus;
     @JsonProperty("workload_status_reason")
-    private JsonNode workloadStatusReason;
+    private transient JsonNode workloadStatusReason;
 
     @JsonCreator
     public MulticloudQueryResponse(@JsonProperty("template_type") String templateType,
index e840d5a..e68364e 100644 (file)
@@ -322,8 +322,8 @@ public class MsoHeatUtilsTest extends MsoHeatUtils {
         CreateStackParam createStackParam = new CreateStackParam();
         createStackParam.setStackName("stackName");
 
-        doReturn(mockResources).when(heatUtils).queryStackResources(cloudSiteId, tenantId, "stackName", 2);
-        doNothing().when(novaClient).deleteKeyPair(cloudSiteId, tenantId, "KeypairName");
+        // doReturn(mockResources).when(heatUtils).queryStackResources(cloudSiteId, tenantId, "stackName", 2);
+        // doNothing().when(novaClient).deleteKeyPair(cloudSiteId, tenantId, "KeypairName");
         doReturn(null).when(heatUtils).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId);
         doReturn(createdStack).when(heatUtils).createStack(createStackParam, cloudSiteId, tenantId);
         doReturn(createdStack).when(heatUtils).processCreateStack(cloudSiteId, tenantId, 120, true, createdStack,
index c9f42d1..1b83722 100644 (file)
@@ -59,20 +59,6 @@ public class SDNCServiceRequest extends SDNCRequestCommon implements Serializabl
     // The SDNC service data specified by SDNC "agnostic" API
     private String sdncServiceData;
 
-    public SDNCServiceRequest() {}
-
-    public SDNCServiceRequest(String bpNotificationUrl, String bpTimeout, String sdncRequestId, String sdncService,
-            String sdncOperation, RequestInformation requestInformation, ServiceInformation serviceInformation,
-            String sdncServiceDataType, String sndcServiceData) {
-        super(bpNotificationUrl, bpTimeout, sdncRequestId);
-        this.requestInformation = requestInformation;
-        this.serviceInformation = serviceInformation;
-        this.sdncService = sdncService;
-        this.sdncOperation = sdncOperation;
-        this.sdncServiceDataType = sdncServiceDataType;
-        this.sdncServiceData = sndcServiceData;
-    }
-
     @JsonProperty("requestInformation")
     @XmlElement(name = "requestInformation")
     public RequestInformation getRequestInformation() {
index 79aad1a..b43447f 100644 (file)
@@ -25,6 +25,7 @@ import javax.ws.rs.ApplicationPath;
 import org.glassfish.jersey.server.ResourceConfig;
 import org.onap.so.adapters.catalogdb.rest.CatalogDbAdapterRest;
 import org.onap.so.adapters.catalogdb.rest.ServiceRestImpl;
+import org.onap.so.adapters.catalogdb.rest.VnfRestImpl;
 import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging;
 import org.springframework.context.annotation.Configuration;
 import io.swagger.jaxrs.config.BeanConfig;
@@ -42,6 +43,7 @@ public class JerseyConfiguration extends ResourceConfig {
         register(SwaggerSerializers.class);
         register(JaxRsFilterLogging.class);
         register(ServiceRestImpl.class);
+        register(VnfRestImpl.class);
         BeanConfig beanConfig = new BeanConfig();
         beanConfig.setVersion("1.0.2");
         beanConfig.setSchemes(new String[] {"https"});
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundException.java
new file mode 100644 (file)
index 0000000..f8a7ba6
--- /dev/null
@@ -0,0 +1,14 @@
+package org.onap.so.adapters.catalogdb.rest;
+
+public class CatalogEntityNotFoundException extends RuntimeException {
+
+    /**
+     * 
+     */
+    private static final long serialVersionUID = -300157844846680791L;
+
+    public CatalogEntityNotFoundException(String errorMessage) {
+        super(errorMessage);
+    }
+
+}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogEntityNotFoundExceptionMapper.java
new file mode 100644 (file)
index 0000000..c42eaab
--- /dev/null
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.adapters.catalogdb.rest;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class CatalogEntityNotFoundExceptionMapper implements ExceptionMapper<CatalogEntityNotFoundException> {
+
+    private static final Logger logger = LoggerFactory.getLogger(CatalogEntityNotFoundExceptionMapper.class);
+
+    @Override
+    public Response toResponse(CatalogEntityNotFoundException e) {
+        return Response.status(Response.Status.NOT_FOUND).entity(e).build();
+    }
+}
index dd18767..e74663d 100644 (file)
@@ -22,9 +22,11 @@ package org.onap.so.adapters.catalogdb.rest;
 
 import java.util.ArrayList;
 import java.util.List;
+import org.onap.so.db.catalog.beans.CvnfcCustomization;
 import org.onap.so.db.catalog.beans.HeatEnvironment;
 import org.onap.so.db.catalog.beans.VfModuleCustomization;
 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
+import org.onap.so.rest.catalog.beans.Cvnfc;
 import org.onap.so.rest.catalog.beans.Service;
 import org.onap.so.rest.catalog.beans.VfModule;
 import org.onap.so.rest.catalog.beans.Vnf;
@@ -39,16 +41,23 @@ public class ServiceMapper {
 
     public Service mapService(org.onap.so.db.catalog.beans.Service service, int depth) {
         Service restService = new Service();
-        restService.setCategory(service.getCategory());
+        if (service.getCategory() != null) {
+            restService.setCategory(service.getCategory());
+        }
         restService.setCreated(service.getCreated());
         restService.setDescription(service.getDescription());
-        restService.setDistrobutionStatus(service.getDistrobutionStatus());
+
+        if (service.getDistrobutionStatus() != null) {
+            restService.setDistrobutionStatus(service.getDistrobutionStatus());
+        }
         restService.setEnvironmentContext(service.getEnvironmentContext());
         restService.setModelInvariantId(service.getModelInvariantUUID());
         restService.setModelName(service.getModelName());
         restService.setModelVersionId(service.getModelUUID());
         restService.setModelVersion(service.getModelVersion());
-        restService.setServiceRole(service.getServiceRole());
+        if (service.getServiceRole() != null) {
+            restService.setServiceRole(service.getServiceRole());
+        }
         restService.setServiceType(service.getServiceType());
         restService.setWorkloadContext(service.getWorkloadContext());
         if (depth > 0)
@@ -63,7 +72,7 @@ public class ServiceMapper {
         return vnfs;
     }
 
-    private Vnf mapVnf(org.onap.so.db.catalog.beans.VnfResourceCustomization vnfResourceCustomization, int depth) {
+    protected Vnf mapVnf(org.onap.so.db.catalog.beans.VnfResourceCustomization vnfResourceCustomization, int depth) {
         Vnf vnf = new Vnf();
         vnf.setAvailabilityZoneMaxCount(vnfResourceCustomization.getAvailabilityZoneMaxCount());
         vnf.setCategory(vnfResourceCustomization.getVnfResources().getCategory());
@@ -81,9 +90,12 @@ public class ServiceMapper {
         vnf.setNfFunction(vnfResourceCustomization.getNfFunction());
         vnf.setNfNamingCode(vnfResourceCustomization.getNfNamingCode());
         vnf.setNfRole(vnfResourceCustomization.getNfRole());
+        vnf.setNfType(vnfResourceCustomization.getNfType());
+        vnf.setNfDataValid(vnfResourceCustomization.getNfDataValid());
         vnf.setOrchestrationMode(vnfResourceCustomization.getVnfResources().getOrchestrationMode());
         vnf.setSubCategory(vnfResourceCustomization.getVnfResources().getSubCategory());
         vnf.setToscaNodeType(vnfResourceCustomization.getVnfResources().getToscaNodeType());
+
         if (depth > 1) {
             vnf.setVfModule(mapVfModules(vnfResourceCustomization, depth));
         }
@@ -93,11 +105,11 @@ public class ServiceMapper {
     private List<VfModule> mapVfModules(VnfResourceCustomization vnfResourceCustomization, int depth) {
         List<VfModule> vfModules = new ArrayList<>();
         vnfResourceCustomization.getVfModuleCustomizations().parallelStream()
-                .forEach(vfModule -> vfModules.add(mapVfModule(vfModule)));
+                .forEach(vfModule -> vfModules.add(mapVfModule(vfModule, depth)));
         return vfModules;
     }
 
-    private VfModule mapVfModule(VfModuleCustomization vfModuleCust) {
+    private VfModule mapVfModule(VfModuleCustomization vfModuleCust, int depth) {
         VfModule vfModule = new VfModule();
         vfModule.setAvailabilityZoneCount(vfModuleCust.getAvailabilityZoneCount());
         vfModule.setCreated(vfModuleCust.getCreated());
@@ -113,9 +125,34 @@ public class ServiceMapper {
         vfModule.setModelName(vfModuleCust.getVfModule().getModelName());
         vfModule.setModelVersionId(vfModuleCust.getVfModule().getModelUUID());
         vfModule.setModelVersion(vfModuleCust.getVfModule().getModelVersion());
+        if (depth > 3) {
+            vfModule.setVnfc(mapCvnfcs(vfModuleCust));
+        }
         return vfModule;
     }
 
+    private List<Cvnfc> mapCvnfcs(VfModuleCustomization vfModuleCustomization) {
+        List<Cvnfc> cvnfcs = new ArrayList<>();
+        vfModuleCustomization.getCvnfcCustomization().parallelStream()
+                .forEach(cvnfcCust -> cvnfcs.add(mapCvnfcCus(cvnfcCust)));
+        return cvnfcs;
+    }
+
+    private Cvnfc mapCvnfcCus(CvnfcCustomization cvnfcCust) {
+        Cvnfc cvnfc = new Cvnfc();
+        cvnfc.setCreated(cvnfcCust.getCreated());
+        cvnfc.setDescription(cvnfcCust.getDescription());
+        cvnfc.setModelCustomizationId(cvnfcCust.getModelCustomizationUUID());
+        cvnfc.setModelInstanceName(cvnfcCust.getModelInstanceName());
+        cvnfc.setModelInvariantId(cvnfcCust.getModelInvariantUUID());
+        cvnfc.setModelName(cvnfcCust.getModelName());
+        cvnfc.setModelVersion(cvnfcCust.getModelVersion());
+        cvnfc.setModelVersionId(cvnfcCust.getModelUUID());
+        cvnfc.setNfcFunction(cvnfcCust.getNfcFunction());
+        cvnfc.setNfcNamingCode(cvnfcCust.getNfcNamingCode());
+        return cvnfc;
+    }
+
     private boolean getIsVolumeGroup(VfModuleCustomization vfModuleCust) {
         boolean isVolumeGroup = false;
         HeatEnvironment envt = vfModuleCust.getVolumeHeatEnv();
index 520de4d..6f556ed 100644 (file)
@@ -38,7 +38,7 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import io.swagger.annotations.ApiParam;
 
-@Api(value = "/v1/services", tags = "model")
+@Api(value = "/v1", tags = "model")
 @Path("/v1/services")
 @Component
 public class ServiceRestImpl {
@@ -49,18 +49,21 @@ public class ServiceRestImpl {
     @Autowired
     private ServiceMapper serviceMapper;
 
+
     @GET
     @Path("/{modelUUID}")
     @Produces({MediaType.APPLICATION_JSON})
     @Transactional(readOnly = true)
     public Service findService(@PathParam("modelUUID") String modelUUID, @QueryParam("depth") int depth) {
         org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(modelUUID);
+        if (service == null) {
+            new CatalogEntityNotFoundException("Unable to find Service " + modelUUID);
+        }
         return serviceMapper.mapService(service, depth);
     }
 
     @GET
-    @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List",
-            notes = "If no query parameters are sent an empty list will be returned")
+    @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List")
     @Produces({MediaType.APPLICATION_JSON})
     @Transactional(readOnly = true)
     public List<Service> queryServices(
@@ -74,6 +77,8 @@ public class ServiceRestImpl {
             serviceFromDB = serviceRepo.findByModelNameAndDistrobutionStatus(modelName, distributionStatus);
         } else if (!Strings.isNullOrEmpty(modelName)) {
             serviceFromDB = serviceRepo.findByModelName(modelName);
+        } else {
+            serviceFromDB = serviceRepo.findAll();
         }
         serviceFromDB.stream().forEach(serviceDB -> services.add(serviceMapper.mapService(serviceDB, depth)));
         return services;
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfMapper.java
new file mode 100644 (file)
index 0000000..52a8ccb
--- /dev/null
@@ -0,0 +1,37 @@
+package org.onap.so.adapters.catalogdb.rest;
+
+import org.onap.so.db.catalog.beans.VnfResource;
+import org.onap.so.db.catalog.beans.VnfResourceCustomization;
+import org.onap.so.rest.catalog.beans.Vnf;
+import org.springframework.stereotype.Component;
+import com.google.common.base.Strings;
+
+@Component
+public class VnfMapper {
+
+    public VnfResourceCustomization mapVnf(VnfResourceCustomization vnfCust, Vnf vnf) {
+
+        vnfCust.setAvailabilityZoneMaxCount(vnf.getAvailabilityZoneMaxCount());
+        vnfCust.setMaxInstances(vnf.getMaxInstances());
+        vnfCust.setMinInstances(vnf.getMinInstances());
+        vnfCust.setModelCustomizationUUID(vnf.getModelCustomizationId());
+        vnfCust.setModelInstanceName(vnf.getModelInstanceName());
+        vnfCust.setMultiStageDesign(vnf.getMultiStageDesign());
+        vnfCust.setNfDataValid(vnf.getNfDataValid());
+        vnfCust.setNfFunction(Strings.nullToEmpty(vnf.getNfFunction()));
+        vnfCust.setNfNamingCode(Strings.nullToEmpty(vnf.getNfNamingCode()));
+        vnfCust.setNfRole(Strings.nullToEmpty(vnf.getNfRole()));
+        vnfCust.setNfType(Strings.nullToEmpty(vnf.getNfType()));
+
+        VnfResource vnfRes = vnfCust.getVnfResources();
+        vnfRes.setOrchestrationMode(Strings.nullToEmpty(vnfRes.getOrchestrationMode()));
+        vnfRes.setSubCategory(Strings.nullToEmpty(vnfRes.getSubCategory()));
+        vnfRes.setToscaNodeType(Strings.nullToEmpty(vnfRes.getToscaNodeType()));
+        vnfRes.setModelInvariantUUID(vnfRes.getModelInvariantId());
+        vnfRes.setModelName(vnfRes.getModelName());
+        vnfRes.setModelUUID(vnfRes.getModelUUID());
+        vnfRes.setModelVersion(vnfRes.getModelVersion());
+        return vnfCust;
+    }
+
+}
diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java
new file mode 100644 (file)
index 0000000..4353526
--- /dev/null
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.adapters.catalogdb.rest;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.onap.so.db.catalog.beans.VnfResourceCustomization;
+import org.onap.so.db.catalog.data.repository.ServiceRepository;
+import org.onap.so.db.catalog.data.repository.VnfCustomizationRepository;
+import org.onap.so.rest.catalog.beans.Vnf;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+
+@Api(value = "/v1/services/{modelUUID}/vnfs", tags = "model")
+@Path("/v1/services/{modelUUID}/vnfs")
+@Component
+public class VnfRestImpl {
+
+    @Autowired
+    private ServiceRepository serviceRepo;
+
+    @Autowired
+    private ServiceMapper serviceMapper;
+
+    @Autowired
+    private VnfMapper vnfMapper;
+
+    @Autowired
+    private VnfCustomizationRepository vnfCustRepo;
+
+    @GET
+    @ApiOperation(value = "Find a VNF model contained within a service", response = Vnf.class)
+    @Path("/{modelCustomizationUUID}")
+    @Produces({MediaType.APPLICATION_JSON})
+    @Transactional(readOnly = true)
+    public Vnf findService(@PathParam("modelUUID") String serviceModelUUID,
+            @PathParam("modelCustomizationUUID") String modelCustomizationUUID, @QueryParam("depth") int depth) {
+        org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(serviceModelUUID);
+        if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) {
+            throw new WebApplicationException("Vnf Not Found", 404);
+        }
+        List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream()
+                .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID))
+                .collect(Collectors.toList());
+        if (vnfCustom.isEmpty() || vnfCustom == null) {
+            return null;
+        } else if (vnfCustom.size() > 1) {
+            throw new RuntimeException(
+                    "More than one Vnf model returned with model Customization UUID: " + modelCustomizationUUID);
+        }
+        return serviceMapper.mapVnf(vnfCustom.get(0), depth);
+    }
+
+    @PUT
+    @ApiOperation(value = "Update a VNF model contained within a service", response = Vnf.class)
+    @Path("/{modelCustomizationUUID}")
+    @Produces({MediaType.APPLICATION_JSON})
+    @Transactional
+    public Response findService(@PathParam("modelUUID") String serviceModelUUID,
+            @PathParam("modelCustomizationUUID") String modelCustomizationUUID, Vnf vnf) {
+        org.onap.so.db.catalog.beans.Service service = serviceRepo.findOneByModelUUID(serviceModelUUID);
+        List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream()
+                .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID))
+                .collect(Collectors.toList());
+        if (vnfCustom.isEmpty() || vnfCustom == null) {
+            throw new RuntimeException("No Vnf Found");
+        } else if (vnfCustom.size() > 1) {
+            throw new RuntimeException(
+                    "More than one Vnf model returned with model Customization UUID: " + modelCustomizationUUID);
+        }
+        VnfResourceCustomization vnfCust = vnfMapper.mapVnf(vnfCustom.get(0), vnf);
+        vnfCustRepo.save(vnfCust);
+        return Response.ok().build();
+    }
+
+}
+
index 486b53c..13d736e 100644 (file)
@@ -813,3 +813,5 @@ VALUES
 ('ConfigDeployVnfBB', 'NO_VALIDATE', 'CUSTOM');
 
 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;
diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1.1__AddServiceRoleToRainyDayHandling.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.1.1__AddServiceRoleToRainyDayHandling.sql
new file mode 100644 (file)
index 0000000..8fe3caf
--- /dev/null
@@ -0,0 +1,2 @@
+use catalogdb;
+ALTER TABLE rainy_day_handler_macro ADD COLUMN IF NOT EXISTS SERVICE_ROLE varchar(300) DEFAULT NULL;
\ No newline at end of file
diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V6.2__AddNfValidData.sql
new file mode 100644 (file)
index 0000000..93dde13
--- /dev/null
@@ -0,0 +1,5 @@
+USE catalogdb;
+
+ALTER TABLE vnf_resource_customization
+ADD IF NOT EXISTS NF_DATA_VALID tinyint(1) DEFAULT 0;
+
index 8decd77..d46fd9c 100644 (file)
@@ -67,6 +67,7 @@ public class ServiceMapperTest {
         testService.setModelVersion("modelVersion");
         testService.setServiceType("serviceType");
         testService.setServiceRole("serviceRole");
+
         testService.getVnfCustomizations().add(getTestVnfCustomization());
         return testService;
     }
index f65f521..f82c7ac 100644 (file)
@@ -22,15 +22,14 @@ package org.onap.so.db.catalog.client;
 
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import java.util.List;
 import java.util.UUID;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.onap.so.adapters.catalogdb.CatalogDBApplication;
 import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest;
 import org.onap.so.db.catalog.beans.AuthenticationType;
 import org.onap.so.db.catalog.beans.CloudIdentity;
@@ -56,10 +55,7 @@ import org.onap.so.db.catalog.beans.macro.NorthBoundRequest;
 import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.web.server.LocalServerPort;
-import org.springframework.test.context.ActiveProfiles;
-import org.springframework.test.context.junit4.SpringRunner;
 
 public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
 
@@ -74,6 +70,8 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     @Autowired
     CatalogDbClientPortChanger client;
 
+
+
     @Before
     public void initialize() {
         client.wiremockPort = String.valueOf(port);
@@ -87,114 +85,115 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     @Test
     public void testGetRainyDayHandler_Regex() {
         RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*",
-                "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found.");
-        Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy());
+                "*", "*", "*", "The Flavor ID (nd.c6r16d20) could not be found.", "*");
+        assertEquals("Rollback", rainyDayHandlerStatus.getPolicy());
     }
 
     @Test
     public void testGetRainyDayHandler__Encoding_Regex() {
         RainyDayHandlerStatus rainyDayHandlerStatus = client.getRainyDayHandlerStatus("AssignServiceInstanceBB", "*",
                 "*", "*", "*",
-                "resources.lba_0_dmz_vmi_0: Unknown id: Error: oper 1 url /fqname-to-id body {\"fq_name\": [\"zrdm6bvota05-dmz_sec_group\"], \"type\": \"security-group\"} response Name ['zrdm6bvota05-dmz_sec_group'] not found");
-        Assert.assertEquals("Rollback", rainyDayHandlerStatus.getPolicy());
+                "resources.lba_0_dmz_vmi_0: Unknown id: Error: oper 1 url /fqname-to-id body {\"fq_name\": [\"zrdm6bvota05-dmz_sec_group\"], \"type\": \"security-group\"} response Name ['zrdm6bvota05-dmz_sec_group'] not found",
+                "*");
+        assertEquals("Rollback", rainyDayHandlerStatus.getPolicy());
     }
 
     @Test
     public void testGetCloudSiteHappyPath() throws Exception {
         CloudSite cloudSite = client.getCloudSite(MTN13);
-        Assert.assertNotNull(cloudSite);
-        Assert.assertNotNull(cloudSite.getIdentityService());
-        Assert.assertEquals("MDT13", cloudSite.getClli());
-        Assert.assertEquals("mtn13", cloudSite.getRegionId());
-        Assert.assertEquals("MTN13", cloudSite.getIdentityServiceId());
+        assertNotNull(cloudSite);
+        assertNotNull(cloudSite.getIdentityService());
+        assertEquals("MDT13", cloudSite.getClli());
+        assertEquals("mtn13", cloudSite.getRegionId());
+        assertEquals("MTN13", cloudSite.getIdentityServiceId());
     }
 
     @Test
     public void testGetCloudSiteNotFound() throws Exception {
         CloudSite cloudSite = client.getCloudSite(UUID.randomUUID().toString());
-        Assert.assertNull(cloudSite);
+        assertNull(cloudSite);
     }
 
     @Test
     public void testGetCloudifyManagerHappyPath() throws Exception {
         CloudifyManager cloudifyManager = client.getCloudifyManager("mtn13");
-        Assert.assertNotNull(cloudifyManager);
-        Assert.assertEquals("http://localhost:28090/v2.0", cloudifyManager.getCloudifyUrl());
+        assertNotNull(cloudifyManager);
+        assertEquals("http://localhost:28090/v2.0", cloudifyManager.getCloudifyUrl());
 
     }
 
     @Test
     public void testGetCloudifyManagerNotFound() throws Exception {
         CloudifyManager cloudifyManager = client.getCloudifyManager(UUID.randomUUID().toString());
-        Assert.assertNull(cloudifyManager);
+        assertNull(cloudifyManager);
     }
 
 
     @Test
     public void testGetCloudSiteByClliAndAicVersionHappyPath() throws Exception {
         CloudSite cloudSite = client.getCloudSiteByClliAndAicVersion("MDT13", "2.5");
-        Assert.assertNotNull(cloudSite);
+        assertNotNull(cloudSite);
     }
 
     @Test
     public void testGetCloudSiteByClliAndAicVersionNotFound() throws Exception {
         CloudSite cloudSite = client.getCloudSiteByClliAndAicVersion("MDT13", "232496239746328");
-        Assert.assertNull(cloudSite);
+        assertNull(cloudSite);
     }
 
     @Test
     public void testGetServiceByID() throws Exception {
         Service serviceByID = client.getServiceByID("5df8b6de-2083-11e7-93ae-92361f002671");
-        Assert.assertNotNull(serviceByID);
-        Assert.assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName());
-        Assert.assertEquals("NA", serviceByID.getServiceType());
-        Assert.assertEquals("NA", serviceByID.getServiceRole());
+        assertNotNull(serviceByID);
+        assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName());
+        assertEquals("NA", serviceByID.getServiceType());
+        assertEquals("NA", serviceByID.getServiceRole());
     }
 
     @Test
     public void testGetServiceByIDNotFound() throws Exception {
         Service serviceByID = client.getServiceByID(UUID.randomUUID().toString());
-        Assert.assertNull(serviceByID);
+        assertNull(serviceByID);
     }
 
     @Test
     public void testGetVfModuleByModelUUID() throws Exception {
         VfModule vfModule = client.getVfModuleByModelUUID("20c4431c-246d-11e7-93ae-92361f002671");
-        Assert.assertNotNull(vfModule);
-        Assert.assertNotNull(vfModule.getVfModuleCustomization());
-        Assert.assertEquals("78ca26d0-246d-11e7-93ae-92361f002671", vfModule.getModelInvariantUUID());
-        Assert.assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName());
+        assertNotNull(vfModule);
+        assertNotNull(vfModule.getVfModuleCustomization());
+        assertEquals("78ca26d0-246d-11e7-93ae-92361f002671", vfModule.getModelInvariantUUID());
+        assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName());
     }
 
     @Test
     public void testGetVfModuleByModelUUIDNotFound() throws Exception {
         VfModule vfModule = client.getVfModuleByModelUUID(UUID.randomUUID().toString());
-        Assert.assertNull(vfModule);
+        assertNull(vfModule);
     }
 
     @Test
     public void testGetVnfResourceByModelUUID() throws Exception {
         VnfResource vnfResource = client.getVnfResourceByModelUUID("ff2ae348-214a-11e7-93ae-92361f002671");
-        Assert.assertNotNull(vnfResource);
-        Assert.assertEquals("vSAMP10a", vnfResource.getModelName());
+        assertNotNull(vnfResource);
+        assertEquals("vSAMP10a", vnfResource.getModelName());
     }
 
     @Test
     public void testGetVnfResourceByModelUUIDNotFound() throws Exception {
         VnfResource vnfResource = client.getVnfResourceByModelUUID(UUID.randomUUID().toString());
-        Assert.assertNull(vnfResource);
+        assertNull(vnfResource);
     }
 
     @Test
     public void testGetVnfResourceCustomizationByModelCustomizationUUID() {
         VnfResourceCustomization vnfResourceCustomization =
                 client.getVnfResourceCustomizationByModelCustomizationUUID("68dc9a92-214c-11e7-93ae-92361f002671");
-        Assert.assertNotNull(vnfResourceCustomization);
-        Assert.assertEquals("vSAMP", vnfResourceCustomization.getNfRole());
-        Assert.assertNotNull(vnfResourceCustomization.getModelCustomizationUUID());
-        Assert.assertNotNull(vnfResourceCustomization.getVnfResources());
-        Assert.assertNotNull(vnfResourceCustomization.getVfModuleCustomizations());
-        Assert.assertEquals("vSAMP10a", vnfResourceCustomization.getVnfResources().getModelName());
+        assertNotNull(vnfResourceCustomization);
+        assertEquals("vSAMP", vnfResourceCustomization.getNfRole());
+        assertNotNull(vnfResourceCustomization.getModelCustomizationUUID());
+        assertNotNull(vnfResourceCustomization.getVnfResources());
+        assertNotNull(vnfResourceCustomization.getVfModuleCustomizations());
+        assertEquals("vSAMP10a", vnfResourceCustomization.getVnfResources().getModelName());
         assertTrue("skip post instantiation configuration", vnfResourceCustomization.isSkipPostInstConf());
     }
 
@@ -202,15 +201,15 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     public void testGetVnfResourceCustomizationByModelCustomizationUUINotFound() {
         VnfResourceCustomization vnfResourceCustomization =
                 client.getVnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
-        Assert.assertNull(vnfResourceCustomization);
+        assertNull(vnfResourceCustomization);
     }
 
     @Test
     public void testGetInstanceGroupByModelUUID() {
         InstanceGroup instanceGroup = client.getInstanceGroupByModelUUID("0c8692ef-b9c0-435d-a738-edf31e71f38b");
-        Assert.assertNotNull(instanceGroup);
-        Assert.assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName());
-        Assert.assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806",
+        assertNotNull(instanceGroup);
+        assertEquals("network_collection_resource_1806..NetworkCollection..0", instanceGroup.getModelName());
+        assertEquals("org.openecomp.resource.cr.NetworkCollectionResource1806",
                 instanceGroup.getToscaNodeType().toString());
     }
 
@@ -218,33 +217,33 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     public void testGetVfModuleCustomizationByModelCuztomizationUUID() {
         VfModuleCustomization vfModuleCustomization =
                 client.getVfModuleCustomizationByModelCuztomizationUUID("cb82ffd8-252a-11e7-93ae-92361f002671");
-        Assert.assertNotNull(vfModuleCustomization);
-        Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID());
-        Assert.assertEquals("base", vfModuleCustomization.getLabel());
+        assertNotNull(vfModuleCustomization);
+        assertNotNull(vfModuleCustomization.getModelCustomizationUUID());
+        assertEquals("base", vfModuleCustomization.getLabel());
     }
 
     @Test
     public void testGetVfModuleCustomizationByModelCuztomizationUUIDNotFound() {
         VfModuleCustomization vfModuleCustomization =
                 client.getVfModuleCustomizationByModelCuztomizationUUID(UUID.randomUUID().toString());
-        Assert.assertNull(vfModuleCustomization);
+        assertNull(vfModuleCustomization);
     }
 
     @Test
     public void testGetNetworkResourceCustomizationByModelCustomizationUUID() {
         NetworkResourceCustomization networkResourceCustomization =
                 client.getNetworkResourceCustomizationByModelCustomizationUUID("3bdbb104-476c-483e-9f8b-c095b3d308ac");
-        Assert.assertNotNull(networkResourceCustomization);
-        Assert.assertNotNull(networkResourceCustomization.getModelCustomizationUUID());
-        Assert.assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName());
-        Assert.assertNotNull(networkResourceCustomization.getNetworkResource());
+        assertNotNull(networkResourceCustomization);
+        assertNotNull(networkResourceCustomization.getModelCustomizationUUID());
+        assertEquals("CONTRAIL30_GNDIRECT 9", networkResourceCustomization.getModelInstanceName());
+        assertNotNull(networkResourceCustomization.getNetworkResource());
     }
 
     @Test
     public void testGetNetworkResourceCustomizationByModelCustomizationUUIDNotFound() {
         NetworkResourceCustomization networkResourceCustomization =
                 client.getNetworkResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
-        Assert.assertNull(networkResourceCustomization);
+        assertNull(networkResourceCustomization);
     }
 
     @Test
@@ -252,10 +251,10 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         VfModuleCustomization vfModuleCustomization =
                 client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
                         "cb82ffd8-252a-11e7-93ae-92361f002672", "20c4431c-246d-11e7-93ae-92361f002672");
-        Assert.assertNotNull(vfModuleCustomization);
-        Assert.assertNotNull(vfModuleCustomization.getModelCustomizationUUID());
-        Assert.assertNotNull(vfModuleCustomization.getVfModule());
-        Assert.assertEquals("base", vfModuleCustomization.getLabel());
+        assertNotNull(vfModuleCustomization);
+        assertNotNull(vfModuleCustomization.getModelCustomizationUUID());
+        assertNotNull(vfModuleCustomization.getVfModule());
+        assertEquals("base", vfModuleCustomization.getLabel());
     }
 
     @Test
@@ -263,44 +262,43 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         VfModuleCustomization vfModuleCustomization =
                 client.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
                         "cb82ffd8-252a-11e7-93ae-92361f002672", UUID.randomUUID().toString());
-        Assert.assertNull(vfModuleCustomization);
+        assertNull(vfModuleCustomization);
     }
 
     @Test
     public void testGetFirstByServiceModelUUIDAndAction() {
         ServiceRecipe serviceRecipe =
                 client.getFirstByServiceModelUUIDAndAction("4694a55f-58b3-4f17-92a5-796d6f5ffd0d", "createInstance");
-        Assert.assertNotNull(serviceRecipe);
-        Assert.assertNotNull(serviceRecipe.getServiceModelUUID());
-        Assert.assertNotNull(serviceRecipe.getAction());
-        Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance",
-                serviceRecipe.getOrchestrationUri());
-        Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription());
+        assertNotNull(serviceRecipe);
+        assertNotNull(serviceRecipe.getServiceModelUUID());
+        assertNotNull(serviceRecipe.getAction());
+        assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", serviceRecipe.getOrchestrationUri());
+        assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription());
     }
 
     @Test
     public void testGetFirstByServiceModelUUIDAndActionNotFound() {
         ServiceRecipe serviceRecipe = client.getFirstByServiceModelUUIDAndAction("5df8b6de-2083-11e7-93ae-92361f002671",
                 UUID.randomUUID().toString());
-        Assert.assertNull(serviceRecipe);
+        assertNull(serviceRecipe);
     }
 
     @Test
     public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersion() {
         VnfResource vnfResource = client
                 .getFirstVnfResourceByModelInvariantUUIDAndModelVersion("2fff5b20-214b-11e7-93ae-92361f002671", "2.0");
-        Assert.assertNotNull(vnfResource);
-        Assert.assertNotNull(vnfResource.getModelInvariantId());
-        Assert.assertNotNull(vnfResource.getModelVersion());
-        Assert.assertNotNull(vnfResource.getHeatTemplates());
-        Assert.assertEquals("vSAMP10a", vnfResource.getModelName());
+        assertNotNull(vnfResource);
+        assertNotNull(vnfResource.getModelInvariantId());
+        assertNotNull(vnfResource.getModelVersion());
+        assertNotNull(vnfResource.getHeatTemplates());
+        assertEquals("vSAMP10a", vnfResource.getModelName());
     }
 
     @Test
     public void testGetFirstVnfResourceByModelInvariantUUIDAndModelVersionNotFound() {
         VnfResource vnfResource = client.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
                 "2fff5b20-214b-11e7-93ae-92361f002671", UUID.randomUUID().toString());
-        Assert.assertNull(vnfResource);
+        assertNull(vnfResource);
     }
 
     @Test
@@ -309,29 +307,28 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         vnfr.setModelUUID("ff2ae348-214a-11e7-93ae-92361f002671");
         VnfResourceCustomization firstVnfResourceCustomizationByModelInstanceNameAndVnfResources =
                 client.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources("vSAMP10a 1", vnfr);
-        Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources);
-        Assert.assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole());
-        Assert.assertEquals("vSAMP10a 1",
+        assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources);
+        assertEquals("vSAMP", firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getNfRole());
+        assertEquals("vSAMP10a 1",
                 firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getModelInstanceName());
-        Assert.assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources());
-        Assert.assertNotNull(
-                firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations());
+        assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVnfResources());
+        assertNotNull(firstVnfResourceCustomizationByModelInstanceNameAndVnfResources.getVfModuleCustomizations());
     }
 
     @Test
     public void testGetFirstVnfRecipeByNfRoleAndAction() {
         VnfRecipe vnfRecipe = client.getFirstVnfRecipeByNfRoleAndAction("GR-API-DEFAULT", "createInstance");
-        Assert.assertNotNull(vnfRecipe);
-        Assert.assertNotNull(vnfRecipe.getNfRole());
-        Assert.assertNotNull(vnfRecipe.getAction());
-        Assert.assertEquals("Gr api recipe to create vnf", vnfRecipe.getDescription());
-        Assert.assertEquals("/mso/async/services/WorkflowActionBB", vnfRecipe.getOrchestrationUri());
+        assertNotNull(vnfRecipe);
+        assertNotNull(vnfRecipe.getNfRole());
+        assertNotNull(vnfRecipe.getAction());
+        assertEquals("Gr api recipe to create vnf", vnfRecipe.getDescription());
+        assertEquals("/mso/async/services/WorkflowActionBB", vnfRecipe.getOrchestrationUri());
     }
 
     @Test
     public void testGetFirstVnfRecipeByNfRoleAndActionNotFound() {
         VnfRecipe vnfRecipe = client.getFirstVnfRecipeByNfRoleAndAction(UUID.randomUUID().toString(), "createInstance");
-        Assert.assertNull(vnfRecipe);
+        assertNull(vnfRecipe);
     }
 
     @Test
@@ -339,12 +336,12 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         VnfComponentsRecipe vnfComponentsRecipe =
                 client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
                         "20c4431c-246d-11e7-93ae-92361f002671", "volumeGroup", "createInstance");
-        Assert.assertNotNull(vnfComponentsRecipe);
-        Assert.assertNotNull(vnfComponentsRecipe.getAction());
-        Assert.assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID());
-        Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType());
-        Assert.assertEquals("Gr api recipe to create volume-group", vnfComponentsRecipe.getDescription());
-        Assert.assertEquals("/mso/async/services/WorkflowActionBB", vnfComponentsRecipe.getOrchestrationUri());
+        assertNotNull(vnfComponentsRecipe);
+        assertNotNull(vnfComponentsRecipe.getAction());
+        assertNotNull(vnfComponentsRecipe.getVfModuleModelUUID());
+        assertNotNull(vnfComponentsRecipe.getVnfComponentType());
+        assertEquals("Gr api recipe to create volume-group", vnfComponentsRecipe.getDescription());
+        assertEquals("/mso/async/services/WorkflowActionBB", vnfComponentsRecipe.getOrchestrationUri());
 
     }
 
@@ -354,80 +351,79 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         VnfComponentsRecipe vnfComponentsRecipe =
                 client.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
                         UUID.randomUUID().toString(), "volumeGroup", "createInstance");
-        Assert.assertNull(vnfComponentsRecipe);
+        assertNull(vnfComponentsRecipe);
     }
 
     @Test
     public void testGetFirstVnfComponentsRecipeByVnfComponentTypeAndAction() {
         VnfComponentsRecipe vnfComponentsRecipe =
                 client.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction("volumeGroup", "createInstance");
-        Assert.assertNotNull(vnfComponentsRecipe);
-        Assert.assertNotNull(vnfComponentsRecipe.getAction());
-        Assert.assertNotNull(vnfComponentsRecipe.getVnfComponentType());
-        Assert.assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription());
-        Assert.assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1",
-                vnfComponentsRecipe.getOrchestrationUri());
+        assertNotNull(vnfComponentsRecipe);
+        assertNotNull(vnfComponentsRecipe.getAction());
+        assertNotNull(vnfComponentsRecipe.getVnfComponentType());
+        assertEquals("VID_DEFAULT recipe t", vnfComponentsRecipe.getDescription());
+        assertEquals("/mso/async/services/CreateVfModuleVolumeInfraV1", vnfComponentsRecipe.getOrchestrationUri());
     }
 
     @Test
     public void testGetServiceByModelVersionAndModelInvariantUUID() {
         Service service =
                 client.getServiceByModelVersionAndModelInvariantUUID("2.0", "9647dfc4-2083-11e7-93ae-92361f002671");
-        Assert.assertNotNull(service);
-        Assert.assertNotNull(service.getModelVersion());
-        Assert.assertNotNull(service.getModelInvariantUUID());
-        Assert.assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName());
-        Assert.assertEquals("NA", service.getServiceRole());
+        assertNotNull(service);
+        assertNotNull(service.getModelVersion());
+        assertNotNull(service.getModelInvariantUUID());
+        assertEquals("MSOTADevInfra_vSAMP10a_Service", service.getModelName());
+        assertEquals("NA", service.getServiceRole());
     }
 
     @Test
     public void testGetServiceByModelVersionAndModelInvariantUUIDNotFound() {
         Service service = client.getServiceByModelVersionAndModelInvariantUUID("2.0", UUID.randomUUID().toString());
-        Assert.assertNull(service);
+        assertNull(service);
     }
 
     @Test
     public void testGetVfModuleByModelInvariantUUIDAndModelVersion() {
         VfModule vfModule =
                 client.getVfModuleByModelInvariantUUIDAndModelVersion("78ca26d0-246d-11e7-93ae-92361f002671", "2");
-        Assert.assertNotNull(vfModule);
-        Assert.assertNotNull(vfModule.getModelVersion());
-        Assert.assertNotNull(vfModule.getModelInvariantUUID());
-        Assert.assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName());
-        Assert.assertEquals("vSAMP10a DEV Base", vfModule.getDescription());
+        assertNotNull(vfModule);
+        assertNotNull(vfModule.getModelVersion());
+        assertNotNull(vfModule.getModelInvariantUUID());
+        assertEquals("vSAMP10aDEV::base::module-0", vfModule.getModelName());
+        assertEquals("vSAMP10a DEV Base", vfModule.getDescription());
     }
 
     @Test
     public void testGetVfModuleByModelInvariantUUIDAndModelVersionNotFound() {
         VfModule vfModule = client.getVfModuleByModelInvariantUUIDAndModelVersion(UUID.randomUUID().toString(), "2");
-        Assert.assertNull(vfModule);
+        assertNull(vfModule);
     }
 
     @Test
     public void testGetServiceByModelInvariantUUIDOrderByModelVersionDesc() {
         List<Service> serviceList =
                 client.getServiceByModelInvariantUUIDOrderByModelVersionDesc("9647dfc4-2083-11e7-93ae-92361f002671");
-        Assert.assertFalse(serviceList.isEmpty());
-        Assert.assertEquals(2, serviceList.size());
+        assertFalse(serviceList.isEmpty());
+        assertEquals(2, serviceList.size());
         Service service = serviceList.get(0);
-        Assert.assertEquals("2.0", service.getModelVersion());
+        assertEquals("2.0", service.getModelVersion());
     }
 
     @Test
     public void testGetServiceByModelInvariantUUIDOrderByModelVersionDescNotFound() {
         List<Service> serviceList =
                 client.getServiceByModelInvariantUUIDOrderByModelVersionDesc(UUID.randomUUID().toString());
-        Assert.assertTrue(serviceList.isEmpty());
+        assertTrue(serviceList.isEmpty());
     }
 
     @Test
     public void testGetVfModuleByModelInvariantUUIDOrderByModelVersionDesc() {
         List<VfModule> moduleList =
                 client.getVfModuleByModelInvariantUUIDOrderByModelVersionDesc("78ca26d0-246d-11e7-93ae-92361f002671");
-        Assert.assertFalse(moduleList.isEmpty());
-        Assert.assertEquals(2, moduleList.size());
+        assertFalse(moduleList.isEmpty());
+        assertEquals(2, moduleList.size());
         VfModule module = moduleList.get(0);
-        Assert.assertEquals("vSAMP10a DEV Base", module.getDescription());
+        assertEquals("vSAMP10a DEV Base", module.getDescription());
     }
 
     @Test
@@ -453,20 +449,20 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         cloudSite.setIdentityService(cloudIdentity);
         localClient.postCloudSite(cloudSite);
         CloudSite getCloudSite = this.client.getCloudSite("MTN6");
-        Assert.assertNotNull(getCloudSite);
-        Assert.assertNotNull(getCloudSite.getIdentityService());
-        Assert.assertEquals("TESTCLLI", getCloudSite.getClli());
-        Assert.assertEquals("regionId", getCloudSite.getRegionId());
-        Assert.assertEquals("RANDOMID", getCloudSite.getIdentityServiceId());
+        assertNotNull(getCloudSite);
+        assertNotNull(getCloudSite.getIdentityService());
+        assertEquals("TESTCLLI", getCloudSite.getClli());
+        assertEquals("regionId", getCloudSite.getRegionId());
+        assertEquals("RANDOMID", getCloudSite.getIdentityServiceId());
     }
 
     @Test
     public void testGetHomingInstance() {
         HomingInstance homingInstance = client.getHomingInstance("5df8b6de-2083-11e7-93ae-92361f232671");
-        Assert.assertNotNull(homingInstance);
-        Assert.assertNotNull(homingInstance.getCloudOwner());
-        Assert.assertNotNull(homingInstance.getCloudRegionId());
-        Assert.assertNotNull(homingInstance.getOofDirectives());
+        assertNotNull(homingInstance);
+        assertNotNull(homingInstance.getCloudOwner());
+        assertNotNull(homingInstance.getCloudRegionId());
+        assertNotNull(homingInstance.getOofDirectives());
     }
 
     @Test
@@ -490,43 +486,43 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
                 + "\"id\": \"vsink\"\n" + "}\n" + "]\n" + "}");
         localClient.postHomingInstance(homingInstance);
         HomingInstance getHomingInstance = this.client.getHomingInstance("5df8d6be-2083-11e7-93ae-92361f232671");
-        Assert.assertNotNull(getHomingInstance);
-        Assert.assertNotNull(getHomingInstance.getCloudRegionId());
-        Assert.assertNotNull(getHomingInstance.getCloudOwner());
-        Assert.assertEquals("CloudOwner-1", getHomingInstance.getCloudOwner());
-        Assert.assertEquals("CloudRegionOne", getHomingInstance.getCloudRegionId());
+        assertNotNull(getHomingInstance);
+        assertNotNull(getHomingInstance.getCloudRegionId());
+        assertNotNull(getHomingInstance.getCloudOwner());
+        assertEquals("CloudOwner-1", getHomingInstance.getCloudOwner());
+        assertEquals("CloudRegionOne", getHomingInstance.getCloudRegionId());
     }
 
     @Test
     public void testGetServiceByModelName() {
         Service service = client.getServiceByModelName("MSOTADevInfra_Test_Service");
-        Assert.assertNotNull(service);
-        Assert.assertNotNull(service.getModelVersion());
-        Assert.assertNotNull(service.getModelInvariantUUID());
-        Assert.assertEquals("MSOTADevInfra_Test_Service", service.getModelName());
-        Assert.assertEquals("NA", service.getServiceRole());
+        assertNotNull(service);
+        assertNotNull(service.getModelVersion());
+        assertNotNull(service.getModelInvariantUUID());
+        assertEquals("MSOTADevInfra_Test_Service", service.getModelName());
+        assertEquals("NA", service.getServiceRole());
     }
 
     @Test
     public void testGetServiceByModelNameNotFound() {
         Service service = client.getServiceByModelName("Not_Found");
-        Assert.assertNull(service);
+        assertNull(service);
     }
 
     @Test
     public void testGetServiceByModelUUID() {
         Service service = client.getServiceByModelUUID("5df8b6de-2083-11e7-93ae-92361f002679");
-        Assert.assertNotNull(service);
-        Assert.assertNotNull(service.getModelVersion());
-        Assert.assertNotNull(service.getModelInvariantUUID());
-        Assert.assertEquals("5df8b6de-2083-11e7-93ae-92361f002679", service.getModelUUID());
-        Assert.assertEquals("NA", service.getServiceRole());
+        assertNotNull(service);
+        assertNotNull(service.getModelVersion());
+        assertNotNull(service.getModelInvariantUUID());
+        assertEquals("5df8b6de-2083-11e7-93ae-92361f002679", service.getModelUUID());
+        assertEquals("NA", service.getServiceRole());
     }
 
     @Test
     public void testGetServiceByModelUUIDNotFound() {
         Service service = client.getServiceByModelUUID("Not_Found");
-        Assert.assertNull(service);
+        assertNull(service);
     }
 
     @Test
@@ -538,53 +534,52 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         northBoundRequest.setCloudOwner("my-custom-cloud-owner");
         client.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner("createService", "service", true,
                 "my-custom-cloud-owner");
-        Assert.assertNotNull(northBoundRequest);
-        Assert.assertEquals("createService", northBoundRequest.getAction());
-        Assert.assertEquals("service", northBoundRequest.getRequestScope());
-        Assert.assertEquals(true, northBoundRequest.getIsAlacarte());
-        Assert.assertEquals("my-custom-cloud-owner", northBoundRequest.getCloudOwner());
+        assertNotNull(northBoundRequest);
+        assertEquals("createService", northBoundRequest.getAction());
+        assertEquals("service", northBoundRequest.getRequestScope());
+        assertEquals(true, northBoundRequest.getIsAlacarte());
+        assertEquals("my-custom-cloud-owner", northBoundRequest.getCloudOwner());
     }
 
     @Test
     public void testFindServiceRecipeByActionAndServiceModelUUID() {
         ServiceRecipe serviceRecipe = client.findServiceRecipeByActionAndServiceModelUUID("createInstance",
                 "4694a55f-58b3-4f17-92a5-796d6f5ffd0d");
-        Assert.assertNotNull(serviceRecipe);
-        Assert.assertNotNull(serviceRecipe.getServiceModelUUID());
-        Assert.assertNotNull(serviceRecipe.getAction());
-        Assert.assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance",
-                serviceRecipe.getOrchestrationUri());
-        Assert.assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription());
+        assertNotNull(serviceRecipe);
+        assertNotNull(serviceRecipe.getServiceModelUUID());
+        assertNotNull(serviceRecipe.getAction());
+        assertEquals("/mso/async/services/CreateGenericALaCarteServiceInstance", serviceRecipe.getOrchestrationUri());
+        assertEquals("MSOTADevInfra aLaCarte", serviceRecipe.getDescription());
     }
 
     @Test
     public void testFindServiceRecipeByActionAndServiceModelUUIDNotFound() {
         ServiceRecipe serviceRecipe =
                 client.findServiceRecipeByActionAndServiceModelUUID("not_found", "5df8b6de-2083-11e7-93ae-test");
-        Assert.assertNull(serviceRecipe);
+        assertNull(serviceRecipe);
     }
 
     @Test
     public void testFindExternalToInternalServiceByServiceName() {
         ExternalServiceToInternalService externalServiceToInternalService =
                 client.findExternalToInternalServiceByServiceName("MySpecialServiceName");
-        Assert.assertNotNull(externalServiceToInternalService);
-        Assert.assertNotNull(externalServiceToInternalService.getServiceName());
-        Assert.assertNotNull(externalServiceToInternalService.getServiceModelUUID());
-        Assert.assertEquals("MySpecialServiceName", externalServiceToInternalService.getServiceName());
+        assertNotNull(externalServiceToInternalService);
+        assertNotNull(externalServiceToInternalService.getServiceName());
+        assertNotNull(externalServiceToInternalService.getServiceModelUUID());
+        assertEquals("MySpecialServiceName", externalServiceToInternalService.getServiceName());
     }
 
     @Test
     public void testFindExternalToInternalServiceByServiceNameNotFound() {
         ExternalServiceToInternalService externalServiceToInternalService =
                 client.findExternalToInternalServiceByServiceName("Not_Found");
-        Assert.assertNull(externalServiceToInternalService);
+        assertNull(externalServiceToInternalService);
     }
 
     @Test
     public void getPnfResourceByModelUUID_validUuid_expectedOutput() {
         PnfResource pnfResource = client.getPnfResourceByModelUUID("ff2ae348-214a-11e7-93ae-92361f002680");
-        Assert.assertNotNull(pnfResource);
+        assertNotNull(pnfResource);
         assertEquals("PNFResource modelUUID", "ff2ae348-214a-11e7-93ae-92361f002680", pnfResource.getModelUUID());
         assertEquals("PNFResource modelInvariantUUID", "2fff5b20-214b-11e7-93ae-92361f002680",
                 pnfResource.getModelInvariantUUID());
@@ -595,7 +590,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     @Test
     public void getPnfResourceByModelUUID_invalidUuid_NullOutput() {
         PnfResource pnfResource = client.getPnfResourceByModelUUID(UUID.randomUUID().toString());
-        Assert.assertNull(pnfResource);
+        assertNull(pnfResource);
     }
 
     @Test
@@ -619,7 +614,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     public void getPnfResourceCustomizationByModelCustomizationUUID_invalidUuid_nullOutput() {
         PnfResourceCustomization pnfResourceCustomization =
                 client.getPnfResourceCustomizationByModelCustomizationUUID(UUID.randomUUID().toString());
-        Assert.assertNull(pnfResourceCustomization);
+        assertNull(pnfResourceCustomization);
     }
 
     @Test
@@ -649,6 +644,53 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
         assertEquals(0, pnfResourceCustomizationList.size());
     }
 
+    @Test
+    public void testGetServiceTopologyById() throws Exception {
+        org.onap.so.rest.catalog.beans.Service serviceByID =
+                client.getServiceModelInformation("5df8b6de-2083-11e7-93ae-92361f002671", "2");
+        assertNotNull(serviceByID);
+        assertEquals("MSOTADevInfra_vSAMP10a_Service", serviceByID.getModelName());
+        assertEquals("NA", serviceByID.getServiceType());
+        assertEquals("NA", serviceByID.getServiceRole());
+    }
+
+    @Test
+    public void testGetServices() throws Exception {
+        List<org.onap.so.rest.catalog.beans.Service> services = client.getServices();
+        assertEquals(false, services.isEmpty());
+    }
+
+    @Test
+    public void testVnf() throws Exception {
+        org.onap.so.rest.catalog.beans.Vnf vnf = client.getVnfModelInformation("5df8b6de-2083-11e7-93ae-92361f002671",
+                "68dc9a92-214c-11e7-93ae-92361f002671", "0");
+        assertNotNull(vnf);
+        assertEquals("vSAMP10a", vnf.getModelName());
+        assertEquals(false, vnf.getNfDataValid());
+        assertEquals("vSAMP", vnf.getNfFunction());
+        assertEquals("vSAMP", vnf.getNfNamingCode());
+        assertEquals("vSAMP", vnf.getNfRole());
+        assertEquals("vSAMP", vnf.getNfType());
+
+        vnf.setNfDataValid(true);
+        vnf.setNfFunction("nfFunction");
+        vnf.setNfRole("nfRole");
+        vnf.setNfType("nfType");
+        vnf.setNfNamingCode("nfNamingCode");
+
+        client.updateVnf("5df8b6de-2083-11e7-93ae-92361f002671", vnf);
+        vnf = client.getVnfModelInformation("5df8b6de-2083-11e7-93ae-92361f002671",
+                "68dc9a92-214c-11e7-93ae-92361f002671", "0");
+        assertEquals("vSAMP10a", vnf.getModelName());
+        assertEquals(true, vnf.getNfDataValid());
+        assertEquals("nfFunction", vnf.getNfFunction());
+        assertEquals("nfNamingCode", vnf.getNfNamingCode());
+        assertEquals("nfRole", vnf.getNfRole());
+        assertEquals("nfType", vnf.getNfType());
+
+
+    }
+
     @Test
     public void getWorkflowByArtifactUUID_validUuid_expectedOutput() {
         Workflow workflow = client.findWorkflowByArtifactUUID("5b0c4322-643d-4c9f-b184-4516049e99b1");
@@ -658,7 +700,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     @Test
     public void getWorkflowByArtifactUUID_invalidUuid_nullOutput() {
         Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString());
-        Assert.assertNull(workflow);
+        assertNull(workflow);
     }
 
     @Test
@@ -673,7 +715,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     @Test
     public void getWorkflowByModelUUID_invalidUuid_nullOutput() {
         Workflow workflow = client.findWorkflowByArtifactUUID(UUID.randomUUID().toString());
-        Assert.assertNull(workflow);
+        assertNull(workflow);
     }
 
     @Test
@@ -688,7 +730,7 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest {
     @Test
     public void getWorkflowBySource_invalidSource_nullOutput() {
         List<Workflow> workflow = client.findWorkflowBySource("abc");
-        Assert.assertNull(workflow);
+        assertNull(workflow);
     }
 
 }
index cc5145f..2dc83c8 100644 (file)
@@ -23,6 +23,7 @@
       "toscaNodeType": "toscaNodeType",
       "nfFunction": "nfFunction",
       "nfRole": "nfRole",
+      "nfType": "nfType",
       "nfNamingCode": "nfNamingCode",
       "multiStageDesign": "multiStageDesign",
       "orchestrationMode": "orchestrationMode",
index 58b2983..32c5129 100644 (file)
@@ -184,8 +184,8 @@ VALUES      ( '9bcce658-9b37-11e8-98d0-529269fb1459',
               'testVnfcCustomizationDescription',
               '2018-07-17 14:05:08');
 
-INSERT INTO `rainy_day_handler_macro` (`FLOW_NAME`,`SERVICE_TYPE`,`VNF_TYPE`,`ERROR_CODE`,`WORK_STEP`,`POLICY`,`SECONDARY_POLICY`,`REG_EX_ERROR_MESSAGE`) 
-VALUES ('AssignServiceInstanceBB','*','*','*','*','Rollback','Rollback','The Flavor ID.*could not be found.');
+INSERT INTO `rainy_day_handler_macro` (`FLOW_NAME`,`SERVICE_TYPE`,`VNF_TYPE`,`ERROR_CODE`,`WORK_STEP`,`POLICY`,`SECONDARY_POLICY`,`REG_EX_ERROR_MESSAGE`, `SERVICE_ROLE`
+VALUES ('AssignServiceInstanceBB','*','*','*','*','Rollback','Rollback','The Flavor ID.*could not be found.','*');
 
 INSERT INTO `cvnfc_customization`
             (`id`,
index 999d273..6a42456 100644 (file)
@@ -40,6 +40,10 @@ public class AuditStackService {
 
     private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class);
 
+    private static final String DEFAULT_AUDIT_LOCK_TIME = "60000";
+
+    private static final String DEFAULT_MAX_CLIENTS_FOR_TOPIC = "10";
+
     @Autowired
     public Environment env;
 
@@ -53,41 +57,40 @@ public class AuditStackService {
     private AuditQueryStackService auditQueryStack;
 
     @PostConstruct
-    public void auditAddAAIInventory() throws Exception {
+    public void auditAddAAIInventory() {
         for (int i = 0; i < getMaxClients(); i++) {
             ExternalTaskClient client = createExternalTaskClient();
             client.subscribe("InventoryAddAudit")
-                    .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000")))
+                    .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", DEFAULT_AUDIT_LOCK_TIME)))
                     .handler(auditCreateStack::executeExternalTask).open();
         }
     }
 
     @PostConstruct
-    public void auditDeleteAAIInventory() throws Exception {
+    public void auditDeleteAAIInventory() {
         for (int i = 0; i < getMaxClients(); i++) {
             ExternalTaskClient client = createExternalTaskClient();
             client.subscribe("InventoryDeleteAudit")
-                    .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000")))
+                    .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", DEFAULT_AUDIT_LOCK_TIME)))
                     .handler(auditDeleteStack::executeExternalTask).open();
         }
     }
 
     @PostConstruct
-    public void auditQueryInventory() throws Exception {
+    public void auditQueryInventory() {
         for (int i = 0; i < getMaxClients(); i++) {
             ExternalTaskClient client = createExternalTaskClient();
             client.subscribe("InventoryQueryAudit")
-                    .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000")))
+                    .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", DEFAULT_AUDIT_LOCK_TIME)))
                     .handler(auditQueryStack::executeExternalTask).open();
         }
     }
 
-    protected ExternalTaskClient createExternalTaskClient() throws Exception {
+    protected ExternalTaskClient createExternalTaskClient() {
         ClientRequestInterceptor interceptor = createClientRequestInterceptor();
-        ExternalTaskClient client = ExternalTaskClient.create()
-                .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor)
-                .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
-        return client;
+        return ExternalTaskClient.create().baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1)
+                .addInterceptor(interceptor).asyncResponseTimeout(120000)
+                .backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build();
     }
 
     protected ClientRequestInterceptor createClientRequestInterceptor() {
@@ -97,13 +100,11 @@ public class AuditStackService {
         } catch (IllegalStateException | GeneralSecurityException e) {
             logger.error("Error Decrypting Password", e);
         }
-        ClientRequestInterceptor interceptor =
-                new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth);
-        return interceptor;
+        return new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth);
     }
 
     protected int getMaxClients() {
-        return Integer.parseInt(env.getProperty("workflow.topics.maxClients", "10"));
+        return Integer.parseInt(env.getProperty("workflow.topics.maxClients", DEFAULT_MAX_CLIENTS_FOR_TOPIC));
     }
 
 
index 4c11527..153de2f 100644 (file)
@@ -842,8 +842,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
         } else {
             String error = String.format(
                     "Network Type:%s Version_Min:%s Version_Max:%s not supported on Cloud:%s with AIC_Version:%s",
-                    networkType, networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(),
-                    cloudSiteId, cloudSite.getCloudVersion());
+                    networkType, networkResource.getAicVersionMin(), networkResource.getAicVersionMax(), cloudSiteId,
+                    cloudSite.getCloudVersion());
             logger.error(LoggingAnchor.THREE, MessageEnum.RA_CONFIG_EXC, ErrorCode.DataError.getValue(), error);
             throw new NetworkException(error, MsoExceptionCategory.USERDATA);
         }
@@ -1477,13 +1477,19 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
             }
 
             if (subnet.getAllocationPools() != null) {
-                curR = curR + "      allocation_pools:\n";
+                StringBuilder tempBuf = new StringBuilder();
+                tempBuf.append(curR);
+                tempBuf.append("      allocation_pools:\n");
                 for (Pool pool : subnet.getAllocationPools()) {
                     if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) {
-                        curR = curR + "       - start: " + pool.getStart() + "\n";
-                        curR = curR + "         end: " + pool.getEnd() + "\n";
+                        tempBuf.append("       - start: ");
+                        tempBuf.append(pool.getStart());
+                        tempBuf.append("\n         end: ");
+                        tempBuf.append(pool.getEnd());
+                        tempBuf.append("\n");
                     }
                 }
+                curR = tempBuf.toString();
             }
 
             resourcesBuf.append(curR);
@@ -1492,7 +1498,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
             curO = curO.replace("%subnetId%", subnet.getSubnetId());
 
             outputsBuf.append(curO);
-
         }
         // append resources and outputs in heatTemplate
         logger.debug("Tempate initial:{}", heatTemplate);
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java
deleted file mode 100644 (file)
index 7786b87..0000000
+++ /dev/null
@@ -1,189 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.so.adapters.vnf;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-import org.onap.so.adapters.vdu.VduArtifact;
-import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
-import org.onap.so.adapters.vdu.VduModelInfo;
-import org.onap.so.adapters.vnf.exceptions.VnfException;
-import com.google.common.io.Files;
-
-/**
- * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA
- * orchestrator.
- * 
- * @author DeWayne
- *
- */
-public class CSAR {
-    private static final String MANIFEST_FILENAME = "MANIFEST.MF";
-    private VduModelInfo vduModel;
-
-    public CSAR(VduModelInfo model) {
-        this.vduModel = model;
-    }
-
-    /**
-     * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor.
-     * 
-     * @return
-     * @throws VnfException
-     */
-    public byte[] create() {
-        File dir = Files.createTempDir();
-
-        /**
-         * Create subdir
-         */
-        File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata");
-        if (!metadir.mkdir()) {
-            throw new RuntimeException("CSAR TOSCA-Metadata directory create failed");
-        }
-
-        /**
-         * Organize model info for consumption
-         */
-        VduArtifact mainTemplate = null;
-        List<VduArtifact> extraFiles = new ArrayList<>();
-        for (VduArtifact artifact : vduModel.getArtifacts()) {
-            if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) {
-                mainTemplate = artifact;
-            } else {
-                extraFiles.add(artifact);
-            }
-        }
-
-        if (mainTemplate == null) { // make a dummy to avoid null pointers
-            mainTemplate = new VduArtifact("", new byte[0], null);
-        }
-
-        /**
-         * Write template files
-         */
-        try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName()));
-                PrintStream mfstream =
-                        new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) {
-            ofs.write(mainTemplate.getContent());
-
-            /**
-             * Write other files
-             */
-            if (!extraFiles.isEmpty()) {
-                for (VduArtifact artifact : extraFiles) {
-                    try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) {
-                        out.write(artifact.getContent());
-                    }
-                }
-            }
-
-
-            /**
-             * Create manifest
-             */
-            mfstream.println("TOSCA-Meta-File-Version: 1.0");
-            mfstream.println("CSAR-Version: 1.1");
-            mfstream.println("Created-by: ONAP");
-            mfstream.println("Entry-Definitions: " + mainTemplate.getName());
-
-            /**
-             * ZIP it up
-             */
-            ByteArrayOutputStream zipbytes = new ByteArrayOutputStream();
-            ZipOutputStream zos = new ZipOutputStream(zipbytes);
-            compressTree(zos, "", dir, dir);
-            zos.close();
-            return zipbytes.toByteArray();
-
-        } catch (Exception e) {
-            throw new RuntimeException("Failed to create CSAR: " + e.getMessage());
-        } finally {
-            /**
-             * Clean up tmpdir
-             */
-            deleteDirectory(dir);
-        }
-    }
-
-    /**
-     * Private methods
-     */
-
-    /**
-     * Compresses (ZIPs) a directory tree
-     * 
-     * @param dir
-     * @throws IOException
-     */
-    private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException {
-        if (!dir.isDirectory())
-            return;
-
-        for (File f : dir.listFiles()) {
-            if (f.isDirectory()) {
-                String newpath = path + f.getName() + '/';
-                ZipEntry entry = new ZipEntry(newpath);
-                zos.putNextEntry(entry);
-                zos.closeEntry();
-                compressTree(zos, newpath, basedir, f);
-            } else {
-                ZipEntry ze = new ZipEntry(
-                        f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/"));
-                zos.putNextEntry(ze);
-                // read the file and write to ZipOutputStream
-                try (FileInputStream fis = new FileInputStream(f);) {
-                    byte[] buffer = new byte[1024];
-                    int len;
-                    while ((len = fis.read(buffer)) > 0) {
-                        zos.write(buffer, 0, len);
-                    }
-                }
-                zos.closeEntry();
-            }
-        }
-    }
-
-    private boolean deleteDirectory(File directory) {
-        if (directory.exists()) {
-            File[] files = directory.listFiles();
-            if (null != files) {
-                for (int i = 0; i < files.length; i++) {
-                    if (files[i].isDirectory()) {
-                        deleteDirectory(files[i]);
-                    } else {
-                        files[i].delete();
-                    }
-                }
-            }
-        }
-        return (directory.delete());
-    }
-}
index 7b3ffd7..9406bc4 100644 (file)
@@ -1109,6 +1109,7 @@ CREATE TABLE `vnf_resource_customization` (
   `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL,
   `SERVICE_MODEL_UUID` varchar(200) NOT NULL,
+  `NF_DATA_VALID` tinyint(1) DEFAULT '0',
   `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL,
   PRIMARY KEY (`ID`),
   UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`),
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt
new file mode 100644 (file)
index 0000000..6687631
--- /dev/null
@@ -0,0 +1,128 @@
+The following describes how to configure authentication for the VNFM adapter.\r
+\r
+\r
+==========================================\r
+To confgure TLS\r
+==========================================\r
+\r
+---------------\r
+VNFM Adapter\r
+---------------\r
+The following parameters can be set to configure the certificate for the VNFM adapter\r
+server:\r
+  ssl:\r
+    key-alias: so@so.onap.org\r
+    key--store-password: 'I,re7WWEJR$e]x370wRgx?qE'\r
+    key-store: classpath:org.onap.so.p12\r
+    key-store-type: PKCS12\r
+The values shown above relate to the certificate included in the VNFM adapter jar which has been generated from AAF. If a different certificate is to be used then these values should be changed accordingly.\r
+\r
+The following paramters can be set to configure the trust store for the VNFM adapter:\r
+http:\r
+  client:\r
+    ssl:\r
+      trust-store: org.onap.so.trust.jks\r
+      trust-store-password: NyRD](z:EJJNIt?},QgM3o7H\r
+The values shown above relate to the trust store included in the VNFM adapter jar which has been generated from AAI. If a different trust store is to be used then these values should be changed accordingly.\r
+\r
+Ensure the value for the below parameter uses https instead of http\r
+vnfmadapter:\r
+  endpoint: http://so-vnfm-adapter.onap:9092\r
+  \r
+---------------\r
+bpmn-infra\r
+---------------\r
+For bpmn-infra, ensure the value for the below parameter uses https instead of http\r
+so:\r
+  vnfm:\r
+    adapter:\r
+      url: https://so-vnfm-adapter.onap:9092/so/vnfm-adapter/v1/\r
+\r
+\r
+==========================================\r
+To use two way TLS\r
+==========================================\r
+\r
+Ensure the value for username and password are empty in the AAI entry for the VNFM (The VNFM adapter will use oauth instead of two way TLS if the username/password is set).\r
+Ensure TLS has been configuered as detailed above.\r
+\r
+---------------\r
+VNFM adapter\r
+---------------\r
+Set the following parameter for the VNFM adapter:\r
+server:\r
+  ssl:\r
+    client-auth: need\r
+       \r
+---------------\r
+bpmn-infra:\r
+---------------\r
+Set the following paramters for bpmn-infra:\r
+rest:\r
+  http:\r
+    client:\r
+      configuration:\r
+        ssl:\r
+          keyStore: classpath:org.onap.so.p12\r
+          keyStorePassword: 'RLe5ExMWW;Kd6GTSt0WQz;.Y'\r
+          trustStore: classpath:org.onap.so.trust.jks\r
+          trustStorePassword: '6V%8oSU$,%WbYp3IUe;^mWt4'\r
+Ensure the value for the below parameter uses https instead of http\r
+so:\r
+  vnfm:\r
+    adapter:\r
+      url: https://so-vnfm-adapter.onap:9092/so/vnfm-adapter/v1/\r
+         \r
+---------------          \r
+VNFM simulator:\r
+---------------\r
+Set the following parameters for the VNFM simulator (if used):\r
+server:\r
+  ssl:\r
+    client-auth: need\r
+  request:\r
+    grant:\r
+      auth: twowaytls\r
+\r
+==========================================\r
+To use oauth token base authentication\r
+==========================================\r
+\r
+---------------          \r
+VNFM adapter:\r
+---------------\r
+Ensure the value for username and password set set in the AAI entry for the VNFM. The VNFM adapter will use this username/password as the client credentials in the request for a token for the VNFM. The token endpoint\r
+for the VNFM will by default will be derived from the service url for the VNFM in AAI as follows: <base of service url>/oauth/token, e.g. if the service url is https://so-vnfm-simulator.onap/vnflcm/v1 then the token url will\r
+be taken to be https://so-vnfm-simulator.onap/oauth/token. This can be overriden using the following parameter for the VNFM adapter:\r
+vnfmadapter:\r
+  temp:\r
+    vnfm:\r
+         oauth:\r
+           endpoint:\r
+               \r
+The VNFM adapter exposes a token point at url: https://<hostname>:<port>/oauth/token e.g. https://so-vnfm-adapter.onap:9092/oauth/token. The VNFM can request a token from this endpoint for use in grant requests and notifications\r
+to the VNFM adapter. The username/password to be used in the token request are passed to the VNFM in a subscription request. The username/password sent by the VNFM adpater in the subscription request can be configuered using the \r
+following parameter:\r
+vnfmadapter:\r
+  auth: <encoded value>\r
+where <encoded value> is '<username>:<password>' encoded using org.onap.so.utils.CryptoUtils with the key set by the paramter:\r
+mso:\r
+  key: <key>\r
+The default username:password is vnfm-adapter:123456 when vnfm-adapter.auth is not set.\r
+                 \r
+---------------          \r
+VNFM simulator:\r
+---------------\r
+Set the following parameters for the simulator:\r
+spring:\r
+  profiles:\r
+    active: oauth-authentication\r
+server:\r
+  request:\r
+    grant:\r
+      auth: oauth\r
+               \r
+==========================================\r
+To use basic auth for notifications\r
+==========================================             \r
+The same username/password is used as for oauth token requests as describe above and passed to the VNFM in the subscription request.
\ No newline at end of file
index 2b33e8b..7920023 100644 (file)
@@ -22,6 +22,7 @@ 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.security.config.annotation.web.builders.HttpSecurity;
 import org.springframework.security.config.annotation.web.builders.WebSecurity;
 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@@ -34,11 +35,18 @@ import org.springframework.util.StringUtils;
 @EnableWebSecurity
 public class WebSecurityConfigImpl extends WebSecurityConfig {
 
+    @Value("${server.ssl.client-auth:none}")
+    private String clientAuth;
+
     @Override
     protected void configure(final HttpSecurity http) throws Exception {
-        http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
-                .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",")).and()
-                .httpBasic();
+        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
index b4355ef..7c22020 100644 (file)
@@ -212,6 +212,8 @@ public class VnfmHelper {
         basicAuthParams.setPassword(decrypedAuth[1]);
         authentication.addAuthTypeItem(AuthTypeEnum.BASIC);
         authentication.paramsBasic(basicAuthParams);
+
+        authentication.addAuthTypeItem(AuthTypeEnum.TLS_CERT);
         return authentication;
     }
 
index a604f9a..93312cf 100644 (file)
@@ -24,11 +24,12 @@ 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;
 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;
 import java.util.concurrent.ConcurrentHashMap;
@@ -42,7 +43,6 @@ import org.onap.aai.domain.yang.EsrSystemInfo;
 import org.onap.aai.domain.yang.EsrVnfm;
 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON;
 import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
-import org.onap.so.logging.jaxrs.filter.SpringClientFilter;
 import org.onap.so.rest.service.HttpRestServiceProvider;
 import org.onap.so.rest.service.HttpRestServiceProviderImpl;
 import org.slf4j.Logger;
@@ -52,7 +52,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.core.io.Resource;
-import org.springframework.http.client.ClientHttpRequestInterceptor;
+import org.springframework.http.client.BufferingClientHttpRequestFactory;
 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.http.converter.HttpMessageConverter;
 import org.springframework.http.converter.json.GsonHttpMessageConverter;
@@ -73,7 +73,12 @@ public class VnfmServiceProviderConfiguration {
     @Value("${http.client.ssl.trust-store:#{null}}")
     private Resource trustStore;
     @Value("${http.client.ssl.trust-store-password:#{null}}")
-    private String trustPassword;
+    private String trustStorePassword;
+
+    @Value("${server.ssl.key-store:#{null}}")
+    private Resource keyStoreResource;
+    @Value("${server.ssl.key--store-password:#{null}}")
+    private String keyStorePassword;
 
     /**
      * This property is only intended to be temporary until the AAI schema is updated to support setting the endpoint
@@ -98,7 +103,6 @@ public class VnfmServiceProviderConfiguration {
         if (trustStore != null) {
             setTrustStore(restTemplate);
         }
-        removeSpringClientFilter(restTemplate);
         return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider());
     }
 
@@ -141,27 +145,26 @@ public class VnfmServiceProviderConfiguration {
     private void setTrustStore(final RestTemplate restTemplate) {
         SSLContext sslContext;
         try {
-            sslContext =
-                    new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustPassword.toCharArray()).build();
+            if (keyStoreResource != null) {
+                KeyStore keystore = KeyStore.getInstance("pkcs12");
+                keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray());
+                sslContext =
+                        new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
+                                .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build();
+            } else {
+                sslContext = new SSLContextBuilder()
+                        .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
+            }
             logger.info("Setting truststore: {}", trustStore.getURL());
             final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
             final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
             final HttpComponentsClientHttpRequestFactory factory =
                     new HttpComponentsClientHttpRequestFactory(httpClient);
-            restTemplate.setRequestFactory(factory);
+            restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
         } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
-                | IOException exception) {
+                | IOException | UnrecoverableKeyException exception) {
             logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception);
         }
     }
 
-    private void removeSpringClientFilter(final RestTemplate restTemplate) {
-        ListIterator<ClientHttpRequestInterceptor> interceptorIterator = restTemplate.getInterceptors().listIterator();
-        while (interceptorIterator.hasNext()) {
-            if (interceptorIterator.next() instanceof SpringClientFilter) {
-                interceptorIterator.remove();
-            }
-        }
-    }
-
 }
index 6cdabb9..fe55907 100644 (file)
@@ -133,7 +133,7 @@ public class VnfmAdapterControllerTest {
         setUpVimInMockAai();
 
         final String expectedsubscriptionRequest =
-                "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"OAUTH2_CLIENT_CREDENTIALS\", \"BASIC\"],\"paramsOauth2ClientCredentials\":{\"clientId\":\"vnfm\",\"clientPassword\":\"password1$\",\"tokenEndpoint\":\"https://so-vnfm-adapter.onap:30406/oauth/token\"},\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"password1$\"}}}";
+                "{\"filter\":{\"vnfInstanceSubscriptionFilter\":{\"vnfInstanceIds\":[\"vnfId\"]},\"notificationTypes\":[\"VnfLcmOperationOccurrenceNotification\"]},\"callbackUri\":\"https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/lcn/VnfLcmOperationOccurrenceNotification\",\"authentication\":{\"authType\":[\"OAUTH2_CLIENT_CREDENTIALS\", \"BASIC\", \"TLS_CERT\"],\"paramsOauth2ClientCredentials\":{\"clientId\":\"vnfm\",\"clientPassword\":\"password1$\",\"tokenEndpoint\":\"https://so-vnfm-adapter.onap:30406/oauth/token\"},\"paramsBasic\":{\"userName\":\"vnfm\",\"password\":\"password1$\"}}}";
         final InlineResponse2001 subscriptionResponse = new InlineResponse2001();
 
         final InlineResponse201 createResponse = createCreateResponse();
index e048d4c..0fc94c8 100644 (file)
@@ -97,10 +97,8 @@ public class DeployActivitySpecs {
         }
         List<String> categoryList = new ArrayList<>();
         for (ActivitySpecActivitySpecCategories activitySpecCat : activitySpecActivitySpecCategories) {
-            if (activitySpecCat != null) {
-                if (activitySpecCat.getActivitySpecCategories() != null) {
-                    categoryList.add(activitySpecCat.getActivitySpecCategories().getName());
-                }
+            if (activitySpecCat != null && activitySpecCat.getActivitySpecCategories() != null) {
+                categoryList.add(activitySpecCat.getActivitySpecCategories().getName());
             }
         }
         activitySpec.setCategoryList(categoryList);
index 3b9406a..0734121 100644 (file)
@@ -37,6 +37,7 @@ import java.nio.file.Paths;
 import java.util.List;
 import java.util.Optional;
 import org.onap.so.logger.LoggingAnchor;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.onap.sdc.api.IDistributionClient;
 import org.onap.sdc.api.consumer.IDistributionStatusMessage;
 import org.onap.sdc.api.consumer.IFinalDistrStatusMessage;
@@ -71,6 +72,7 @@ import org.onap.so.logger.ErrorCode;
 import org.onap.so.logger.MessageEnum;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.orm.ObjectOptimisticLockingFailureException;
 import org.springframework.stereotype.Component;
@@ -588,6 +590,10 @@ public class ASDCController {
         logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_CALLBACK_NOTIF.toString(),
                 String.valueOf(noOfArtifacts), iNotif.getServiceUUID(), "ASDC");
         try {
+
+            if (iNotif.getDistributionID() != null && !iNotif.getDistributionID().isEmpty()) {
+                MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, iNotif.getDistributionID());
+            }
             logger.debug(ASDCNotificationLogging.dumpASDCNotification(iNotif));
             logger.info(LoggingAnchor.FOUR, MessageEnum.ASDC_RECEIVE_SERVICE_NOTIF.toString(), iNotif.getServiceUUID(),
                     "ASDC", "treatNotification");
index 8be3d6b..f2c6b2f 100644 (file)
@@ -61,7 +61,7 @@ public abstract class ResourceStructure {
     /**
      * Number of resources provided by the resource structure.
      */
-    protected int NumberOfResources;
+    protected int numberOfResources;
 
     /**
      * The list of artifacts existing in this resource hashed by UUID.
@@ -142,11 +142,11 @@ public abstract class ResourceStructure {
     }
 
     public int getNumberOfResources() {
-        return NumberOfResources;
+        return numberOfResources;
     }
 
     public void setNumberOfResources(int numberOfResources) {
-        NumberOfResources = numberOfResources;
+        this.numberOfResources = numberOfResources;
     }
 
     public Map<String, VfModuleArtifact> getArtifactsMapByUUID() {
index a68d98e..ef4dfa2 100644 (file)
@@ -52,7 +52,7 @@ import org.springframework.stereotype.Component;
 public class WorkflowResource {
     protected static final Logger logger = LoggerFactory.getLogger(WorkflowResource.class);
 
-    private static final String pattern = ".*\\\"activity:(.*)\\\" .*";
+    private static final String PATTERN = ".*\\\"activity:(.*)\\\" .*";
     private static final String TARGET_RESOURCE_VNF = "vnf";
     private static final String SOURCE_SDC = "sdc";
     private static final String BPMN_SUFFIX = ".bpmn";
@@ -176,7 +176,7 @@ public class WorkflowResource {
     protected List<String> getActivityNameList(String bpmnContent) {
         List<String> activityNameList = new ArrayList<>();
 
-        Pattern p = Pattern.compile(pattern);
+        Pattern p = Pattern.compile(PATTERN);
         Matcher m = p.matcher(bpmnContent);
         while (m.find()) {
             activityNameList.add(m.group(1));
index 276b818..3e6b442 100644 (file)
@@ -47,6 +47,7 @@ import org.onap.sdc.api.notification.IStatusData;
 import org.onap.sdc.tosca.parser.api.IEntityDetails;
 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
+import org.onap.sdc.tosca.parser.elements.queries.EntityQuery.EntityQueryBuilder;
 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery.TopologyTemplateQueryBuilder;
 import org.onap.sdc.tosca.parser.enums.SdcTypes;
@@ -1015,17 +1016,18 @@ public class ToscaResourceInstaller {
 
 
                 // Check for VNFC Instance Group info and add it if there is
-                List<Group> groupList =
-                        toscaResourceStruct.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(
-                                nodeTemplate, "org.openecomp.groups.VfcInstanceGroup");
+                List<IEntityDetails> vfcEntityList = getEntityDetails(toscaResourceStruct,
+                        "org.openecomp.groups.VfcInstanceGroup",
+                        TopologyTemplateQuery.newBuilder(SdcTypes.VF).customizationUUID(vfCustomizationUUID), false);
 
-                for (Group group : groupList) {
+
+                for (IEntityDetails groupEntity : vfcEntityList) {
                     VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization =
-                            createVNFCInstanceGroup(nodeTemplate, group, vnfResource, toscaResourceStruct);
+                            createVNFCInstanceGroup(groupEntity, nodeTemplate, vnfResource, toscaResourceStruct);
                     vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization);
                 }
 
-                List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, groupList);
+                List<String> seqResult = processVNFCGroupSequence(toscaResourceStruct, vfcEntityList);
                 if (!CollectionUtils.isEmpty(seqResult)) {
                     String resultStr = seqResult.stream().collect(Collectors.joining(","));
                     vnfResource.setVnfcInstanceGroupOrder(resultStr);
@@ -1043,82 +1045,90 @@ public class ToscaResourceInstaller {
     }
 
     private List<String> processVNFCGroupSequence(ToscaResourceStructure toscaResourceStructure,
-            List<Group> groupList) {
-        if (CollectionUtils.isEmpty(groupList)) {
+            List<IEntityDetails> groupEntityDetails) {
+        if (CollectionUtils.isEmpty(groupEntityDetails)) {
             return Collections.emptyList();
         }
 
         ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper();
-        List<String> strSequence = new ArrayList<>(groupList.size());
-        List<Group> tempGroupList = new ArrayList<>(groupList.size());
-        List<NodeTemplate> nodes = new ArrayList<>();
-        tempGroupList.addAll(groupList);
+        List<String> strSequence = new ArrayList<>(groupEntityDetails.size());
+        List<IEntityDetails> tempEntityList = new ArrayList<>(groupEntityDetails.size());
+        List<IEntityDetails> entities = new ArrayList<>();
+        tempEntityList.addAll(groupEntityDetails);
+
+        for (IEntityDetails vnfcEntityDetails : groupEntityDetails) {
+
+            List<IEntityDetails> vnfcMemberNodes = vnfcEntityDetails.getMemberNodes();
 
-        for (Group group : groupList) {
-            List<NodeTemplate> nodeList = group.getMemberNodes();
             boolean hasRequirements = false;
-            for (NodeTemplate node : nodeList) {
-                RequirementAssignments requirements = iSdcCsarHelper.getRequirementsOf(node);
-                if (requirements != null && requirements.getAll() != null && !requirements.getAll().isEmpty()) {
+            for (IEntityDetails vnfcDetails : vnfcMemberNodes) {
+
+                Map<String, RequirementAssignment> requirements = vnfcDetails.getRequirements();
+
+                if (requirements != null && !requirements.isEmpty()) {
                     hasRequirements = true;
                     break;
                 }
             }
 
             if (!hasRequirements) {
-                strSequence.add(group.getName());
-                tempGroupList.remove(group);
-                nodes.addAll(nodeList);
+                strSequence.add(vnfcEntityDetails.getName());
+                tempEntityList.remove(vnfcEntityDetails);
+                entities.addAll(vnfcMemberNodes);
             }
         }
 
-        getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper);
+        getVNFCGroupSequenceList(strSequence, tempEntityList, entities, iSdcCsarHelper);
 
         return strSequence;
 
     }
 
-    private void getVNFCGroupSequenceList(List<String> strSequence, List<Group> groupList, List<NodeTemplate> nodes,
-            ISdcCsarHelper iSdcCsarHelper) {
-        if (CollectionUtils.isEmpty(groupList)) {
+    private void getVNFCGroupSequenceList(List<String> strSequence, List<IEntityDetails> vnfcGroupDetails,
+            List<IEntityDetails> vnfcMemberNodes, ISdcCsarHelper iSdcCsarHelper) {
+        if (CollectionUtils.isEmpty(vnfcGroupDetails)) {
             return;
         }
 
-        List<Group> tempGroupList = new ArrayList<>();
-        tempGroupList.addAll(groupList);
+        List<IEntityDetails> tempGroupList = new ArrayList<>();
+        tempGroupList.addAll(vnfcGroupDetails);
 
-        for (Group group : groupList) {
-            boolean isAllExists = true;
-            ArrayList<NodeTemplate> members = group.getMemberNodes();
-            for (NodeTemplate memberNode : members) {
-                RequirementAssignments requirements = iSdcCsarHelper.getRequirementsOf(memberNode);
-                if (requirements == null || requirements.getAll() == null || requirements.getAll().isEmpty()) {
+        for (IEntityDetails vnfcGroup : vnfcGroupDetails) {
+            List<IEntityDetails> members = vnfcGroup.getMemberNodes();
+            for (IEntityDetails memberNode : members) {
+                boolean isAllExists = true;
+
+
+                Map<String, RequirementAssignment> requirements = memberNode.getRequirements();
+
+                if (requirements == null || requirements.isEmpty()) {
                     continue;
                 }
-                List<RequirementAssignment> rqaList = requirements.getAll();
-                for (RequirementAssignment rqa : rqaList) {
+
+
+                for (Map.Entry<String, RequirementAssignment> entry : requirements.entrySet()) {
+                    RequirementAssignment rqa = entry.getValue();
                     String name = rqa.getNodeTemplateName();
-                    Optional<NodeTemplate> findNode =
-                            nodes.stream().filter(node -> node.getName().equals(name)).findFirst();
-                    if (!findNode.isPresent()) {
-                        isAllExists = false;
-                        break;
+                    for (IEntityDetails node : vnfcMemberNodes) {
+                        if (name.equals(node.getName())) {
+                            break;
+                        }
                     }
-                }
-                if (!isAllExists) {
+
+                    isAllExists = false;
                     break;
                 }
-            }
 
-            if (isAllExists) {
-                strSequence.add(group.getName());
-                tempGroupList.remove(group);
-                nodes.addAll(group.getMemberNodes());
+                if (isAllExists) {
+                    strSequence.add(vnfcGroup.getName());
+                    tempGroupList.remove(vnfcGroupDetails);
+                    vnfcMemberNodes.addAll(vnfcGroupDetails);
+                }
             }
-        }
 
-        if (!tempGroupList.isEmpty() && tempGroupList.size() < groupList.size()) {
-            getVNFCGroupSequenceList(strSequence, tempGroupList, nodes, iSdcCsarHelper);
+            if (!tempGroupList.isEmpty() && tempGroupList.size() < vnfcGroupDetails.size()) {
+                getVNFCGroupSequenceList(strSequence, tempGroupList, vnfcMemberNodes, iSdcCsarHelper);
+            }
         }
     }
 
@@ -1822,10 +1832,11 @@ public class ToscaResourceInstaller {
         return collectionNetworkResourceCustomization;
     }
 
-    protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group,
-            VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) {
+    protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(IEntityDetails vfcInstanceEntity,
+            NodeTemplate vnfcNodeTemplate, VnfResourceCustomization vnfResourceCustomization,
+            ToscaResourceStructure toscaResourceStructure) {
 
-        Metadata instanceMetadata = group.getMetadata();
+        Metadata instanceMetadata = vfcInstanceEntity.getMetadata();
 
         InstanceGroup existingInstanceGroup =
                 instanceGroupRepo.findByModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
@@ -1839,7 +1850,7 @@ public class ToscaResourceInstaller {
                     .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
             vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
             vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
-            vfcInstanceGroup.setToscaNodeType(group.getType());
+            vfcInstanceGroup.setToscaNodeType(vfcInstanceEntity.getToscaType());
             vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role
             vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type
         } else {
@@ -1858,45 +1869,64 @@ public class ToscaResourceInstaller {
         vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION));
 
         String getInputName = null;
-        String groupProperty = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group,
-                "vfc_instance_group_function");
-        if (groupProperty != null) {
-            int getInputIndex = groupProperty.indexOf("{get_input=");
-            if (getInputIndex > -1) {
-                getInputName = groupProperty.substring(getInputIndex + 11, groupProperty.length() - 1);
+
+        Map<String, Property> groupProperties = vfcInstanceEntity.getProperties();
+
+        for (String key : groupProperties.keySet()) {
+            Property property = groupProperties.get(key);
+
+            String vfcName = property.getName();
+
+            if (vfcName != null) {
+                if (vfcName.equals("vfc_instance_group_function")) {
+
+                    String vfcValue = property.getValue().toString();
+                    int getInputIndex = vfcValue.indexOf("{get_input=");
+                    if (getInputIndex > -1) {
+                        getInputName = vfcValue.substring(getInputIndex + 11, vfcValue.length() - 1);
+                    }
+
+                }
             }
+
         }
-        vfcInstanceGroupCustom.setFunction(toscaResourceStructure.getSdcCsarHelper()
-                .getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName));
+
+        List<IEntityDetails> serviceEntityList =
+                getEntityDetails(toscaResourceStructure, EntityQuery.newBuilder(SdcTypes.VF).customizationUUID(
+                        vnfResourceCustomization.getModelCustomizationUUID()), SdcTypes.SERVICE, false);
+
+        if (serviceEntityList != null && !serviceEntityList.isEmpty()) {
+            vfcInstanceGroupCustom.setFunction(getLeafPropertyValue(serviceEntityList.get(0), getInputName));
+        }
+
         vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup);
 
         ArrayList<Input> inputs = vnfcNodeTemplate.getSubMappingToscaTemplate().getInputs();
-        createVFCInstanceGroupMembers(vfcInstanceGroupCustom, group, inputs);
+        createVFCInstanceGroupMembers(vfcInstanceGroupCustom, vfcInstanceEntity, inputs);
 
         return vfcInstanceGroupCustom;
-
     }
 
-    private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom, Group group,
-            List<Input> inputList) {
-        List<NodeTemplate> members = group.getMemberNodes();
+    private void createVFCInstanceGroupMembers(VnfcInstanceGroupCustomization vfcInstanceGroupCustom,
+            IEntityDetails vfcModuleEntity, List<Input> inputList) {
+        List<IEntityDetails> members = vfcModuleEntity.getMemberNodes();
         if (!CollectionUtils.isEmpty(members)) {
-            for (NodeTemplate vfcTemplate : members) {
+            for (IEntityDetails vfcEntity : members) {
                 VnfcCustomization vnfcCustomization = new VnfcCustomization();
 
-                Metadata metadata = vfcTemplate.getMetaData();
+                Metadata metadata = vfcEntity.getMetadata();
                 vnfcCustomization
                         .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID));
-                vnfcCustomization.setModelInstanceName(vfcTemplate.getName());
+                vnfcCustomization.setModelInstanceName(vfcEntity.getName());
                 vnfcCustomization.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID));
                 vnfcCustomization
                         .setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID));
                 vnfcCustomization.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION));
                 vnfcCustomization.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME));
-                vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType()));
+                vnfcCustomization.setToscaNodeType(testNull(vfcEntity.getToscaType()));
                 vnfcCustomization
                         .setDescription(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)));
-                vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcTemplate, inputList));
+                vnfcCustomization.setResourceInput(getVnfcResourceInput(vfcEntity, inputList));
                 List<VnfcCustomization> vnfcCustomizations = vfcInstanceGroupCustom.getVnfcCustomizations();
 
                 if (vnfcCustomizations == null) {
@@ -1908,9 +1938,9 @@ public class ToscaResourceInstaller {
         }
     }
 
-    public String getVnfcResourceInput(NodeTemplate vfcTemplate, List<Input> inputList) {
+    public String getVnfcResourceInput(IEntityDetails vfcEntity, List<Input> inputList) {
         Map<String, String> resouceRequest = new HashMap<>();
-        LinkedHashMap<String, Property> vfcTemplateProperties = vfcTemplate.getProperties();
+        Map<String, Property> vfcTemplateProperties = vfcEntity.getProperties();
         for (String key : vfcTemplateProperties.keySet()) {
             Property property = vfcTemplateProperties.get(key);
             String resourceValue = getValue(property.getValue(), inputList);
@@ -1918,7 +1948,7 @@ public class ToscaResourceInstaller {
         }
 
         String resourceCustomizationUuid =
-                vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
+                vfcEntity.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID);
 
         String jsonStr = null;
         try {
@@ -2700,6 +2730,18 @@ public class ToscaResourceInstaller {
 
     }
 
+    protected List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct, String entityType,
+            TopologyTemplateQueryBuilder topologyTemplateBuilder, boolean nestedSearch) {
+
+        EntityQuery entityQuery = EntityQuery.newBuilder(entityType).build();
+        TopologyTemplateQuery topologyTemplateQuery = topologyTemplateBuilder.build();
+        List<IEntityDetails> entityDetails =
+                toscaResourceStruct.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, nestedSearch);
+
+        return entityDetails;
+
+    }
+
     protected List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct, SdcTypes entityType,
             TopologyTemplateQueryBuilder topologyTemplateBuilder, boolean nestedSearch) {
 
@@ -2712,6 +2754,18 @@ public class ToscaResourceInstaller {
 
     }
 
+    protected List<IEntityDetails> getEntityDetails(ToscaResourceStructure toscaResourceStruct,
+            EntityQueryBuilder entityType, SdcTypes topologyTemplate, boolean nestedSearch) {
+
+        EntityQuery entityQuery = entityType.build();
+        TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(topologyTemplate).build();
+        List<IEntityDetails> entityDetails =
+                toscaResourceStruct.getSdcCsarHelper().getEntity(entityQuery, topologyTemplateQuery, nestedSearch);
+
+        return entityDetails;
+
+    }
+
     protected String getLeafPropertyValue(IEntityDetails entityDetails, String propName) {
 
         Property leafProperty = entityDetails.getProperties().get(propName);
index 0681cd8..055968c 100644 (file)
@@ -33,6 +33,7 @@ import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TestName;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.onap.so.asdc.BaseTest;
 import org.onap.so.asdc.client.exceptions.ASDCControllerException;
 import org.onap.so.asdc.client.test.emulators.ArtifactInfoImpl;
@@ -55,6 +56,7 @@ import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus;
 import org.onap.so.db.request.data.repository.WatchdogComponentDistributionStatusRepository;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -277,6 +279,35 @@ public class ASDCControllerITTest extends BaseTest {
         }
     }
 
+    /**
+     * Test to check RequestId is being set using the DistributionID.
+     */
+    @Test
+    public void treatNotification_verifyRequestID() {
+
+        String serviceUuid = "efaea486-561f-4159-9191-a8d3cb346728";
+        String serviceInvariantUuid = "f2edfbf4-bb0a-4fe7-a57a-71362d4b0b23";
+        distributionId = "bb15de12-166d-4e45-9e5f-4b3f25200d7b";
+
+        initMockAaiServer(serviceUuid, serviceInvariantUuid);
+
+        NotificationDataImpl notificationData = new NotificationDataImpl();
+        notificationData.setServiceUUID(serviceUuid);
+        notificationData.setDistributionID(distributionId);
+        notificationData.setServiceInvariantUUID(serviceInvariantUuid);
+        notificationData.setServiceVersion("1.0");
+
+        try {
+            asdcController.treatNotification(notificationData);
+            logger.info("Verify RequestId : {}", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+            assertEquals("bb15de12-166d-4e45-9e5f-4b3f25200d7b", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+
+        } catch (Exception e) {
+            logger.info(e.getMessage(), e);
+            fail(e.getMessage());
+        }
+    }
+
     private ArtifactInfoImpl constructPnfServiceArtifact() {
         ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl();
         artifactInfo.setArtifactType(ASDCConfiguration.TOSCA_CSAR);
index 846eaf4..da99efa 100644 (file)
@@ -24,6 +24,7 @@ import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.junit.MockitoJUnit;
 import org.mockito.junit.MockitoRule;
+import org.onap.sdc.tosca.parser.api.IEntityDetails;
 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
 import org.onap.sdc.toscaparser.api.NodeTemplate;
 import org.onap.sdc.toscaparser.api.Property;
@@ -48,6 +49,9 @@ public class ToscaResourceInputTest {
     @Mock
     NodeTemplate nodeTemplate;
 
+    @Mock
+    IEntityDetails entityDetails;
+
     @Mock
     Property property;
 
@@ -65,16 +69,16 @@ public class ToscaResourceInputTest {
         Map<String, Object> map = new HashMap<>();
         map.put("customizationUUID", "69df3303-d2b3-47a1-9d04-41604d3a95fd");
         Metadata metadata = new Metadata(map);
-        when(nodeTemplate.getProperties()).thenReturn(hashMap);
+        when(entityDetails.getProperties()).thenReturn(hashMap);
         when(property.getValue()).thenReturn(getInput);
         when(getInput.getInputName()).thenReturn("nameKey");
         when(input.getName()).thenReturn("nameKey");
         when(input.getDefault()).thenReturn("defaultValue");
         when(getInput.toString()).thenReturn("getinput:[sites,INDEX,role]");
-        when(nodeTemplate.getMetaData()).thenReturn(metadata);
+        when(entityDetails.getMetadata()).thenReturn(metadata);
         List<Input> inputs = new ArrayList<>();
         inputs.add(input);
-        String resourceInput = toscaResourceInstaller.getVnfcResourceInput(nodeTemplate, inputs);
+        String resourceInput = toscaResourceInstaller.getVnfcResourceInput(entityDetails, inputs);
         assertEquals("{\\\"key1\\\":\\\"[sites,INDEX,role]|defaultValue\\\"}", resourceInput);
     }
 
index 652fc8f..ad6b156 100644 (file)
@@ -1113,6 +1113,7 @@ CREATE TABLE `vnf_resource_customization` (
   `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL,
   `SERVICE_MODEL_UUID` varchar(200) NOT NULL,
   `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL,
+  `NF_DATA_VALID` tinyint(1) DEFAULT '0',  
   PRIMARY KEY (`ID`),
   UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`),
   KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`),
index 64567a3..5525c26 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -40,11 +40,11 @@ class ExternalAPIUtil {
 
        String Prefix="EXTAPI_"
 
-    private static final Logger logger = LoggerFactory.getLogger( ExternalAPIUtil.class);
+    private static final Logger logger = LoggerFactory.getLogger( ExternalAPIUtil.class)
 
-       private final HttpClientFactory httpClientFactory;
-       private final MsoUtils utils;
-       private final ExceptionUtil exceptionUtil;
+       private final HttpClientFactory httpClientFactory
+       private final MsoUtils utils
+       private final ExceptionUtil exceptionUtil
 
        public static final String PostServiceOrderRequestsTemplate =
        "{\n" +
@@ -107,22 +107,22 @@ class ExternalAPIUtil {
 //     }
 
        public String setTemplate(String template, Map<String, String> valueMap) {
-               logger.debug("ExternalAPIUtil setTemplate", true);
-               StringBuffer result = new StringBuffer();
+               logger.debug("ExternalAPIUtil setTemplate", true)
+               StringBuffer result = new StringBuffer()
 
-               String pattern = "<.*>";
-               Pattern r = Pattern.compile(pattern);
-               Matcher m = r.matcher(template);
+               String pattern = "<.*>"
+               Pattern r = Pattern.compile(pattern)
+               Matcher m = r.matcher(template)
 
-               logger.debug("ExternalAPIUtil template:" + template, true);
+               logger.debug("ExternalAPIUtil template:" + template, true)
                while (m.find()) {
-                       String key = template.substring(m.start() + 1, m.end() - 1);
-                       logger.debug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true);
-                       m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\""));
+                       String key = template.substring(m.start() + 1, m.end() - 1)
+                       logger.debug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true)
+                       m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\""))
                }
-               m.appendTail(result);
-               logger.debug("ExternalAPIUtil return:" + result.toString(), true);
-               return result.toString();
+               m.appendTail(result)
+               logger.debug("ExternalAPIUtil return:" + result.toString(), true)
+               return result.toString()
        }
 
        /**
index e7f4646..549267e 100644 (file)
@@ -4,7 +4,7 @@
  * ================================================================================
  * Copyright (C) 2018 Nokia.
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
index f013fa8..db39358 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -22,9 +22,9 @@
 
 package org.onap.so.bpmn.common.scripts
 
-import org.onap.so.logger.LoggingAnchor;
+import org.onap.so.logger.LoggingAnchor
 import org.onap.so.bpmn.core.UrnPropertiesReader
-import org.onap.so.logger.ErrorCode;
+import org.onap.so.logger.ErrorCode
 
 import java.text.SimpleDateFormat
 
@@ -39,7 +39,7 @@ import static org.apache.commons.lang3.StringUtils.*
 
 // SDNC Adapter Request/Response processing
 public class SDNCAdapter extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( SDNCAdapter.class);
+    private static final Logger logger = LoggerFactory.getLogger( SDNCAdapter.class)
 
 
        def Prefix="SDNCA_"
@@ -77,7 +77,7 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor {
                        } catch (IOException ex) {
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                                "Unable to encode username password string", "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                        }
 
                        // TODO Use variables instead of passing xml request - Huh?
@@ -238,9 +238,9 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor {
                def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest")
                logger.debug("sdncAdapterCallbackRequest :" + sdnccallbackreq)
                if (sdnccallbackreq==null){
-                       execution.setVariable("callbackResponseReceived",false);
+                       execution.setVariable("callbackResponseReceived",false)
                }else{
-                       execution.setVariable("callbackResponseReceived",true);
+                       execution.setVariable("callbackResponseReceived",true)
                }
        }
 
@@ -303,10 +303,10 @@ public class SDNCAdapter extends AbstractServiceTaskProcessor {
        }
 
        public String generateCurrentTimeInUtc(){
-               final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
-               sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
-               final String utcTime = sdf.format(new Date());
-               return utcTime;
+               final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
+               sdf.setTimeZone(TimeZone.getTimeZone("UTC"))
+               final String utcTime = sdf.format(new Date())
+               return utcTime
        }
 
        public void toggleSuccessIndicator(DelegateExecution execution){
index 449f4e3..c30d807 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -53,7 +53,7 @@ import org.onap.so.utils.TargetEntity
 
 
 class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV1.class);
+    private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV1.class)
 
 
        ExceptionUtil exceptionUtil = new ExceptionUtil()
@@ -88,7 +88,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined'
                                logger.debug(msg)
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                                exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                        }
 
@@ -109,7 +109,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                        String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType
                                        logger.debug(msg)
                                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                                       ErrorCode.UnknownError.getValue());
+                                                       ErrorCode.UnknownError.getValue())
                                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                                }
 
@@ -124,7 +124,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                        String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType
                                        logger.debug(msg)
                                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                                       ErrorCode.UnknownError.getValue());
+                                                       ErrorCode.UnknownError.getValue())
                                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                                }
 
@@ -141,7 +141,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
                                logger.debug(msg)
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                                exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                        }
 
@@ -157,7 +157,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined")
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                                getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                        } else {
                                try {
                                        def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
@@ -166,7 +166,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                        logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter")
                                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                                        getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter",
-                                                       "BPMN", ErrorCode.UnknownError.getValue(), ex);
+                                                       "BPMN", ErrorCode.UnknownError.getValue(), ex)
                                }
                        }
 
@@ -176,7 +176,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout")
 
                        // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S"
-                       String timerRegex = "PT[0-9]+[HMS]";
+                       String timerRegex = "PT[0-9]+[HMS]"
                        if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) {
                                logger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"')
                                timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
@@ -197,7 +197,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        String msg = 'Caught exception in ' + method + ": " + e
                        logger.debug(msg)
                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                       ErrorCode.UnknownError.getValue());
+                                       ErrorCode.UnknownError.getValue())
                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                }
        }
@@ -221,7 +221,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        String sdncAdapterRequest = execution.getVariable(prefix + 'sdncAdapterRequest')
                        logger.debug("SDNC Rest Request is: " + sdncAdapterRequest)
 
-                       URL url = new URL(sdncAdapterUrl);
+                       URL url = new URL(sdncAdapterUrl)
 
                        HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.SDNC_ADAPTER)
                        httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id"))
@@ -245,7 +245,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                                String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e
                                logger.debug(msg)
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                                exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                        }
 
@@ -259,7 +259,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        String msg = 'Caught exception in ' + method + ": " + e
                        logger.debug(msg, e)
                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                       ErrorCode.UnknownError.getValue());
+                                       ErrorCode.UnknownError.getValue())
                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                }
        }
@@ -330,7 +330,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        }
 
                        // Note: the mapping function handles a null or empty responseCode
-                       int mappedResponseCode = Integer.parseInt(exceptionUtil.MapSDNCResponseCodeToErrorCode(responseCode));
+                       int mappedResponseCode = Integer.parseInt(exceptionUtil.MapSDNCResponseCodeToErrorCode(responseCode))
                        exceptionUtil.buildWorkflowException(execution, mappedResponseCode, "Received " + responseType +
                                " from SDNCAdapter:" + info)
                } catch (Exception e) {
@@ -370,7 +370,7 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        String msg = 'Caught exception in ' + method + ": " + e
                        logger.debug(msg)
                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                       ErrorCode.UnknownError.getValue());
+                                       ErrorCode.UnknownError.getValue())
                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                }
        }
@@ -396,12 +396,12 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
                        String msg = 'Caught exception in ' + method + ": " + e
                        logger.debug(msg)
                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                       ErrorCode.UnknownError.getValue());
+                                       ErrorCode.UnknownError.getValue())
                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                }
        }
        
        public Logger getLogger() {
-               return logger;
+               return logger
        }
 }
index 62c7bb5..ba5145d 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -51,7 +51,7 @@ import org.slf4j.LoggerFactory
  * any non-final response received from SDNC.
  */
 class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
-    private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV2.class);
+    private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV2.class)
 
 
        ExceptionUtil exceptionUtil = new ExceptionUtil()
@@ -87,7 +87,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                                String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined'
                                logger.debug(msg)
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                                exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                        }
 
@@ -108,7 +108,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                                        String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType
                                        logger.debug(msg)
                                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                                       ErrorCode.UnknownError.getValue());
+                                                       ErrorCode.UnknownError.getValue())
                                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                                }
 
@@ -123,7 +123,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                                        String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType
                                        logger.debug(msg)
                                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                                       ErrorCode.UnknownError.getValue());
+                                                       ErrorCode.UnknownError.getValue())
                                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                                }
 
@@ -134,7 +134,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                                String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
                                logger.debug(msg)
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                                exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                        }
 
@@ -153,7 +153,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                                logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined")
                                logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                                getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN",
-                                               ErrorCode.UnknownError.getValue());
+                                               ErrorCode.UnknownError.getValue())
                        } else {
                                try {
                                        def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
@@ -162,7 +162,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                                        logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter")
                                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                                        getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter",
-                                                       "BPMN", ErrorCode.UnknownError.getValue(), ex);
+                                                       "BPMN", ErrorCode.UnknownError.getValue(), ex)
                                }
                        }
 
@@ -172,7 +172,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                        String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout")
 
                        // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S"
-                       String timerRegex = "PT[0-9]+[HMS]";
+                       String timerRegex = "PT[0-9]+[HMS]"
                        if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) {
                                logger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"')
                                timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
@@ -193,7 +193,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
                        String msg = 'Caught exception in ' + method + ": " + e
                        logger.debug(msg)
                        logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
-                                       ErrorCode.UnknownError.getValue());
+                                       ErrorCode.UnknownError.getValue())
                        exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
                }
        }
@@ -297,6 +297,6 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
        }
        
        public Logger getLogger() {
-               return logger;
+               return logger
        }
 }
index 68cda5c..69151ff 100644 (file)
@@ -27,9 +27,9 @@ import java.util.Optional;
 import java.util.stream.Collectors;
 import javax.annotation.PostConstruct;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
-import org.onap.so.bpmn.common.listener.ListenerRunner;
 import org.onap.so.bpmn.common.listener.flowmanipulator.FlowManipulatorListenerRunner;
 import org.onap.so.db.request.beans.InfraActiveRequests;
+import org.onap.so.listener.ListenerRunner;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
index 5f4dc87..ea7de68 100644 (file)
@@ -27,8 +27,8 @@ import java.util.Optional;
 import java.util.stream.Collectors;
 import javax.annotation.PostConstruct;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
-import org.onap.so.bpmn.common.listener.ListenerRunner;
 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
+import org.onap.so.listener.ListenerRunner;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Component;
index 040522b..02cddf3 100644 (file)
@@ -28,9 +28,11 @@ import org.camunda.bpm.engine.delegate.DelegateExecution;
 import org.javatuples.Pair;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
 import org.onap.so.bpmn.common.DelegateExecutionImpl;
-import org.onap.so.bpmn.common.listener.ListenerRunner;
+import org.onap.so.client.exception.ExceptionBuilder;
+import org.onap.so.listener.ListenerRunner;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
 
@@ -47,6 +49,9 @@ public abstract class FlowValidatorRunner<S extends FlowValidator, E extends Flo
 
     private static Logger logger = LoggerFactory.getLogger(FlowValidatorRunner.class);
 
+    @Autowired
+    protected ExceptionBuilder exceptionBuilder;
+
     protected List<S> preFlowValidators;
     protected List<E> postFlowValidators;
 
index b1173bb..3a4df68 100644 (file)
@@ -68,7 +68,7 @@ public class InstanceResourceList {
 
 
     public static List<Resource> getInstanceResourceList(final VnfResource vnfResource, final String uuiRequest) {
-        List<Resource> sequencedResourceList = new ArrayList<Resource>();
+        List<Resource> sequencedResourceList = new ArrayList<>();
         Gson gson = new Gson();
         JsonObject servJsonObject = gson.fromJson(uuiRequest, JsonObject.class);
         JsonObject reqInputJsonObj = servJsonObject.getAsJsonObject("service").getAsJsonObject("parameters")
@@ -108,11 +108,16 @@ public class InstanceResourceList {
             sequencedResourceList.add(vnfResource);
         }
 
+        // check if the resource contains vf-module
+        if (vnfResource != null && vnfResource.getVfModules() != null) {
+            sequencedResourceList.addAll(vnfResource.getVfModules());
+        }
+
         return sequencedResourceList;
     }
 
     private static List<Resource> getGroupResourceInstanceList(VnfResource vnfResource, JsonObject vfObj) {
-        List<Resource> sequencedResourceList = new ArrayList<Resource>();
+        List<Resource> sequencedResourceList = new ArrayList<>();
         if (vnfResource.getGroupOrder() != null && !StringUtils.isEmpty(vnfResource.getGroupOrder())) {
             String[] grpSequence = vnfResource.getGroupOrder().split(",");
             for (String grpType : grpSequence) {
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/util/CryptoHandler.java
deleted file mode 100644 (file)
index 5c0406c..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.so.bpmn.common.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.util.Properties;
-import org.onap.so.utils.CryptoUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class CryptoHandler implements ICryptoHandler {
-    private static final Logger logger = LoggerFactory.getLogger(CryptoHandler.class);
-    private static final String GENERAL_SECURITY_EXCEPTION_PREFIX = "GeneralSecurityException :";
-    private static final String MSO_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
-    private static final String PROPERTY_KEY = "mso.AaiEncrypted.Pwd";
-
-    @Override
-    public String getMsoAaiPassword() {
-        Properties keyProp = new Properties();
-        try {
-            ClassLoader cl = Thread.currentThread().getContextClassLoader();
-            InputStream rs = cl.getResourceAsStream("urn.properties");
-            keyProp.load(rs);
-            rs.close();
-            return CryptoUtils.decrypt((String) keyProp.get(PROPERTY_KEY), MSO_KEY);
-        } catch (GeneralSecurityException | IOException e) {
-            logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
-            return null;
-        }
-    }
-
-
-    @Override
-    public String encryptMsoPassword(String plainMsoPwd) {
-        try {
-            return CryptoUtils.encrypt(plainMsoPwd, MSO_KEY);
-        } catch (GeneralSecurityException e) {
-            logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
-            return null;
-        }
-    }
-
-    @Override
-    public String decryptMsoPassword(String encryptedPwd) {
-        try {
-            return CryptoUtils.decrypt(encryptedPwd, MSO_KEY);
-        } catch (GeneralSecurityException e) {
-            logger.error(GENERAL_SECURITY_EXCEPTION_PREFIX + e.getMessage(), e);
-            return null;
-        }
-    }
-}
index f56fad3..84b162e 100644 (file)
@@ -31,7 +31,7 @@ public class Metadata implements Serializable {
     private static final long serialVersionUID = 4981393122007858950L;
 
     @JsonProperty("metadatum")
-    private List<Metadatum> metadatum = new ArrayList<Metadatum>();
+    private List<Metadatum> metadatum = new ArrayList<>();
 
     public List<Metadatum> getMetadatum() {
         return metadatum;
index a5eb9d8..96a6ab7 100644 (file)
@@ -36,8 +36,6 @@ public class AggregateRoute implements Serializable, ShallowCopy<AggregateRoute>
     @Id
     @JsonProperty("route-id")
     private String routeId;
-    @JsonProperty("route-name")
-    private String routeName;
     @JsonProperty("network-start-address")
     private String networkStartAddress;
     @JsonProperty("cidr-mask")
@@ -54,14 +52,6 @@ public class AggregateRoute implements Serializable, ShallowCopy<AggregateRoute>
         this.routeId = routeId;
     }
 
-    public String getRouteName() {
-        return routeName;
-    }
-
-    public void setRouteName(String routeName) {
-        this.routeName = routeName;
-    }
-
     public String getNetworkStartAddress() {
         return networkStartAddress;
     }
index 841546b..ebf722e 100644 (file)
@@ -133,7 +133,7 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> {
     @JsonProperty("model-info-generic-vnf")
     private ModelInfoGenericVnf modelInfoGenericVnf;
     @JsonProperty("instance-groups")
-    private List<InstanceGroup> instanceGroups = new ArrayList<InstanceGroup>();
+    private List<InstanceGroup> instanceGroups = new ArrayList<>();
     @JsonProperty("call-homing")
     private Boolean callHoming;
     @JsonProperty("nf-function")
index 387d191..db27859 100644 (file)
@@ -65,15 +65,15 @@ public class LInterface implements Serializable, ShallowCopy<LInterface> {
     @JsonProperty("allowed-address-pairs")
     private String allowedAddressPairs;
     @JsonProperty("vlans")
-    private List<Vlan> vlans = new ArrayList<Vlan>();
+    private List<Vlan> vlans = new ArrayList<>();
     @JsonProperty("sriov-vfs")
-    private List<SriovVf> sriovVfs = new ArrayList<SriovVf>();
+    private List<SriovVf> sriovVfs = new ArrayList<>();
     @JsonProperty("l-interfaces")
-    private List<LInterface> lInterfaces = new ArrayList<LInterface>();
+    private List<LInterface> lInterfaces = new ArrayList<>();
     @JsonProperty("l3-interface-ipv4-address-list")
-    private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<L3InterfaceIpv4AddressList>();
+    private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<>();
     @JsonProperty("l3-interface-ipv6-address-list")
-    private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<L3InterfaceIpv6AddressList>();
+    private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<>();
 
     public String getInterfaceName() {
         return interfaceName;
index d0bf1f5..f3e28fa 100644 (file)
@@ -41,9 +41,9 @@ public class PServer implements Serializable, ShallowCopy<PServer> {
     @JsonProperty("hostname")
     private String hostname;
     @JsonProperty("physical-links")
-    private List<PhysicalLink> physicalLinks = new ArrayList<PhysicalLink>(); // TODO techincally there is a pInterface
-                                                                              // between (pserver <--> physical-link)
-                                                                              // but dont really need that pojo
+    private List<PhysicalLink> physicalLinks = new ArrayList<>(); // TODO techincally there is a pInterface
+                                                                  // between (pserver <--> physical-link)
+                                                                  // but dont really need that pojo
 
     public String getPserverId() {
         return pserverId;
index 0803bed..6cc8aa3 100644 (file)
@@ -79,7 +79,7 @@ public class ServiceInstance implements Serializable, ShallowCopy<ServiceInstanc
     @JsonProperty("instance-groups")
     private List<InstanceGroup> instanceGroups = new ArrayList<>();
     @JsonProperty("service-proxies")
-    private List<ServiceProxy> serviceProxies = new ArrayList<ServiceProxy>();
+    private List<ServiceProxy> serviceProxies = new ArrayList<>();
 
     public void setServiceProxies(List<ServiceProxy> serviceProxies) {
         this.serviceProxies = serviceProxies;
index 05199b7..b677b1e 100644 (file)
@@ -41,7 +41,7 @@ public class ServiceSubscription implements Serializable, ShallowCopy<ServiceSub
     @JsonProperty("temp-ub-sub-account-id")
     private String tempUbSubAccountId;
     @JsonProperty("service-instances")
-    private List<ServiceInstance> serviceInstances = new ArrayList<ServiceInstance>();
+    private List<ServiceInstance> serviceInstances = new ArrayList<>();
 
     public String getServiceType() {
         return serviceType;
index 6951a23..8c0db18 100644 (file)
@@ -62,9 +62,9 @@ public class Vlan implements Serializable, ShallowCopy<Vlan> {
     @JsonProperty("is-ip-unnumbered")
     private Boolean isIpUnnumbered;
     @JsonProperty("l3-interface-ipv4-address-list")
-    private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<L3InterfaceIpv4AddressList>();
+    private List<L3InterfaceIpv4AddressList> l3InterfaceIpv4AddressList = new ArrayList<>();
     @JsonProperty("l3-interface-ipv6-address-list")
-    private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<L3InterfaceIpv6AddressList>();
+    private List<L3InterfaceIpv6AddressList> l3InterfaceIpv6AddressList = new ArrayList<>();
 
     public String getVlanInterface() {
         return vlanInterface;
index 4ee8213..4e5b355 100644 (file)
@@ -41,10 +41,10 @@ public class VpnBondingLink implements Serializable, ShallowCopy<VpnBondingLink>
     private String vpnBondingLinkId;
 
     @JsonProperty("configurations")
-    private List<Configuration> configurations = new ArrayList<Configuration>();
+    private List<Configuration> configurations = new ArrayList<>();
 
     @JsonProperty("service-proxies")
-    private List<ServiceProxy> serviceProxies = new ArrayList<ServiceProxy>();
+    private List<ServiceProxy> serviceProxies = new ArrayList<>();
 
     public String getVpnBondingLinkId() {
         return vpnBondingLinkId;
index c9f7e5e..93d85da 100644 (file)
@@ -34,9 +34,9 @@ public class License implements Serializable {
     private static final long serialVersionUID = 2345786874755685318L;
 
     @JsonProperty("entitlement-pool-uuids")
-    private List<String> entitlementPoolUuids = new ArrayList<String>();
+    private List<String> entitlementPoolUuids = new ArrayList<>();
     @JsonProperty("license-key-group-uuids")
-    private List<String> licenseKeyGroupUuids = new ArrayList<String>();
+    private List<String> licenseKeyGroupUuids = new ArrayList<>();
 
 
     public List<String> getEntitlementPoolUuids() {
index 573925f..ea48c78 100644 (file)
@@ -30,6 +30,7 @@ import java.util.Map;
 import java.util.Optional;
 import org.modelmapper.ModelMapper;
 import org.modelmapper.convention.MatchingStrategies;
+import org.onap.so.bpmn.servicedecomposition.bbobjects.AggregateRoute;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.Collection;
@@ -131,6 +132,10 @@ public class BBInputSetupMapperLayer {
         return modelMapper.map(aaiSegmentationAssignment, SegmentationAssignment.class);
     }
 
+    protected AggregateRoute mapAAIAggregateRoute(org.onap.aai.domain.yang.AggregateRoute aaiAggregateRoute) {
+        return modelMapper.map(aaiAggregateRoute, AggregateRoute.class);
+    }
+
     protected CtagAssignment mapAAICtagAssignment(org.onap.aai.domain.yang.CtagAssignment aaiCtagAssignment) {
         return modelMapper.map(aaiCtagAssignment, CtagAssignment.class);
     }
@@ -262,10 +267,21 @@ public class BBInputSetupMapperLayer {
         mapAllSubnetsIntoL3Network(aaiL3Network, network);
         mapAllCtagAssignmentsIntoL3Network(aaiL3Network, network);
         mapAllSegmentationAssignmentsIntoL3Network(aaiL3Network, network);
+        mapAllAggregateRoutesIntoL3Network(aaiL3Network, network);
         network.setOrchestrationStatus(this.mapOrchestrationStatusFromAAI(aaiL3Network.getOrchestrationStatus()));
         return network;
     }
 
+    protected void mapAllAggregateRoutesIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network,
+            L3Network network) {
+        if (aaiL3Network.getAggregateRoutes() != null) {
+            for (org.onap.aai.domain.yang.AggregateRoute aaiAggregateRoute : aaiL3Network.getAggregateRoutes()
+                    .getAggregateRoute()) {
+                network.getAggregateRoutes().add(mapAAIAggregateRoute(aaiAggregateRoute));
+            }
+        }
+    }
+
     protected void mapAllSegmentationAssignmentsIntoL3Network(org.onap.aai.domain.yang.L3Network aaiL3Network,
             L3Network network) {
         if (aaiL3Network.getSegmentationAssignments() != null) {
index fd2054c..be53e50 100644 (file)
@@ -104,6 +104,7 @@ public class ExecuteBuildingBlockRainyDay {
                     }
                 } catch (Exception ex) {
                     // keep default serviceType value
+                    logger.error("Exception in serviceType retrivel", ex);
                 }
                 String vnfType = ASTERISK;
                 try {
@@ -115,6 +116,7 @@ public class ExecuteBuildingBlockRainyDay {
                     }
                 } catch (Exception ex) {
                     // keep default vnfType value
+                    logger.error("Exception in vnfType retrivel", ex);
                 }
 
                 String errorCode = ASTERISK;
@@ -122,12 +124,14 @@ public class ExecuteBuildingBlockRainyDay {
                     errorCode = "" + workflowException.getErrorCode();
                 } catch (Exception ex) {
                     // keep default errorCode value
+                    logger.error("Exception in errorCode retrivel", ex);
                 }
 
                 try {
                     errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode");
                 } catch (Exception ex) {
                     // keep default errorCode value
+                    logger.error("Exception in errorCode retrivel", ex);
                 }
 
                 String workStep = ASTERISK;
@@ -135,6 +139,7 @@ public class ExecuteBuildingBlockRainyDay {
                     workStep = workflowException.getWorkStep();
                 } catch (Exception ex) {
                     // keep default workStep value
+                    logger.error("Exception in workStep retrivel", ex);
                 }
 
                 String errorMessage = ASTERISK;
@@ -142,11 +147,23 @@ public class ExecuteBuildingBlockRainyDay {
                     errorMessage = workflowException.getErrorMessage();
                 } catch (Exception ex) {
                     // keep default workStep value
+                    logger.error("Exception in errorMessage retrivel", ex);
+                }
+
+                String serviceRole = ASTERISK;
+                try {
+                    serviceRole = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0)
+                            .getModelInfoServiceInstance().getServiceRole();
+                    if (serviceRole == null || serviceRole.isEmpty()) {
+                        serviceRole = ASTERISK;
+                    }
+                } catch (Exception ex) {
+                    // keep default serviceRole value
                 }
 
                 RainyDayHandlerStatus rainyDayHandlerStatus;
                 rainyDayHandlerStatus = catalogDbClient.getRainyDayHandlerStatus(bbName, serviceType, vnfType,
-                        errorCode, workStep, errorMessage);
+                        errorCode, workStep, errorMessage, serviceRole);
 
                 if (rainyDayHandlerStatus == null) {
                     handlingCode = "Abort";
@@ -166,14 +183,14 @@ public class ExecuteBuildingBlockRainyDay {
                         logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex);
                     }
                 }
-                if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) {
+                if ("RollbackToAssigned".equals(handlingCode) && !aLaCarte) {
                     handlingCode = "Rollback";
                 }
                 if (handlingCode.startsWith("Rollback")) {
                     String targetState = "";
-                    if (handlingCode.equalsIgnoreCase("RollbackToAssigned")) {
+                    if ("RollbackToAssigned".equalsIgnoreCase(handlingCode)) {
                         targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString();
-                    } else if (handlingCode.equalsIgnoreCase("RollbackToCreated")) {
+                    } else if ("RollbackToCreated".equalsIgnoreCase(handlingCode)) {
                         targetState = Status.ROLLED_BACK_TO_CREATED.toString();
                     } else {
                         targetState = Status.ROLLED_BACK.toString();
@@ -193,7 +210,7 @@ public class ExecuteBuildingBlockRainyDay {
             int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
             execution.setVariable("maxRetries", envMaxRetries);
         } catch (Exception ex) {
-            logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
+            logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
             execution.setVariable("maxRetries", 5);
         }
     }
@@ -236,8 +253,7 @@ public class ExecuteBuildingBlockRainyDay {
             request.setLastModifiedBy("CamundaBPMN");
             requestDbclient.updateInfraActiveRequests(request);
         } catch (Exception e) {
-            logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: "
-                    + e.getMessage());
+            logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: ", e);
         }
     }
 
index b2dbd97..aee28ca 100644 (file)
@@ -90,7 +90,6 @@ public class ExtractPojosForBB {
                     result = lookupObjectInList(serviceInstance.getConfigurations(), value);
                     break;
                 case VPN_ID:
-                    serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
                     result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value);
                     break;
                 case VPN_BONDING_LINK_ID:
@@ -107,8 +106,9 @@ public class ExtractPojosForBB {
         } catch (BBObjectNotFoundException e) { // re-throw parent object not found
             throw e;
         } catch (Exception e) { // convert all other exceptions to object not found
-            logger.warn("BBObjectNotFoundException in ExtractPojosForBB",
-                    "BBObject " + key + " was not found in " + "gBBInput using reference value: " + value);
+            logger.warn(
+                    "BBObjectNotFoundException in ExtractPojosForBB, BBObject {} was not found in gBBInput using reference value: {} {}",
+                    key, value, e);
             throw new BBObjectNotFoundException(key, value);
         }
 
@@ -119,13 +119,8 @@ public class ExtractPojosForBB {
         }
     }
 
-    protected <T> Optional<T> lookupObject(Object obj, String value) throws IllegalAccessException,
-            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
-        return findValue(obj, value);
-    }
-
-    protected <T> Optional<T> lookupObjectInList(List<?> list, String value) throws IllegalAccessException,
-            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+    protected <T> Optional<T> lookupObjectInList(List<?> list, String value)
+            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
         Optional<T> result = Optional.empty();
         for (Object obj : list) {
             result = findValue(obj, value);
@@ -137,8 +132,8 @@ public class ExtractPojosForBB {
 
     }
 
-    protected <T> Optional<T> findValue(Object obj, String value) throws IllegalAccessException,
-            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+    protected <T> Optional<T> findValue(Object obj, String value)
+            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
         for (Field field : obj.getClass().getDeclaredFields()) {
             if (field.isAnnotationPresent(Id.class)) {
                 String fieldName = field.getName();
index b2e6ead..ad94421 100644 (file)
@@ -48,7 +48,7 @@ public class ConfigAssignPropertiesForPnf {
     private String pnfCustomizationUuid;
 
     @JsonIgnore
-    private Map<String, Object> userParam = new HashMap<String, Object>();
+    private Map<String, Object> userParam = new HashMap<>();
 
     public String getServiceInstanceId() {
         return serviceInstanceId;
index 592b349..acd60a4 100644 (file)
@@ -48,7 +48,7 @@ public class ConfigAssignPropertiesForVnf {
     private String vnfCustomizationUuid;
 
     @JsonIgnore
-    private Map<String, Object> userParam = new HashMap<String, Object>();
+    private Map<String, Object> userParam = new HashMap<>();
 
     public String getServiceInstanceId() {
         return serviceInstanceId;
index 2c0377d..f4fe6d7 100644 (file)
@@ -47,7 +47,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(classes = {ValidationConfig.class})
-public class BuildingBlockValidatorRunnerTest {
+public class BuildingBlockValidatorRunnerTest extends BuildingBlockValidatorRunner {
 
     @Rule
     public ExpectedException thrown = ExpectedException.none();
index 0143e56..596eced 100644 (file)
@@ -45,7 +45,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(classes = {ValidationConfig.class})
-public class WorkflowValidatorRunnerTest {
+public class WorkflowValidatorRunnerTest extends WorkflowValidatorRunner {
 
     @Rule
     public ExpectedException thrown = ExpectedException.none();
index af64ed2..544d370 100644 (file)
@@ -23,8 +23,8 @@ package org.onap.so.bpmn.common.listener.validation;
 import java.util.Collections;
 import java.util.Optional;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
-import org.onap.so.bpmn.common.listener.Skip;
 import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator;
+import org.onap.so.listener.Skip;
 import org.springframework.stereotype.Component;
 
 @Component
index 068f433..a3692a5 100644 (file)
 package org.onap.so.bpmn.common.listener.validation;
 
 import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator;
-import org.onap.so.bpmn.common.listener.ListenerRunner;
 import org.onap.so.client.exception.ExceptionBuilder;
+import org.onap.so.listener.ListenerRunner;
 import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 
 @Configuration
-@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class},
+@ComponentScan(basePackageClasses = {ExceptionBuilder.class, ListenerRunner.class, WorkflowValidatorRunner.class},
         nameGenerator = DefaultToShortClassNameBeanNameGenerator.class)
 public class ValidationConfig {
 
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/util/CryptoHandlerTest.java
deleted file mode 100644 (file)
index 273e9f0..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 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.common.util;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
-public class CryptoHandlerTest {
-    private static final String plainPswd = "mso0206";
-    private CryptoHandler cryptoHandler;
-    private static String encryptPwd;
-
-
-    @Before
-    public void setup() {
-        cryptoHandler = new CryptoHandler();
-        encryptPwd = cryptoHandler.encryptMsoPassword(plainPswd);
-    }
-
-    @Test
-    @Ignore // ignored until we can mock the properties file.
-    public void getMsoAaiPasswordTest() {
-        assertEquals(plainPswd, cryptoHandler.getMsoAaiPassword());
-    }
-
-    @Test
-    public void encryptMsoPasswordTest() {
-        assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(cryptoHandler.encryptMsoPassword(plainPswd)));
-    }
-
-    @Test
-    public void decryptMsoPasswordTest() {
-        assertEquals(plainPswd, cryptoHandler.decryptMsoPassword(encryptPwd));
-    }
-}
index 80373eb..18e0891 100644 (file)
@@ -105,7 +105,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         rainyDayHandlerStatus.setWorkStep(ASTERISK);
 
         doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
-                "st1", "vnft1", "7000", "*", "errorMessage");
+                "st1", "vnft1", "7000", "*", "errorMessage", "*");
 
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
         assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
@@ -128,7 +128,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         rainyDayHandlerStatus.setWorkStep(ASTERISK);
 
         doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
-                "st1", "vnft1", ASTERISK, ASTERISK, "errorMessage");
+                "st1", "vnft1", ASTERISK, ASTERISK, "errorMessage", "*");
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
         assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
         assertEquals(5, delegateExecution.getVariable("maxRetries"));
@@ -141,7 +141,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         vnf.setVnfType("vnft1");
         delegateExecution.setVariable("aLaCarte", true);
         doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatus(isA(String.class), isA(String.class),
-                isA(String.class), isA(String.class), isA(String.class), isA(String.class));
+                isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class));
         delegateExecution.setVariable("suppressRollback", false);
 
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
@@ -152,7 +152,8 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
     @Test
     public void queryRainyDayTableExceptionTest() {
         doThrow(RuntimeException.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatus(isA(String.class),
-                isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class));
+                isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class),
+                isA(String.class));
         delegateExecution.setVariable("aLaCarte", true);
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
         delegateExecution.setVariable("suppressRollback", false);
@@ -178,7 +179,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         rainyDayHandlerStatus.setSecondaryPolicy("Abort");
 
         doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
-                "st1", "vnft1", "7000", "*", "errorMessage");
+                "st1", "vnft1", "7000", "*", "errorMessage", "*");
 
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, false);
 
@@ -203,7 +204,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         rainyDayHandlerStatus.setSecondaryPolicy("Abort");
 
         doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
-                "st1", "vnft1", "7000", "*", "errorMessage");
+                "st1", "vnft1", "7000", "*", "errorMessage", "*");
 
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
 
@@ -229,7 +230,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         rainyDayHandlerStatus.setSecondaryPolicy("Abort");
 
         doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
-                "st1", "vnft1", "7000", "*", "errorMessage");
+                "st1", "vnft1", "7000", "*", "errorMessage", "*");
 
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
 
@@ -255,7 +256,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         rainyDayHandlerStatus.setSecondaryPolicy("Abort");
 
         doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
-                "st1", "vnft1", "7000", "*", "errorMessage");
+                "st1", "vnft1", "7000", "*", "errorMessage", "*");
 
         executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
 
@@ -272,4 +273,52 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest {
         assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
     }
 
+    @Test
+    public void queryRainyDayTableServiceRoleNotDefined() throws Exception {
+        customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+        serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+        serviceInstance.getModelInfoServiceInstance().setServiceRole("sr1");
+        vnf.setVnfType("vnft1");
+        delegateExecution.setVariable("aLaCarte", true);
+        delegateExecution.setVariable("suppressRollback", false);
+        delegateExecution.setVariable("WorkflowExceptionCode", "7000");
+        RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+        rainyDayHandlerStatus.setErrorCode("7000");
+        rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB");
+        rainyDayHandlerStatus.setServiceType("st1");
+        rainyDayHandlerStatus.setVnfType("vnft1");
+        rainyDayHandlerStatus.setPolicy("Rollback");
+        rainyDayHandlerStatus.setWorkStep(ASTERISK);
+
+        doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
+                "st1", "vnft1", "7000", "*", "errorMessage", "sr1");
+
+        executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+        assertEquals("Rollback", delegateExecution.getVariable("handlingCode"));
+    }
+
+    @Test
+    public void queryRainyDayTableServiceRoleNC() throws Exception {
+        customer.getServiceSubscription().getServiceInstances().add(serviceInstance);
+        serviceInstance.getModelInfoServiceInstance().setServiceType("st1");
+        serviceInstance.getModelInfoServiceInstance().setServiceRole("NETWORK-COLLECTION");
+        vnf.setVnfType("vnft1");
+        delegateExecution.setVariable("aLaCarte", true);
+        delegateExecution.setVariable("suppressRollback", false);
+        delegateExecution.setVariable("WorkflowExceptionCode", "7000");
+        RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus();
+        rainyDayHandlerStatus.setErrorCode("7000");
+        rainyDayHandlerStatus.setFlowName("ActivateServiceInstanceBB");
+        rainyDayHandlerStatus.setServiceType("st1");
+        rainyDayHandlerStatus.setVnfType("vnft1");
+        rainyDayHandlerStatus.setPolicy("Abort");
+        rainyDayHandlerStatus.setWorkStep(ASTERISK);
+
+        doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatus("AssignServiceInstanceBB",
+                "st1", "vnft1", "7000", "*", "errorMessage", "NETWORK-COLLECTION");
+
+        executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution, true);
+        assertEquals("Abort", delegateExecution.getVariable("handlingCode"));
+    }
+
 }
index 418396f..9b32a4c 100644 (file)
                        }
                ]
        },
+       "aggregateRoutes": {
+               "aggregateRoute": [
+                       {
+                               "routeId": "routeId",
+                               "networkStartAddress": "10.80.12.0",
+                               "cidrMask": "23",
+                               "ipVersion": "4"
+                       }
+               ]
+       },
        "relationshipList": null
 }
\ No newline at end of file
index ccefe19..f65fe17 100644 (file)
                        "segmentation-id": "segmentationId"
                }
        ],
+       "aggregate-routes": [
+               {
+                       "route-id": "routeId",
+                       "network-start-address": "10.80.12.0",
+                       "cidr-mask": "23",
+                       "ip-version": "4"
+               }
+       ],
        "model-info-network": null
 }
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java b/bpmn/MSOCoreBPMN/src/main/java/org/onap/so/bpmn/core/BaseTask.java
deleted file mode 100644 (file)
index 1442099..0000000
+++ /dev/null
@@ -1,422 +0,0 @@
-/*-
- * ============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.core;
-
-import org.camunda.bpm.engine.delegate.DelegateExecution;
-import org.camunda.bpm.engine.delegate.Expression;
-import org.camunda.bpm.engine.delegate.JavaDelegate;
-import org.onap.so.bpmn.core.internal.VariableNameExtractor;
-
-/**
- * Base class for service tasks.
- */
-public class BaseTask implements JavaDelegate {
-
-    /**
-     * Get the value of a required field. This method throws MissingInjectedFieldException if the expression is null,
-     * and BadInjectedFieldException if the expression evaluates to a null value.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value
-     */
-    protected Object getField(Expression expression, DelegateExecution execution, String fieldName) {
-        return getFieldImpl(expression, execution, fieldName, false);
-    }
-
-    /**
-     * Gets the value of an optional field. There are three conditions in which this method returns null:
-     * <p>
-     * <ol>
-     * <li>The expression itself is null (i.e. the field is missing altogether.</li>
-     * <li>The expression evaluates to a null value.</li>
-     * <li>The expression references a single variable which has not been set.</li>
-     * </ol>
-     * <p>
-     * Examples:<br>
-     * Expression ${x} when x is null: return null<br>
-     * Expression ${x} when x is unset: return null<br>
-     * Expression ${x+y} when x and/or y are unset: exception<br>
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value, possibly null
-     */
-    protected Object getOptionalField(Expression expression, DelegateExecution execution, String fieldName) {
-        return getFieldImpl(expression, execution, fieldName, true);
-    }
-
-    /**
-     * Get the value of a required output variable field. This method throws MissingInjectedFieldException if the
-     * expression is null, and BadInjectedFieldException if the expression produces a null or illegal variable name.
-     * Legal variable names contain only letters, numbers, and the underscore character ('_').
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the output variable name
-     */
-    protected String getOutputField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, false);
-        if (o instanceof String) {
-            String variable = (String) o;
-            if (!isLegalVariable(variable)) {
-                throw new BadInjectedFieldException(fieldName, getTaskName(),
-                        "'" + variable + "' is not a legal variable name");
-            }
-            return variable;
-        } else {
-            if (o != null) {
-                throw new BadInjectedFieldException(fieldName, getTaskName(),
-                        "expected a variable name string, got object of type " + o.getClass().getName());
-            } else {
-                throw new BadInjectedFieldException(fieldName, getTaskName(),
-                        "expected a variable name string, got null object");
-            }
-        }
-    }
-
-    /**
-     * Get the value of an optional output variable field. This method throws BadInjectedFieldException if the
-     * expression produces an illegal variable name. Legal variable names contain only letters, numbers, and the
-     * underscore character ('_').
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the output variable name, possibly null
-     */
-    protected String getOptionalOutputField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, true);
-        if (o instanceof String) {
-            String variable = (String) o;
-            if (!isLegalVariable(variable)) {
-                throw new BadInjectedFieldException(fieldName, getTaskName(),
-                        "'" + variable + "' is not a legal variable name");
-            }
-            return variable;
-        } else if (o == null) {
-            return null;
-        } else {
-            throw new BadInjectedFieldException(fieldName, getTaskName(),
-                    "expected a variable name string, got object of type " + o.getClass().getName());
-        }
-    }
-
-    /**
-     * Get the value of a required string field. This method throws MissingInjectedFieldException if the expression is
-     * null, and BadInjectedFieldException if the expression evaluates to a null value.
-     * <p>
-     * Note: the result is coerced to a string value, if necessary.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value
-     */
-    protected String getStringField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, false);
-        if (o instanceof String) {
-            return (String) o;
-        } else if (o != null) {
-            throw new BadInjectedFieldException(fieldName, getTaskName(),
-                    "cannot convert '" + o.toString() + "' to Integer");
-        } else {
-            throw new MissingInjectedFieldException(fieldName, getTaskName());
-        }
-    }
-
-    /**
-     * Gets the value of an optional string field. There are three conditions in which this method returns null:
-     * <p>
-     * <ol>
-     * <li>The expression itself is null (i.e. the field is missing altogether.</li>
-     * <li>The expression evaluates to a null value.</li>
-     * <li>The expression references a single variable which has not been set.</li>
-     * </ol>
-     * <p>
-     * Examples:<br>
-     * Expression ${x} when x is null: return null<br>
-     * Expression ${x} when x is unset: return null<br>
-     * Expression ${x+y} when x and/or y are unset: exception<br>
-     * <p>
-     * Note: the result is coerced to a string value, if necessary.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value, possibly null
-     */
-    protected String getOptionalStringField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, true);
-        if (o instanceof String) {
-            return (String) o;
-        } else if (o == null) {
-            return null;
-        } else {
-            return o.toString();
-        }
-    }
-
-    /**
-     * Get the value of a required integer field. This method throws MissingInjectedFieldException if the expression is
-     * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced
-     * to an integer.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value
-     */
-    protected Integer getIntegerField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, false);
-        if (o instanceof Integer) {
-            return (Integer) o;
-        } else {
-            try {
-                return Integer.parseInt(o.toString());
-            } catch (NumberFormatException e) {
-                if (o != null) {
-                    throw new BadInjectedFieldException(fieldName, getTaskName(),
-                            "cannot convert '" + o.toString() + "' to Integer");
-                } else {
-                    throw new MissingInjectedFieldException(fieldName, getTaskName());
-                }
-            }
-        }
-    }
-
-    /**
-     * Gets the value of an optional integer field. There are three conditions in which this method returns null:
-     * <p>
-     * <ol>
-     * <li>The expression itself is null (i.e. the field is missing altogether.</li>
-     * <li>The expression evaluates to a null value.</li>
-     * <li>The expression references a single variable which has not been set.</li>
-     * </ol>
-     * <p>
-     * Examples:<br>
-     * Expression ${x} when x is null: return null<br>
-     * Expression ${x} when x is unset: return null<br>
-     * Expression ${x+y} when x and/or y are unset: exception<br>
-     * <p>
-     * Note: the result is coerced to an integer value, if necessary. This method throws BadInjectedFieldException if
-     * the result cannot be coerced to an integer.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value, possibly null
-     */
-    protected Integer getOptionalIntegerField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, true);
-        if (o instanceof Integer) {
-            return (Integer) o;
-        } else if (o == null) {
-            return null;
-        } else {
-            try {
-                return Integer.parseInt(o.toString());
-            } catch (NumberFormatException e) {
-                throw new BadInjectedFieldException(fieldName, getTaskName(),
-                        "cannot convert '" + o.toString() + "' to Integer");
-            }
-        }
-    }
-
-    /**
-     * Gets the value of an optional long field. There are three conditions in which this method returns null:
-     * <p>
-     * <ol>
-     * <li>The expression itself is null (i.e. the field is missing altogether.</li>
-     * <li>The expression evaluates to a null value.</li>
-     * <li>The expression references a single variable which has not been set.</li>
-     * </ol>
-     * <p>
-     * Examples:<br>
-     * Expression ${x} when x is null: return null<br>
-     * Expression ${x} when x is unset: return null<br>
-     * Expression ${x+y} when x and/or y are unset: exception<br>
-     * <p>
-     * Note: the result is coerced to a long value, if necessary. This method throws BadInjectedFieldException if the
-     * result cannot be coerced to a long.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value, possibly null
-     */
-    protected Long getOptionalLongField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, true);
-        if (o instanceof Long) {
-            return (Long) o;
-        } else if (o == null) {
-            return null;
-        } else {
-            try {
-                return Long.parseLong(o.toString());
-            } catch (NumberFormatException e) {
-                throw new BadInjectedFieldException(fieldName, getTaskName(),
-                        "cannot convert '" + o.toString() + "' to Long");
-            }
-        }
-    }
-
-    /**
-     * Get the value of a required long field. This method throws MissingInjectedFieldException if the expression is
-     * null, and BadInjectedFieldException if the expression evaluates to a null value or a value that cannot be coerced
-     * to a long.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @return the field value
-     */
-    protected Long getLongField(Expression expression, DelegateExecution execution, String fieldName) {
-        Object o = getFieldImpl(expression, execution, fieldName, false);
-        if (o instanceof Long) {
-            return (Long) o;
-        } else {
-            try {
-                return Long.parseLong(o.toString());
-            } catch (NumberFormatException e) {
-                if (o != null) {
-                    throw new BadInjectedFieldException(fieldName, getTaskName(),
-                            "cannot convert '" + o.toString() + "' to Long");
-                } else {
-                    throw new MissingInjectedFieldException(fieldName, getTaskName());
-                }
-            }
-        }
-    }
-
-    /**
-     * Common implementation for field "getter" methods.
-     *
-     * @param expression the expression
-     * @param execution the execution
-     * @param fieldName the field name (for logging and exceptions)
-     * @param optional true if the field is optional
-     * @return the field value, possibly null
-     */
-    private Object getFieldImpl(Expression expression, DelegateExecution execution, String fieldName,
-            boolean optional) {
-        if (expression == null) {
-            if (!optional) {
-                throw new MissingInjectedFieldException(fieldName, getTaskName());
-            }
-            return null;
-        }
-
-        Object value = null;
-
-        try {
-            value = expression.getValue(execution);
-        } catch (Exception e) {
-            if (!optional) {
-                throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e);
-            }
-
-            // At this point, we have an exception that occurred while
-            // evaluating an expression for an optional field. A common
-            // problem is that the expression is a simple reference to a
-            // variable which has never been set, e.g. the expression is
-            // ${x}. The normal activiti behavior is to throw an exception,
-            // but we don't like that, so we have the following workaround,
-            // which parses the expression text to see if it is a "simple"
-            // variable reference, and if so, returns null. If the
-            // expression is anything other than a single variable
-            // reference, then an exception is thrown, as it would have
-            // been without this workaround.
-
-            // Get the expression text so we can parse it
-            String s = expression.getExpressionText();
-            new VariableNameExtractor(s).extract().ifPresent(name -> {
-                if (execution.hasVariable(name)) {
-                    throw new BadInjectedFieldException(fieldName, getTaskName(), e.getClass().getSimpleName(), e);
-                }
-            });
-        }
-
-        if (value == null && !optional) {
-            throw new BadInjectedFieldException(fieldName, getTaskName(), "required field has null value");
-        }
-
-        return value;
-    }
-
-    /**
-     * Tests if a character is a "word" character.
-     *
-     * @param c the character
-     * @return true if the character is a "word" character.
-     */
-    private static boolean isWordCharacter(char c) {
-        return (Character.isLetterOrDigit(c) || c == '_');
-    }
-
-    /**
-     * Tests if the specified string is a legal flow variable name.
-     *
-     * @param name the string
-     * @return true if the string is a legal flow variable name
-     */
-    private boolean isLegalVariable(String name) {
-        if (name == null) {
-            return false;
-        }
-
-        int len = name.length();
-
-        if (len == 0) {
-            return false;
-        }
-
-        char c = name.charAt(0);
-
-        if (!Character.isLetter(c) && c != '_') {
-            return false;
-        }
-
-        for (int i = 1; i < len; i++) {
-            c = name.charAt(i);
-            if (!Character.isLetterOrDigit(c) && c != '_') {
-                return false;
-            }
-        }
-
-        return true;
-    }
-
-    /**
-     * Returns the name of the task (normally the java class name).
-     *
-     * @return the name of the task
-     */
-    public String getTaskName() {
-        return getClass().getSimpleName();
-    }
-
-    @Override
-    public void execute(DelegateExecution execution) throws Exception {}
-}
index 21847e1..7d5bb0d 100644 (file)
@@ -33,7 +33,7 @@ public class WorkflowException implements Serializable {
     private final int errorCode;
     private final String errorMessage;
     private final String workStep;
-    private transient TargetEntities extSystemErrorSource;
+    private TargetEntities extSystemErrorSource;
 
     /**
      * Constructor
diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/onap/so/bpmn/core/BaseTaskTest.java
deleted file mode 100644 (file)
index a9f33f2..0000000
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * ============LICENSE_START======================================================= ONAP : SO
- * ================================================================================ Copyright (C) 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.core;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import org.camunda.bpm.engine.ProcessEngineServices;
-import org.camunda.bpm.engine.RepositoryService;
-import org.camunda.bpm.engine.delegate.DelegateExecution;
-import org.camunda.bpm.engine.delegate.Expression;
-import org.camunda.bpm.engine.repository.ProcessDefinition;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-public class BaseTaskTest {
-
-    private String prefix = "PRE_";
-    private String processKey = "AnyProcessKey";
-    private String definitionId = "100";
-    private String anyVariable = "anyVariable";
-    private String anyValueString = "anyValue";
-    private String badValueString = "123abc";
-    private int anyValueInt = 123;
-    private Integer anyValueInteger = Integer.valueOf(anyValueInt);
-    private long anyValuelong = 123L;
-    private Long anyValueLong = Long.valueOf(anyValuelong);
-
-    private DelegateExecution mockExecution;
-    private Expression mockExpression;
-    private BaseTask baseTask;
-    private Object obj1;
-    private Object obj2;
-    private Object objectString;
-    private Object objectInteger;
-    private Object objectLong;
-    private Object objectBoolean;
-
-    @Rule
-    public ExpectedException expectedException = ExpectedException.none();
-
-    @Before
-    public void before() throws Exception {
-        baseTask = new BaseTask();
-        ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class);
-        when(mockProcessDefinition.getKey()).thenReturn(processKey);
-        RepositoryService mockRepositoryService = mock(RepositoryService.class);
-        when(mockRepositoryService.getProcessDefinition(definitionId)).thenReturn(mockProcessDefinition);
-        ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class);
-        when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService);
-        mockExecution = mock(DelegateExecution.class);
-        when(mockExecution.getId()).thenReturn(definitionId);
-        when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices);
-        when(mockExecution.getProcessEngineServices().getRepositoryService()
-                .getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition);
-        when(mockExecution.getVariable("prefix")).thenReturn(prefix);
-        when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true");
-        mockExpression = mock(Expression.class);
-    }
-
-    @Test
-    public void testExecution() throws Exception {
-        baseTask.execute(mockExecution);
-        assertEquals("BaseTask", baseTask.getTaskName());
-    }
-
-    @Test
-    public void testGetFieldAndMissingInjectedException() throws Exception {
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj1 = baseTask.getField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueString, obj1.toString());
-
-        expectedException.expect(MissingInjectedFieldException.class);
-        obj2 = baseTask.getField(null, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        obj1 = baseTask.getField(mockExpression, mockExecution, null);
-    }
-
-    @Test
-    public void testGetOptionalField() throws Exception {
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj1 = baseTask.getOptionalField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueString, obj1.toString());
-    }
-
-    @Test
-    public void testGetStringFieldAndMissingInjectedFieldException() throws Exception {
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj1 = baseTask.getStringField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueString, obj1.toString());
-
-        expectedException.expect(MissingInjectedFieldException.class);
-        Object objectBoolean = Boolean.valueOf(true); // bad data
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
-        obj2 = baseTask.getStringField(null, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetStringFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        obj1 = baseTask.getStringField(mockExpression, mockExecution, null);
-    }
-
-    @Test
-    public void testGetOptionalStringField() throws Exception {
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj1 = baseTask.getOptionalStringField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueString, obj1.toString());
-    }
-
-    @Test
-    public void testGetIntegerFieldAndMissingInjectedFieldException() throws Exception {
-        objectInteger = Integer.valueOf(anyValueInt);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger);
-        obj1 = baseTask.getIntegerField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueInteger, (Integer) obj1);
-
-        expectedException.expect(MissingInjectedFieldException.class);
-        objectString = new String(badValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj2 = baseTask.getIntegerField(null, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetIntegerFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        obj1 = baseTask.getIntegerField(mockExpression, mockExecution, null);
-    }
-
-
-    @Test
-    public void testGetOptionalIntegerField() throws Exception {
-        objectInteger = Integer.valueOf(anyValueInt);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectInteger);
-        obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueInteger, (Integer) obj1);
-    }
-
-    @Test
-    public void testGetOptionalIntegerFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        objectBoolean = Boolean.valueOf(true);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
-        obj1 = baseTask.getOptionalIntegerField(mockExpression, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetLongFieldAndMissingInjectedFieldException() throws Exception {
-        objectLong = Long.valueOf(anyValuelong);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectLong);
-        obj1 = baseTask.getLongField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueLong, (Long) obj1);
-
-        expectedException.expect(MissingInjectedFieldException.class);
-        objectString = new String(badValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj2 = baseTask.getLongField(null, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetLongFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        obj2 = baseTask.getLongField(mockExpression, mockExecution, null);
-    }
-
-    @Test
-    public void testGetOptionalLongField() throws Exception {
-        objectLong = Long.valueOf(anyValuelong);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectLong);
-        obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueLong, (Long) obj1);
-    }
-
-    @Test
-    public void testGetOptionalLongFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        objectBoolean = Boolean.valueOf(true);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
-        obj1 = baseTask.getOptionalLongField(mockExpression, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetOutputAndMissingInjectedFieldException() throws Exception {
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj1 = baseTask.getOutputField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueString, obj1.toString());
-
-        expectedException.expect(MissingInjectedFieldException.class);
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj2 = baseTask.getOutputField(null, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetOutputAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        obj2 = baseTask.getOutputField(null, mockExecution, anyVariable);
-    }
-
-    @Test
-    public void testGetOptionalOutputField() throws Exception {
-        objectString = new String(anyValueString);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectString);
-        obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable);
-        assertEquals(anyValueString, obj1.toString());
-    }
-
-    @Test
-    public void testGetOptionalOutputFieldAndBadInjectedFieldException() throws Exception {
-        expectedException.expect(BadInjectedFieldException.class);
-        objectBoolean = Boolean.valueOf(true);
-        when(mockExpression.getValue(mockExecution)).thenReturn(objectBoolean);
-        obj1 = baseTask.getOptionalOutputField(mockExpression, mockExecution, anyVariable);
-    }
-
-}
index ea1a205..25913ea 100644 (file)
         </executions>
       </plugin>
     </plugins>
+    <resources>
+      <resource>
+        <directory>src/main/resources</directory>
+        <filtering>true</filtering>
+        <excludes>
+          <exclude>**/*.p12</exclude>
+          <exclude>**/*.jks</exclude>
+        </excludes>
+      </resource>
+      <resource>
+        <directory>src/main/resources</directory>
+        <filtering>false</filtering>
+        <includes>
+          <include>**/*.p12</include>
+          <include>**/*.jks</include>
+        </includes>
+      </resource>
+    </resources>
   </build>
   <dependencyManagement>
     <dependencies>
index 093fba0..050a2af 100644 (file)
@@ -136,8 +136,8 @@ public class MSOInfrastructureApplication {
                         deploymentBuilder.addString(workflowName, workflowBody);
                     }
                     deploymentBuilder.enableDuplicateFiltering(true);
-                    deploymentBuilder.deploy();
                 }
+                deploymentBuilder.deploy();
             }
         } catch (Exception e) {
             logger.warn("Unable to deploy custom workflows, " + e.getMessage());
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.p12 b/bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.p12
new file mode 100644 (file)
index 0000000..79631bf
Binary files /dev/null and b/bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.p12 differ
diff --git a/bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.trust.jks b/bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.trust.jks
new file mode 100644 (file)
index 0000000..6f8168d
Binary files /dev/null and b/bpmn/mso-infrastructure-bpmn/src/main/resources/org.onap.so.trust.jks differ
index e4f1998..12f30cf 100644 (file)
@@ -31,6 +31,8 @@ import org.apache.http.client.methods.HttpPost;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.HttpClientBuilder;
 import org.springframework.stereotype.Component;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 @Component
 public class DeployActivitySpecs {
@@ -38,10 +40,12 @@ public class DeployActivitySpecs {
     private static final String ACTIVITY_SPEC_URI = "/activityspec-api/v1.0/activity-spec";
     private static final String CONTENT_TYPE_JSON = "application/json";
 
+    private static final Logger logger = LoggerFactory.getLogger(DeployActivitySpecs.class);
+
     public static void main(String[] args) throws Exception {
 
         if (args == null || args.length == 0) {
-            System.out.println("Please specify hostname argument");
+            logger.info("Please specify hostname argument");
             return;
         }
 
@@ -49,20 +53,23 @@ public class DeployActivitySpecs {
 
         File dir = new File(ACTIVITY_FILE_LOCATION);
         if (!dir.isDirectory()) {
-            System.out.println("ActivitySpec store is not a directory");
+            logger.debug("ActivitySpec store is not a directory");
             return;
         }
 
-        for (File f : dir.listFiles()) {
-            String activitySpecName = f.getName();
-            String errorMessage = deployActivitySpec(hostname, activitySpecName);
-            if (errorMessage == null) {
-                System.out.println("Deployed Activity Spec: " + activitySpecName);
-            } else {
-                System.out.println("Error deploying Activity Spec: " + activitySpecName + " : " + errorMessage);
+        if (dir.listFiles() != null) {
+            for (File f : dir.listFiles()) {
+                String activitySpecName = f.getName();
+                String errorMessage = deployActivitySpec(hostname, activitySpecName);
+                if (errorMessage == null) {
+                    logger.debug("Deployed Activity Spec: " + activitySpecName);
+                } else {
+                    logger.error("Error deploying Activity Spec: " + activitySpecName + " : " + errorMessage);
+                }
             }
+        } else {
+            logger.error("Null file list for Activity Specs.");
         }
-        return;
     }
 
     protected static String deployActivitySpec(String hostname, String activitySpecName) throws Exception {
index 30b5cc8..b855e93 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -45,7 +45,7 @@ import org.slf4j.LoggerFactory
  * flow for SDNC Network Resource Activate
  */
 public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( ActivateSDNCNetworkResource.class);
+    private static final Logger logger = LoggerFactory.getLogger( ActivateSDNCNetworkResource.class)
 
     String Prefix = "ACTSDNCRES_"
 
@@ -57,7 +57,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
 
     MsoUtils msoUtils = new MsoUtils()
 
-    public void preProcessRequest(DelegateExecution execution) {
+     void preProcessRequest(DelegateExecution execution) {
         logger.info(" ***** Started preProcessRequest *****")
 
         try {
@@ -106,7 +106,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
         }
     }
 
-    public void prepareUpdateAfterActivateSDNCResource(DelegateExecution execution) {
+     void prepareUpdateAfterActivateSDNCResource(DelegateExecution execution) {
         logger.info("started prepareUpdateAfterActivateSDNCResource ")
 
         ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(execution.getVariable(Prefix + "resourceInput"), ResourceInput.class)
@@ -135,7 +135,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
                                <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription>
                     </ns:updateResourceOperationStatus>
                 </soapenv:Body>
-                </soapenv:Envelope>""";
+                </soapenv:Envelope>"""
 
         setProgressUpdateVariables(execution, body)
     }
@@ -148,12 +148,12 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
 
     String customizeResourceParam(String networkInputParametersJson) {
         List<Map<String, Object>> paramList = new ArrayList()
-        JSONObject jsonObject = new JSONObject(networkInputParametersJson);
+        JSONObject jsonObject = new JSONObject(networkInputParametersJson)
         Iterator iterator = jsonObject.keys()
         while (iterator.hasNext()) {
             String key = iterator.next()
             HashMap<String, String> hashMap = new HashMap()
-            hashMap.put("name", key);
+            hashMap.put("name", key)
             hashMap.put("value", jsonObject.get(key))
             paramList.add(hashMap)
         }
@@ -163,7 +163,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
         return  new JSONObject(paramMap).toString()
     }
 
-    public void prepareSDNCRequest (DelegateExecution execution) {
+     void prepareSDNCRequest (DelegateExecution execution) {
         logger.info("Started prepareSDNCRequest ")
 
         try {
@@ -186,7 +186,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
             String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion()
             String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName()
             String globalCustomerId = resourceInputObj.getGlobalSubscriberId()
-            String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid();
+            String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid()
             String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
             String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
             String modelName = resourceInputObj.getResourceModelInfo().getModelName()
@@ -451,7 +451,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
         logger.info(" ***** Exit prepareSDNCRequest *****")
     }
 
-    public void postActivateSDNCCall(DelegateExecution execution) {
+     void postActivateSDNCCall(DelegateExecution execution) {
         logger.info("started postCreateSDNCCall ")
 
         String responseCode = execution.getVariable(Prefix + "sdncCreateReturnCode")
@@ -460,7 +460,7 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
         logger.info("response from sdnc, response code :" + responseCode + "  response object :" + responseObj)
     }
 
-    public void sendSyncResponse(DelegateExecution execution) {
+     void sendSyncResponse(DelegateExecution execution) {
         logger.info("started sendsyncResp")
 
         try {
@@ -478,4 +478,4 @@ public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
         }
         logger.info("exited send sync Resp")
     }
-}
\ No newline at end of file
+}
index 608bf66..df11549 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  * 
@@ -19,9 +19,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-package org.onap.so.bpmn.infrastructure.scripts;
+package org.onap.so.bpmn.infrastructure.scripts
 
-import static org.apache.commons.lang3.StringUtils.*;
+import static org.apache.commons.lang3.StringUtils.*
 
 import org.apache.commons.lang3.*
 import org.camunda.bpm.engine.delegate.BpmnError
@@ -55,7 +55,7 @@ import groovy.json.*
  * @param - WorkflowException
  */
 public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( CompareModelofE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( CompareModelofE2EServiceInstance.class)
 
        String Prefix="CMPMDSI_"
        private static final String DebugFlag = "isDebugEnabled"
@@ -64,7 +64,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess
        JsonUtils jsonUtil = new JsonUtils()
        VidUtils vidUtils = new VidUtils()
 
-       public void preProcessRequest (DelegateExecution execution) {
+        void preProcessRequest (DelegateExecution execution) {
                execution.setVariable("prefix",Prefix)
                String msg = ""
                
@@ -128,7 +128,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess
                        execution.setVariable("operationType", "CompareModel") 
        
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex){
                        msg = "Exception in preProcessRequest " + ex.getMessage()
                        logger.info(msg)
@@ -137,7 +137,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess
                logger.trace("Exit preProcessRequest ")
        }
 
-       public void sendSyncResponse (DelegateExecution execution) {
+        void sendSyncResponse (DelegateExecution execution) {
                logger.trace("sendSyncResponse  ")
 
                try {
@@ -155,7 +155,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess
                logger.trace("Exit sendSyncResopnse ")
        }
        
-       public void sendSyncError (DelegateExecution execution) {
+        void sendSyncError (DelegateExecution execution) {
                logger.trace("sendSyncError ")
 
                try {
@@ -182,7 +182,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess
 
        }
        
-       public void prepareCompletionRequest (DelegateExecution execution) {
+        void prepareCompletionRequest (DelegateExecution execution) {
                logger.trace("prepareCompletion ")
 
                try {
@@ -214,7 +214,7 @@ public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcess
                logger.trace("Exit prepareCompletionRequest ")
        }
        
-       public void prepareFalloutRequest(DelegateExecution execution){
+        void prepareFalloutRequest(DelegateExecution execution){
                logger.trace("prepareFalloutRequest ")
 
                try {
index 8bb48a2..ced1b92 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -72,7 +72,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso
 
        JsonUtils jsonUtil = new JsonUtils()
 
-    private static final Logger logger = LoggerFactory.getLogger( Create3rdONAPE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( Create3rdONAPE2EServiceInstance.class)
 
        public void checkSPPartnerInfo (DelegateExecution execution) {
                logger.info(" ***** Started checkSPPartnerInfo *****")
@@ -312,7 +312,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso
                        // Put TP Link info into serviceParameters
                        JSONObject inputParameters = new JSONObject(execution.getVariable(Prefix + "ServiceParameters"))
                        if(inputParameters.has("remote-access-provider-id")) {
-                               Map<String, Object> crossTPs = new HashMap<String, Object>();
+                               Map<String, Object> crossTPs = new HashMap<String, Object>()
                                crossTPs.put("local-access-provider-id", inputParameters.get("remote-access-provider-id"))
                                crossTPs.put("local-access-client-id", inputParameters.get("remote-access-client-id"))
                                crossTPs.put("local-access-topology-id", inputParameters.get("remote-access-topology-id"))
index 2abee7c..cae629f 100644 (file)
@@ -7,7 +7,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  * 
@@ -39,7 +39,7 @@ import org.onap.so.client.aai.AAIObjectType
 import org.onap.so.client.aai.AAIResourcesClient
 import org.onap.so.client.aai.entities.uri.AAIResourceUri
 import org.onap.so.client.aai.entities.uri.AAIUriFactory
-import org.onap.so.logger.ErrorCode;
+import org.onap.so.logger.ErrorCode
 import org.onap.so.logger.LoggingAnchor
 import org.onap.so.logger.MessageEnum
 import org.slf4j.Logger
@@ -56,7 +56,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor
        String Prefix="CRESI_"
        ExceptionUtil exceptionUtil = new ExceptionUtil()
        JsonUtils jsonUtil = new JsonUtils()
-    private static final Logger logger = LoggerFactory.getLogger( CreateCustomE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( CreateCustomE2EServiceInstance.class)
        
 
        public void preProcessRequest (DelegateExecution execution) {
@@ -154,7 +154,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor
                        //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams"))
                        //execution.setVariable("failExists", true)
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex){
                        msg = "Exception in preProcessRequest " + ex.getMessage()
                        logger.debug(msg)
@@ -332,7 +332,7 @@ public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor
         }catch(Exception e){
                        logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                        "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN",
-                                       ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
+                                       ErrorCode.UnknownError.getValue(), "Exception is:\n" + e)
             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage())
         }
                logger.trace("finished prepareInitServiceOperationStatus")
index bcd3353..4b3c1aa 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -55,7 +55,7 @@ import org.slf4j.LoggerFactory
  */
 public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
 
-    private static final Logger logger = LoggerFactory.getLogger( CreateSDNCNetworkResource.class);
+    private static final Logger logger = LoggerFactory.getLogger( CreateSDNCNetworkResource.class)
     String Prefix="CRESDNCRES_"
 
     ExceptionUtil exceptionUtil = new ExceptionUtil()
@@ -120,20 +120,20 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
     }
 
     String customizeResourceParam(String networkInputParametersJson) {
-        List<Map<String, Object>> paramList = new ArrayList();
-        JSONObject jsonObject = new JSONObject(networkInputParametersJson);
-        Iterator iterator = jsonObject.keys();
+        List<Map<String, Object>> paramList = new ArrayList()
+        JSONObject jsonObject = new JSONObject(networkInputParametersJson)
+        Iterator iterator = jsonObject.keys()
         while (iterator.hasNext()) {
-            String key = iterator.next();
-            HashMap<String, String> hashMap = new HashMap();
-            hashMap.put("name", key);
+            String key = iterator.next()
+            HashMap<String, String> hashMap = new HashMap()
+            hashMap.put("name", key)
             hashMap.put("value", jsonObject.get(key))
             paramList.add(hashMap)
         }
-        Map<String, List<Map<String, Object>>> paramMap = new HashMap();
-        paramMap.put("param", paramList);
+        Map<String, List<Map<String, Object>>> paramMap = new HashMap()
+        paramMap.put("param", paramList)
 
-        return  new JSONObject(paramMap).toString();
+        return  new JSONObject(paramMap).toString()
     }
 
     private List<Metadatum> getMetaDatum(String customerId,
@@ -347,7 +347,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
             String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion()
             String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName()
             String globalCustomerId = resourceInputObj.getGlobalSubscriberId()
-            String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid();
+            String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid()
             String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
             String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
             String modelName = resourceInputObj.getResourceModelInfo().getModelName()
@@ -357,7 +357,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
             //here convert json string to xml string
             String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(networkInputParametersJson)))
             // 1. prepare assign topology via SDNC Adapter SUBFLOW call
-            String sdncTopologyCreateRequest = "";
+            String sdncTopologyCreateRequest = ""
 
             String modelType = resourceInputObj.getResourceModelInfo().getModelType()
 
@@ -641,7 +641,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
                                <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription>
                     </ns:updateResourceOperationStatus>
                 </soapenv:Body>
-                </soapenv:Envelope>""";
+                </soapenv:Envelope>"""
 
         setProgressUpdateVariables(execution, body)
 
@@ -674,7 +674,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
                                <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription>
                     </ns:updateResourceOperationStatus>
                 </soapenv:Body>
-                </soapenv:Envelope>""";
+                </soapenv:Envelope>"""
 
         setProgressUpdateVariables(execution, body)
     }
@@ -724,7 +724,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor {
         try {
             String operationStatus = "finished"
             // RESTResponse for main flow
-            String vnfid=execution.getVariable("resourceInstanceId");
+            String vnfid=execution.getVariable("resourceInstanceId")
             String resourceOperationResp = """{"operationStatus":"${operationStatus}","vnf-id":"${vnfid}"}""".trim()
             logger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp)
             sendWorkflowResponse(execution, 202, resourceOperationResp)
index 433a8d0..901964f 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -25,7 +25,7 @@ package org.onap.so.bpmn.infrastructure.scripts
 import org.onap.so.client.HttpClientFactory
 import org.onap.so.client.aai.AAIObjectType
 import org.onap.so.client.aai.entities.uri.AAIResourceUri
-import org.onap.so.client.aai.entities.uri.AAIUriFactory;
+import org.onap.so.client.aai.entities.uri.AAIUriFactory
 import org.camunda.bpm.engine.delegate.BpmnError
 import org.camunda.bpm.engine.delegate.DelegateExecution
 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
@@ -44,7 +44,7 @@ import org.onap.so.utils.TargetEntity
  * flow for VFC Network Service Create
  */
 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( CreateVFCNSResource.class);
+    private static final Logger logger = LoggerFactory.getLogger( CreateVFCNSResource.class)
 
     ExceptionUtil exceptionUtil = new ExceptionUtil()
 
@@ -77,7 +77,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
            logger.info("globalSubscriberId:" + globalSubscriberId)
            //set local globalSubscriberId variable
-           execution.setVariable("globalSubscriberId", globalSubscriberId);
+           execution.setVariable("globalSubscriberId", globalSubscriberId)
            String serviceType = execution.getVariable("serviceType")
            logger.info("serviceType:" + serviceType)
 
@@ -110,9 +110,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
                    "operationId":"${operationId}",
                    "nodeTemplateUUID":"${nodeTemplateUUID}"
                     }"""
-           execution.setVariable("nsOperationKey", nsOperationKey);
+           execution.setVariable("nsOperationKey", nsOperationKey)
            execution.setVariable("nsParameters", nsParameters)
-           execution.setVariable("nsServiceModelUUID", nsServiceModelUUID);
+           execution.setVariable("nsServiceModelUUID", nsServiceModelUUID)
 
            String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
                   
@@ -128,7 +128,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
            execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
 
        } catch (BpmnError e) {
-           throw e;
+           throw e
        } catch (Exception ex){
            msg = "Exception in preProcessRequest " + ex.getMessage()
            logger.info(msg)
@@ -143,9 +143,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
     public void createNetworkService(DelegateExecution execution) {
         logger.trace("createNetworkService ")
         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
-        String nsOperationKey = execution.getVariable("nsOperationKey");
-        String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID");
-        String nsParameters = execution.getVariable("nsParameters");
+        String nsOperationKey = execution.getVariable("nsOperationKey")
+        String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID")
+        String nsParameters = execution.getVariable("nsParameters")
         String nsServiceName = execution.getVariable("nsServiceName")
         String nsServiceDescription = execution.getVariable("nsServiceDescription")
         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
@@ -163,7 +163,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
         Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody)
         String returnCode = apiResponse.getStatus ()
         String aaiResponseAsString = apiResponse.readEntity(String.class)
-        String nsInstanceId = "";
+        String nsInstanceId = ""
         if(returnCode== "200" || returnCode == "201"){
             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
         }
@@ -177,8 +177,8 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
     public void instantiateNetworkService(DelegateExecution execution) {
         logger.trace("instantiateNetworkService ")
         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
-        String nsOperationKey = execution.getVariable("nsOperationKey");
-        String nsParameters = execution.getVariable("nsParameters");
+        String nsOperationKey = execution.getVariable("nsOperationKey")
+        String nsParameters = execution.getVariable("nsParameters")
         String nsServiceName = execution.getVariable("nsServiceName")
         String nsServiceDescription = execution.getVariable("nsServiceDescription")
         String reqBody ="""{
@@ -192,7 +192,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
         Response apiResponse = postRequest(execution, url, reqBody)
         String returnCode = apiResponse.getStatus()
         String aaiResponseAsString = apiResponse.readEntity(String.class)
-        String jobId = "";
+        String jobId = ""
         if(returnCode== "200"|| returnCode == "201"){
             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
         }
@@ -207,7 +207,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
         logger.trace("queryNSProgress ")
         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
         String jobId = execution.getVariable("jobId")
-        String nsOperationKey = execution.getVariable("nsOperationKey");
+        String nsOperationKey = execution.getVariable("nsOperationKey")
         String url = vfcAdapterUrl + "/jobs/" + jobId
         Response apiResponse = postRequest(execution, url, nsOperationKey)
         String returnCode = apiResponse.getStatus()
@@ -225,9 +225,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
      */
     public void timeDelay(DelegateExecution execution) {
         try {
-            Thread.sleep(5000);
+            Thread.sleep(5000)
         } catch(InterruptedException e) {
-            logger.error("Time Delay exception" + e.getMessage());
+            logger.error("Time Delay exception" + e.getMessage())
         }
     }
 
@@ -252,7 +252,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
             getAAIClient().connect(nsUri,relatedServiceUri)
             logger.info("NS relationship to Service added successfully")
         }catch(Exception e){
-            logger.error("Exception occured while Creating NS relationship."+ e.getMessage());
+            logger.error("Exception occured while Creating NS relationship."+ e.getMessage())
             throw new BpmnError("MSOWorkflowException")
         }
     }
@@ -268,7 +268,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
         Response apiResponse = null
         try{
 
-            URL url = new URL(urlString);
+            URL url = new URL(urlString)
             
             // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
             // user 'bepl' authHeader is the same with mso.db.auth
@@ -282,7 +282,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
             logger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
 
         }catch(Exception e){
-            logger.error("VFC Aatpter Post Call Exception:" + e.getMessage());
+            logger.error("VFC Aatpter Post Call Exception:" + e.getMessage())
             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "VFC Aatpter Post Call Exception")
         }              
                
index 097a1be..1a689d4 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -42,7 +42,7 @@ import org.slf4j.LoggerFactory
  * flow for SDNC Network Resource Activate
  */
 public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( DeActivateSDNCNetworkResource.class);
+    private static final Logger logger = LoggerFactory.getLogger( DeActivateSDNCNetworkResource.class)
     String Prefix = "DEACTSDNCRES_"
 
     ExceptionUtil exceptionUtil = new ExceptionUtil()
@@ -53,7 +53,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
     
     MsoUtils msoUtils = new MsoUtils()
 
-    public void preProcessRequest(DelegateExecution execution) {
+    void preProcessRequest(DelegateExecution execution) {
 
         logger.info(" ***** Started preProcessRequest *****")
 
@@ -96,7 +96,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
             execution.setVariable("mso-request-id", requestId)
             execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId())
         } catch (BpmnError e) {
-            throw e;
+            throw e
         } catch (Exception ex){
             msg = "Exception in preProcessRequest " + ex.getMessage()
             logger.debug(msg)
@@ -104,7 +104,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
         }
     }
 
-    public void prepareSDNCRequest(DelegateExecution execution) {
+    void prepareSDNCRequest(DelegateExecution execution) {
         logger.info(" ***** Started prepareSDNCRequest *****")
 
         try {
@@ -127,7 +127,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
             String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion()
             String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName()
             String globalCustomerId = resourceInputObj.getGlobalSubscriberId()
-            String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid();
+            String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid()
             String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
             String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
             String modelName = resourceInputObj.getResourceModelInfo().getModelName()
@@ -390,7 +390,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
         logger.info(" ***** Exit prepareSDNCRequest *****")
     }
 
-    public void prepareUpdateAfterDeActivateSDNCResource(DelegateExecution execution) {
+    void prepareUpdateAfterDeActivateSDNCResource(DelegateExecution execution) {
         String resourceInput = execution.getVariable("resourceInput")
         ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
         String operType = resourceInputObj.getOperationType()
@@ -418,7 +418,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
                                <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription>
                     </ns:updateResourceOperationStatus>
                 </soapenv:Body>
-                </soapenv:Envelope>""";
+                </soapenv:Envelope>"""
 
         setProgressUpdateVariables(execution, body)
     }
@@ -429,7 +429,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
     }
 
-    public void postDeactivateSDNCCall(DelegateExecution execution) {
+    void postDeactivateSDNCCall(DelegateExecution execution) {
         logger.info(" ***** Started prepareSDNCRequest *****")        
         String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode")
         String responseObj = execution.getVariable(Prefix + "SuccessIndicator")
@@ -438,7 +438,7 @@ public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor
         logger.info(" ***** Exit prepareSDNCRequest *****")
     }
 
-    public void sendSyncResponse(DelegateExecution execution) {
+    void sendSyncResponse(DelegateExecution execution) {
         logger.debug(" *** sendSyncResponse *** ")
 
         try {
index 64ae3df..da486bb 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -60,7 +60,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso
 
        JsonUtils jsonUtil = new JsonUtils()
 
-    private static final Logger logger = LoggerFactory.getLogger( Delete3rdONAPE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( Delete3rdONAPE2EServiceInstance.class)
 
        public void checkSPPartnerInfoFromAAI (DelegateExecution execution) {
                logger.info(" ***** Started checkSPPartnerInfo *****")
index a9b1fda..2a65ae9 100644 (file)
@@ -8,7 +8,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  * 
@@ -22,9 +22,9 @@
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.so.bpmn.infrastructure.scripts;
+package org.onap.so.bpmn.infrastructure.scripts
 
-import static org.apache.commons.lang3.StringUtils.*;
+import static org.apache.commons.lang3.StringUtils.*
 
 import org.apache.commons.lang3.*
 import org.camunda.bpm.engine.delegate.BpmnError
@@ -38,7 +38,7 @@ import org.onap.so.bpmn.core.json.JsonUtils
 import org.onap.so.bpmn.core.UrnPropertiesReader
 import org.slf4j.Logger
 import org.slf4j.LoggerFactory
-import org.springframework.web.util.UriUtils;
+import org.springframework.web.util.UriUtils
 
 import groovy.json.*
 
@@ -52,7 +52,7 @@ public class DeleteCustomE2EServiceInstance extends AbstractServiceTaskProcessor
        ExceptionUtil exceptionUtil = new ExceptionUtil()
        JsonUtils jsonUtil = new JsonUtils()
        VidUtils vidUtils = new VidUtils()
-    private static final Logger logger = LoggerFactory.getLogger( DeleteCustomE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( DeleteCustomE2EServiceInstance.class)
        
        public void preProcessRequest (DelegateExecution execution) {
                execution.setVariable("prefix",Prefix)
index 7c8b7eb..61b1250 100644 (file)
@@ -67,7 +67,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor {
 
     MsoUtils msoUtils = new MsoUtils()
 
-    public void preProcessRequest(DelegateExecution execution){
+    void preProcessRequest(DelegateExecution execution){
         logger.info(" ***** Started preProcessRequest *****")
         try {
 
@@ -184,7 +184,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor {
      * generate the nsOperationKey
      * generate the nsParameters
      */
-    public void prepareSDNCRequest (DelegateExecution execution) {
+     void prepareSDNCRequest (DelegateExecution execution) {
         logger.info(" ***** Started prepareSDNCRequest *****")
 
         try {
@@ -475,7 +475,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor {
         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
     }
 
-    public void prepareUpdateBeforeDeleteSDNCResource(DelegateExecution execution) {
+    void prepareUpdateBeforeDeleteSDNCResource(DelegateExecution execution) {
         logger.debug(" *** prepareUpdateBeforeDeleteSDNCResource *** ")
         String resourceInput = execution.getVariable(Prefix + "resourceInput");
         ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
@@ -511,7 +511,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor {
 
     }
 
-    public void prepareUpdateAfterDeleteSDNCResource(DelegateExecution execution) {
+    void prepareUpdateAfterDeleteSDNCResource(DelegateExecution execution) {
         logger.debug(" *** prepareUpdateAfterDeleteSDNCResource *** ")
         String resourceInput = execution.getVariable(Prefix + "resourceInput");
         ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
@@ -546,7 +546,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor {
         logger.debug(" ***** Exit prepareUpdateAfterDeleteSDNCResource *****")
     }
 
-    public void postDeleteSDNCCall(DelegateExecution execution){
+    void postDeleteSDNCCall(DelegateExecution execution){
         logger.info(" ***** Started postDeleteSDNCCall *****")
         String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode")
         String responseObj = execution.getVariable(Prefix + "SuccessIndicator")
@@ -555,7 +555,7 @@ public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor {
         logger.info(" ***** Exit postDeleteSDNCCall *****")
     }
 
-    public void sendSyncResponse (DelegateExecution execution) {
+    void sendSyncResponse (DelegateExecution execution) {
         logger.debug( " *** sendSyncResponse *** ")
 
         try {
index 9b269c7..642609a 100644 (file)
@@ -63,14 +63,14 @@ public class DeleteVFCNSResource extends AbstractServiceTaskProcessor {
         logger.info(" ***** end preProcessRequest *****")
     }
 
-    public void postProcessRequest (DelegateExecution execution) {
+    void postProcessRequest (DelegateExecution execution) {
         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
         logger.info(" ***** start postProcessRequest *****")
 
         logger.info(" ***** end postProcessRequest *****")
     }
 
-    public void sendSyncResponse (DelegateExecution execution) {
+    void sendSyncResponse (DelegateExecution execution) {
         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
         logger.debug( " *** sendSyncResponse *** ")
 
index fff2503..324e6b4 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -19,9 +19,9 @@
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
-package org.onap.so.bpmn.infrastructure.scripts;
+package org.onap.so.bpmn.infrastructure.scripts
 
-import static org.apache.commons.lang3.StringUtils.*;
+import static org.apache.commons.lang3.StringUtils.*
 
 import org.onap.so.bpmn.core.domain.ServiceDecomposition
 import org.onap.so.bpmn.core.domain.Resource
@@ -52,7 +52,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor {
        String Prefix="DCMPMDV_"
        ExceptionUtil exceptionUtil = new ExceptionUtil()
        JsonUtils jsonUtil = new JsonUtils()
-    private static final Logger logger = LoggerFactory.getLogger( DoCompareModelVersions.class);
+    private static final Logger logger = LoggerFactory.getLogger( DoCompareModelVersions.class)
 
        public void preProcessRequest (DelegateExecution execution) {
                def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
@@ -196,8 +196,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor {
         ServiceDecomposition serviceDecomposition_Target = execution.getVariable("serviceDecomposition_Target")
         ServiceDecomposition serviceDecomposition_Original = execution.getVariable("serviceDecomposition_Original")
 
-        List<Resource> allSR_target = serviceDecomposition_Target.getServiceResources();
-        List<Resource> allSR_original = serviceDecomposition_Original.getServiceResources();
+        List<Resource> allSR_target = serviceDecomposition_Target.getServiceResources()
+        List<Resource> allSR_original = serviceDecomposition_Original.getServiceResources()
 
         List<Resource> addResourceList = new ArrayList<String>()
         List<Resource> delResourceList = new ArrayList<String>()
@@ -214,8 +214,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor {
                 if(rc_o.getModelInfo().getModelUuid() == muuid
                 && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid
                 && rc_o.getModelInfo().getModelCustomizationUuid() == mCuuid) {
-                    addResourceList.remove(rc_t);
-                    delResourceList.remove(rc_o);
+                    addResourceList.remove(rc_t)
+                    delResourceList.remove(rc_o)
                 }
             }
         }
index 0191439..9d8b953 100644 (file)
@@ -7,7 +7,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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,9 +26,9 @@ import com.fasterxml.jackson.databind.ObjectMapper
 import com.fasterxml.jackson.databind.SerializationFeature
 
 import org.onap.so.logger.LoggingAnchor
-import org.onap.so.logger.ErrorCode;
+import org.onap.so.logger.ErrorCode
 
-import static org.apache.commons.lang3.StringUtils.*;
+import static org.apache.commons.lang3.StringUtils.*
 
 import javax.ws.rs.NotFoundException
 
@@ -83,7 +83,7 @@ import org.onap.so.bpmn.core.UrnPropertiesReader
  *
  */
 public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( DoCreateE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( DoCreateE2EServiceInstance.class)
 
 
        String Prefix="DCRESI_"
@@ -165,7 +165,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                        execution.setVariable("serviceInstanceData", si)
 
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex){
                        msg = "Exception in preProcessRequest " + ex.getMessage()
                        logger.info(msg)
@@ -210,7 +210,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
        //we need a service plugin platform here.
        ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
        String uuiRequest = execution.getVariable("uuiRequest")
-       String newUuiRequest = ServicePluginFactory.getInstance().preProcessService(serviceDecomposition, uuiRequest);
+       String newUuiRequest = ServicePluginFactory.getInstance().preProcessService(serviceDecomposition, uuiRequest)
        execution.setVariable("uuiRequest", newUuiRequest)
     }
 
@@ -218,7 +218,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
        //we need a service plugin platform here.
        ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
        String uuiRequest = execution.getVariable("uuiRequest")
-       String newUuiRequest = ServicePluginFactory.getInstance().doServiceHoming(serviceDecomposition, uuiRequest);
+       String newUuiRequest = ServicePluginFactory.getInstance().doServiceHoming(serviceDecomposition, uuiRequest)
        execution.setVariable("uuiRequest", newUuiRequest)
     }
 
@@ -254,7 +254,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                                }
                        }
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex) {
                        msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage()
                        logger.info(msg)
@@ -276,7 +276,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                        client.create(uri, si)
 
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex) {
                        //start rollback set up
                        RollbackData rollbackData = new RollbackData()
@@ -310,11 +310,11 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                                AAIResultWrapper aaiResult = client.get(uri,NotFoundException.class)
                                Map<String, Object> result = aaiResult.asMap()
                                List<Object> resources =
-                                               (List<Object>) result.getOrDefault("result-data", Collections.emptyList());
+                                               (List<Object>) result.getOrDefault("result-data", Collections.emptyList())
                                if(resources.size()>0) {
                                        String relationshipUrl = ((Map<String, Object>) resources.get(0)).get("resource-link")
 
-                                       final Relationship body = new Relationship();
+                                       final Relationship body = new Relationship()
                                        body.setRelatedLink(relationshipUrl)
 
                                        createRelationShipInAAI(execution, body)
@@ -329,7 +329,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
 
 
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex) {
 
                        msg = "Exception in DoCreateE2EServiceInstance.createCustomRelationship. " + ex.getMessage()
@@ -349,7 +349,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                        client.create(uri, relationship)
 
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex) {
 
                        msg = "Exception in DoCreateE2EServiceInstance.createRelationShipInAAI. " + ex.getMessage()
@@ -362,9 +362,9 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
 
        private String isNeedProcessCustomRelationship(String uuiRequest) {
                String requestInput = jsonUtil.getJsonValue(uuiRequest, "service.parameters.requestInputs")
-               Map<String, String> requestInputObject = getJsonObject(requestInput, Map.class);
+               Map<String, String> requestInputObject = getJsonObject(requestInput, Map.class)
                if (requestInputObject == null) {
-                       return null;
+                       return null
                }
 
                Optional<Map.Entry> firstKey =
@@ -380,15 +380,15 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
        }
 
        private static <T> T getJsonObject(String jsonstr, Class<T> type) {
-               ObjectMapper mapper = new ObjectMapper();
-               mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
+               ObjectMapper mapper = new ObjectMapper()
+               mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true)
                try {
-                       return mapper.readValue(jsonstr, type);
+                       return mapper.readValue(jsonstr, type)
                } catch (IOException e) {
                        logger.error("{} {} fail to unMarshal json", MessageEnum.RA_NS_EXC.toString(),
-                                       ErrorCode.BusinessProcesssError.getValue(), e);
+                                       ErrorCode.BusinessProcesssError.getValue(), e)
                }
-               return null;
+               return null
        }
 
 
@@ -409,7 +409,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                        execution.setVariable("serviceInstanceName", si.get().getServiceInstanceName())
 
                }catch(BpmnError e) {
-                       throw e;
+                       throw e
                }catch(Exception ex) {
                        String msg = "Internal Error in getServiceInstance: " + ex.getMessage()
                        exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
@@ -449,7 +449,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                                }
                        }
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex) {
                        msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage()
                        logger.info(msg)
@@ -462,12 +462,12 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("preProcessRollback ")
                try {
 
-                       Object workflowException = execution.getVariable("WorkflowException");
+                       Object workflowException = execution.getVariable("WorkflowException")
 
                        if (workflowException instanceof WorkflowException) {
                                logger.info("Prev workflowException: " + workflowException.getErrorMessage())
-                               execution.setVariable("prevWorkflowException", workflowException);
-                               //execution.setVariable("WorkflowException", null);
+                               execution.setVariable("prevWorkflowException", workflowException)
+                               //execution.setVariable("WorkflowException", null)
                        }
                } catch (BpmnError e) {
                        logger.info("BPMN Error during preProcessRollback")
@@ -482,15 +482,15 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("postProcessRollback ")
                String msg = ""
                try {
-                       Object workflowException = execution.getVariable("prevWorkflowException");
+                       Object workflowException = execution.getVariable("prevWorkflowException")
                        if (workflowException instanceof WorkflowException) {
                                logger.info("Setting prevException to WorkflowException: ")
-                               execution.setVariable("WorkflowException", workflowException);
+                               execution.setVariable("WorkflowException", workflowException)
                        }
                        execution.setVariable("rollbackData", null)
                } catch (BpmnError b) {
                        logger.info("BPMN Error during postProcessRollback")
-                       throw b;
+                       throw b
                } catch(Exception ex) {
                        msg = "Exception in postProcessRollback. " + ex.getMessage()
                        logger.info(msg)
@@ -547,19 +547,19 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
         }catch(Exception e){
             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                        "Exception Occured Processing preInitResourcesOperStatus.", "BPMN",
-                                       ErrorCode.UnknownError.getValue(), e);
+                                       ErrorCode.UnknownError.getValue(), e)
             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
         }
         logger.trace("COMPLETED preInitResourcesOperStatus Process ")
        }
 
-       // if site location is in local Operator, create all resources in local ONAP;
+       // if site location is in local Operator, create all resources in local ONAP
        // if site location is in 3rd Operator, only process sp-partner to create all resources in 3rd ONAP
        public void doProcessSiteLocation(DelegateExecution execution){
                logger.trace("======== Start doProcessSiteLocation Process ======== ")
                ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
                String uuiRequest = execution.getVariable("uuiRequest")
-               uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest);
+               uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest)
                execution.setVariable("uuiRequest", uuiRequest)
                execution.setVariable("serviceDecomposition", serviceDecomposition)
 
@@ -571,7 +571,7 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("======== Start doTPResourcesAllocation Process ======== ")
                ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
                String uuiRequest = execution.getVariable("uuiRequest")
-               uuiRequest = ServicePluginFactory.getInstance().doTPResourcesAllocation(execution, uuiRequest);
+               uuiRequest = ServicePluginFactory.getInstance().doTPResourcesAllocation(execution, uuiRequest)
                execution.setVariable("uuiRequest", uuiRequest)
                logger.trace("======== COMPLETED doTPResourcesAllocation Process ======== ")
        }
index b1356b9..bc26aa1 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -72,13 +72,13 @@ import java.lang.reflect.Type
  * @param - WorkflowException
  */
 public class DoCreateResources extends AbstractServiceTaskProcessor{
-    private static final Logger logger = LoggerFactory.getLogger( DoCreateResources.class);
+    private static final Logger logger = LoggerFactory.getLogger( DoCreateResources.class)
 
     ExceptionUtil exceptionUtil = new ExceptionUtil()
     JsonUtils jsonUtil = new JsonUtils()
     CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
 
-    public void preProcessRequest(DelegateExecution execution) {
+     void preProcessRequest(DelegateExecution execution) {
         logger.trace("preProcessRequest ")
         String msg = ""
 
@@ -95,7 +95,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         logger.trace("Exit preProcessRequest ")
     }
 
-    public void sequenceResoure(DelegateExecution execution) {
+     void sequenceResoure(DelegateExecution execution) {
         logger.trace("Start sequenceResoure Process ")
 
         String incomingRequest = execution.getVariable("uuiRequest")
@@ -170,7 +170,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         String isContainsWanResource = networkResourceList.isEmpty() ? "false" : "true"
         //if no networkResource, get SDNC config from properties file
         if( "false".equals(isContainsWanResource)) {
-            String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need";
+            String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need"
             isContainsWanResource = BPMNProperties.getProperty(serviceNeedSDNC, isContainsWanResource)
         }
 
@@ -181,7 +181,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         logger.trace("COMPLETED sequenceResoure Process ")
     }
 
-    public prepareServiceTopologyRequest(DelegateExecution execution) {
+     void prepareServiceTopologyRequest(DelegateExecution execution) {
 
         logger.trace("======== Start prepareServiceTopologyRequest Process ======== ")
 
@@ -201,7 +201,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         logger.trace("======== End prepareServiceTopologyRequest Process ======== ")
     }
 
-    public void getCurrentResoure(DelegateExecution execution){
+     void getCurrentResoure(DelegateExecution execution){
         logger.trace("Start getCurrentResoure Process ")
         def currentIndex = execution.getVariable("currentResourceIndex")
         List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")
@@ -211,7 +211,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         logger.trace("COMPLETED getCurrentResource Process ")
     }
 
-    public void parseNextResource(DelegateExecution execution){
+     void parseNextResource(DelegateExecution execution){
         logger.trace("Start parseNextResource Process ")
         def currentIndex = execution.getVariable("currentResourceIndex")
         def nextIndex =  currentIndex + 1
@@ -225,7 +225,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         logger.trace("COMPLETED parseNextResource Process ")
     }
 
-    public void prepareResourceRecipeRequest(DelegateExecution execution){
+     void prepareResourceRecipeRequest(DelegateExecution execution){
         logger.trace("Start prepareResourceRecipeRequest Process ")
         ResourceInput resourceInput = new ResourceInput()
         String serviceInstanceName = execution.getVariable("serviceInstanceName")
@@ -242,7 +242,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         resourceInput.setServiceType(serviceType)
         resourceInput.setServiceInstanceId(serviceInstanceId)
         resourceInput.setOperationId(operationId)
-        resourceInput.setOperationType(operationType);
+        resourceInput.setOperationType(operationType)
         def currentIndex = execution.getVariable("currentResourceIndex")
         List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")
         Resource currentResource = sequencedResourceList.get(currentIndex)
@@ -284,7 +284,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         logger.trace("COMPLETED prepareResourceRecipeRequest Process ")
     }
 
-    public void executeResourceRecipe(DelegateExecution execution){
+     void executeResourceRecipe(DelegateExecution execution){
         logger.trace("Start executeResourceRecipe Process ")
 
         try {
@@ -338,7 +338,7 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         }
     }
 
-    public void postConfigRequest(DelegateExecution execution){
+     void postConfigRequest(DelegateExecution execution){
         //now do noting
         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
         for (VnfResource resource : serviceDecomposition.vnfResources) {
@@ -346,4 +346,4 @@ public class DoCreateResources extends AbstractServiceTaskProcessor{
         }
         execution.setVariable("serviceDecomposition", serviceDecomposition)
     }
-}
\ No newline at end of file
+}
index bf52b11..64d9827 100644 (file)
@@ -83,7 +83,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
        JsonUtils jsonUtil = new JsonUtils()
        CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()
 
-       public void preProcessRequest (DelegateExecution execution) {
+       void preProcessRequest (DelegateExecution execution) {
                def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
                String msg = ""
                logger.trace("preProcessRequest")
@@ -286,7 +286,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit preProcessRequest")
        }
 
-       public void getAAICustomerById (DelegateExecution execution) {
+       void getAAICustomerById (DelegateExecution execution) {
                // https://{aaiEP}/aai/v8/business/customers/customer/{globalCustomerId}
                try {
 
@@ -306,7 +306,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
 
        }
 
-       public void putServiceInstance(DelegateExecution execution) {
+       void putServiceInstance(DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("putServiceInstance")
                String msg = ""
@@ -380,7 +380,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit putServiceInstance")
        }
 
-       public void preProcessSDNCAssignRequest(DelegateExecution execution) {
+       void preProcessSDNCAssignRequest(DelegateExecution execution) {
                def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
                String msg = ""
                logger.trace("preProcessSDNCAssignRequest")
@@ -479,7 +479,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit preProcessSDNCAssignRequest")
        }
 
-       public void postProcessSDNCAssign (DelegateExecution execution) {
+       void postProcessSDNCAssign (DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("postProcessSDNCAssign")
                try {
@@ -518,7 +518,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit postProcessSDNCAssign")
        }
 
-       public void postProcessAAIGET2(DelegateExecution execution) {
+       void postProcessAAIGET2(DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("postProcessAAIGET2")
                String msg = ""
@@ -561,7 +561,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit postProcessAAIGET2")
        }
 
-       public void preProcessRollback (DelegateExecution execution) {
+       void preProcessRollback (DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("preProcessRollback")
                try {
@@ -582,7 +582,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit preProcessRollback")
        }
 
-       public void postProcessRollback (DelegateExecution execution) {
+       void postProcessRollback (DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("postProcessRollback")
                String msg = ""
@@ -603,7 +603,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit postProcessRollback")
        }
 
-       public void createProject(DelegateExecution execution) {
+       void createProject(DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("createProject")
 
@@ -631,7 +631,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
                logger.trace("Exit createProject")
        }
 
-       public void createOwningEntity(DelegateExecution execution) {
+       void createOwningEntity(DelegateExecution execution) {
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
                logger.trace("createOwningEntity")
                String msg = "";
@@ -679,7 +679,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor {
        //     Build Error Section
        // *******************************
 
-       public void processJavaException(DelegateExecution execution){
+       void processJavaException(DelegateExecution execution){
                def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
 
                try{
index 1eeba49..af82bf0 100644 (file)
@@ -69,7 +69,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso
 
        String Prefix="DCRESIRB_"
 
-       public void preProcessRequest(DelegateExecution execution) {
+       void preProcessRequest(DelegateExecution execution) {
                def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
                execution.setVariable("prefix",Prefix)
                String msg = ""
@@ -139,7 +139,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso
                logger.trace("Exit preProcessRequest")
        }
 
-       public void validateSDNCResponse(DelegateExecution execution, String response, String method) {
+       void validateSDNCResponse(DelegateExecution execution, String response, String method) {
 
                logger.trace("validateSDNCResponse")
                String msg = ""
@@ -172,7 +172,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso
                logger.trace("Exit validateSDNCResponse")
        }
 
-       public void postProcessRequest(DelegateExecution execution) {
+       void postProcessRequest(DelegateExecution execution) {
 
                logger.trace("postProcessRequest")
                String msg = ""
@@ -206,7 +206,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso
 
        }
 
-       public void processRollbackException(DelegateExecution execution){
+       void processRollbackException(DelegateExecution execution){
 
                logger.trace("processRollbackException")
                try{
@@ -224,7 +224,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso
                logger.debug("Exit processRollbackException")
        }
 
-       public void processRollbackJavaException(DelegateExecution execution){
+       void processRollbackJavaException(DelegateExecution execution){
 
                logger.trace("processRollbackJavaException")
                try{
index eab99df..1517a33 100644 (file)
@@ -61,7 +61,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces
      * generate the nsOperationKey
      * generate the nsParameters
      */
-    public void preProcessRequest (DelegateExecution execution) {
+    void preProcessRequest (DelegateExecution execution) {
        String msg = ""
        logger.trace("preProcessRequest()")
        try {
@@ -130,7 +130,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces
     /**
      * create NS task
      */
-    public void createNetworkService(DelegateExecution execution) {
+    void createNetworkService(DelegateExecution execution) {
         logger.trace("createNetworkService")
         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
         String nsOperationKey = execution.getVariable("nsOperationKey");
@@ -157,7 +157,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces
     /**
      * instantiate NS task
      */
-    public void instantiateNetworkService(DelegateExecution execution) {
+    void instantiateNetworkService(DelegateExecution execution) {
         logger.trace("instantiateNetworkService")
         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
         String nsOperationKey = execution.getVariable("nsOperationKey");
@@ -186,7 +186,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces
     /**
      * query NS task
      */
-    public void queryNSProgress(DelegateExecution execution) {
+    void queryNSProgress(DelegateExecution execution) {
         logger.trace("queryNSProgress")
         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
         String jobId = execution.getVariable("jobId")
@@ -206,7 +206,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces
     /**
      * delay 5 sec
      */
-    public void timeDelay(DelegateExecution execution) {
+    void timeDelay(DelegateExecution execution) {
         try {
             Thread.sleep(5000);
         } catch(InterruptedException e) {
@@ -217,7 +217,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces
     /**
      * finish NS task
      */
-    public void addNSRelationship(DelegateExecution execution) {
+    void addNSRelationship(DelegateExecution execution) {
         logger.trace("addNSRelationship")
         String nsInstanceId = execution.getVariable("nsInstanceId")
         if(nsInstanceId == null || nsInstanceId == ""){
index cf3a0ef..a88beca 100644 (file)
@@ -7,7 +7,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -25,7 +25,7 @@ package org.onap.so.bpmn.infrastructure.scripts
 import org.onap.so.logger.LoggingAnchor
 import org.onap.so.logger.ErrorCode
 
-import static org.apache.commons.lang3.StringUtils.*;
+import static org.apache.commons.lang3.StringUtils.*
 
 import javax.xml.parsers.DocumentBuilder
 import javax.xml.parsers.DocumentBuilderFactory
@@ -33,8 +33,8 @@ import javax.xml.parsers.DocumentBuilderFactory
 import org.apache.commons.lang3.*
 import org.camunda.bpm.engine.delegate.BpmnError
 import org.camunda.bpm.engine.delegate.DelegateExecution
-import org.json.JSONArray;
-import org.json.JSONObject;
+import org.json.JSONArray
+import org.json.JSONObject
 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
 import org.onap.so.bpmn.common.scripts.ExceptionUtil
 import org.onap.so.bpmn.common.scripts.MsoUtils
@@ -44,7 +44,7 @@ import org.onap.so.bpmn.core.json.JsonUtils
 import org.onap.so.logger.MessageEnum
 import org.slf4j.Logger
 import org.slf4j.LoggerFactory
-import org.springframework.web.util.UriUtils;
+import org.springframework.web.util.UriUtils
 import org.w3c.dom.Document
 import org.w3c.dom.Element
 import org.w3c.dom.Node
@@ -79,7 +79,7 @@ import groovy.json.*
  * Rollback - Deferred
  */
 public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
-    private static final Logger logger = LoggerFactory.getLogger( DoCustomDeleteE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( DoCustomDeleteE2EServiceInstance.class)
 
 
        String Prefix="DDELSI_"
@@ -151,7 +151,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
                        execution.setVariable("siParamsXml", siParamsXml)
 
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex){
                        msg = "Exception in preProcessRequest " + ex.getMessage()
                        logger.info(msg)
@@ -271,7 +271,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
                        logger.info("sdncDelete:\n" + sdncDelete)
 
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch(Exception ex) {
                        msg = "Exception in preProcessSDNCDelete. " + ex.getMessage()
                        logger.info(msg)
@@ -302,7 +302,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
                                exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg)
                        }
                } catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch(Exception ex) {
                        msg = "Exception in postProcessSDNC " + method + " Exception:" + ex.getMessage()
                        logger.info(msg)
@@ -337,8 +337,8 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
                                        //Confirm there are no related service instances (vnf/network or volume)
                                        if (utils.nodeExists(siData, "relationship-list")) {
                                                logger.info("SI Data relationship-list exists:")
-                                               InputSource source = new InputSource(new StringReader(siData));
-                                               DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
+                                               InputSource source = new InputSource(new StringReader(siData))
+                                               DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance()
                                                DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
                                                Document serviceXml = docBuilder.parse(source)
                                                serviceXml.getDocumentElement().normalize()
@@ -433,7 +433,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
                                logger.info("Service-instance NOT found in AAI. Silent Success")
                        }
                }catch (BpmnError e) {
-                       throw e;
+                       throw e
                } catch (Exception ex) {
                        msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage()
                        logger.info(msg)
@@ -452,7 +452,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
                        String serviceType = execution.getVariable("serviceType")
                        String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
-                       AAIResourcesClient resourceClient = new AAIResourcesClient();
+                       AAIResourcesClient resourceClient = new AAIResourcesClient()
                        AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId)
                        resourceClient.delete(serviceInstanceUri)
 
@@ -535,7 +535,7 @@ public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcess
         }catch(Exception e){
                        logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
                                        "Exception Occured Processing preInitResourcesOperStatus.", "BPMN",
-                                       ErrorCode.UnknownError.getValue(), e);
+                                       ErrorCode.UnknownError.getValue(), e)
             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
         }
         logger.trace("COMPLETED preInitResourcesOperStatus Process ")
index 481a79a..34ea20b 100644 (file)
@@ -6,7 +6,7 @@
  * ================================================================================
  * Modifications Copyright (c) 2019 Samsung
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -90,7 +90,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
        String Prefix="DDEESI_"
     ExceptionUtil exceptionUtil = new ExceptionUtil()
     JsonUtils jsonUtil = new JsonUtils()
-    private static final Logger logger = LoggerFactory.getLogger( DoDeleteE2EServiceInstance.class);
+    private static final Logger logger = LoggerFactory.getLogger( DoDeleteE2EServiceInstance.class)
 
 
     public void preProcessRequest (DelegateExecution execution) {
@@ -158,7 +158,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
             execution.setVariable("siParamsXml", siParamsXml)
 
         } catch (BpmnError e) {
-            throw e;
+            throw e
         } catch (Exception ex){
             msg = "Exception in preProcessRequest " + ex.getMessage()
             logger.error(msg)
@@ -243,7 +243,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
             // for sp-partner and others
             else if (eKey.endsWith("-id")) {
                 jObj.put("resourceInstanceId", eValue)
-                String resourceName = rt + eValue;
+                String resourceName = rt + eValue
                 jObj.put("resourceType", resourceName)
             }
             jObj.put("resourceLinkUrl", rl)
@@ -520,12 +520,12 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
         if (StringUtils.containsIgnoreCase(obj.get("resourceType"), modelName)) {
             resource.setResourceId(obj.get("resourceInstanceId"))
             //deleteRealResourceList.add(resource)
-            matches = true;
+            matches = true
         } else if (modelCustomizationUuid.equals(obj.get("modelCustomizationId")) || modelUuid.equals(obj.get("model-version-id")) ) {
             resource.setResourceId(obj.get("resourceInstanceId"))
             resource.setResourceInstanceName(obj.get("resourceType"))
             //deleteRealResourceList.add(resource)
-            matches = true;
+            matches = true
         }
         return matches
     }
@@ -646,7 +646,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
             String serviceType = execution.getVariable("serviceType")
             String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
-            AAIResourcesClient resourceClient = new AAIResourcesClient();
+            AAIResourcesClient resourceClient = new AAIResourcesClient()
             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId)
             resourceClient.delete(serviceInstanceUri)
 
index cbeb1d3..97eb3b3 100644 (file)
@@ -4,7 +4,7 @@
  * ================================================================================
  * Copyright (C) 2017 - 2019 Huawei Intellectual Property. All rights reserved.
  * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * 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
  *
@@ -34,7 +34,7 @@ import org.slf4j.Logger
 import org.slf4j.LoggerFactory
 
 public class HandlePNF extends AbstractServiceTaskProcessor{
-    private static final Logger logger = LoggerFactory.getLogger( HandlePNF.class);
+    private static final Logger logger = LoggerFactory.getLogger( HandlePNF.class)
 
     ExceptionUtil exceptionUtil = new ExceptionUtil()
     JsonUtils jsonUtil = new JsonUtils()
@@ -95,7 +95,7 @@ public class HandlePNF extends AbstractServiceTaskProcessor{
                                <statusDescription>${msoUtils.xmlEscape(statusDescription)}</statusDescription>
                     </ns:updateResourceOperationStatus>
                 </soapenv:Body>
-                </soapenv:Envelope>""";
+                </soapenv:Envelope>"""
         logger.debug("body: "+body)
         setProgressUpdateVariables(execution, body)
         logger.debug("exit postProcess for HandlePNF")
index d67e6ef..a011346 100644 (file)
@@ -45,7 +45,7 @@ public class ConfigCheckerDelegate implements JavaDelegate {
     private Logger logger = LoggerFactory.getLogger(ConfigCheckerDelegate.class);
 
     // ERROR CODE for variable not found in the delegation Context
-    private static int ERROR_CODE = 601;
+    private static final int ERROR_CODE = 601;
 
     @Autowired
     protected ExceptionBuilder exceptionUtil;
index 357b571..48061db 100644 (file)
@@ -90,7 +90,7 @@ public class PnfEventReadyDmaapClient implements DmaapClient {
     @Override
     public synchronized Runnable unregister(String pnfCorrelationId) {
         logger.debug("unregistering from pnf ready dmaap event for pnf correlation id: {}", pnfCorrelationId);
-        Runnable runnable = runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
+        Runnable runnable = pnfCorrelationIdToThreadMap.remove(pnfCorrelationId);
         synchronized (updateInfoMap) {
             for (int i = updateInfoMap.size() - 1; i >= 0; i--) {
                 if (!updateInfoMap.get(i).containsKey("pnfCorrelationId"))
index 1abe1cc..2f05eb5 100644 (file)
@@ -98,12 +98,17 @@ public class ServicePluginFactory {
             new String[] {VS_MONITORED, VS_UNMONITORED, TS_MONITORED, TS_UNMONITORED};
 
     static {
-        try (InputStream is = ClassLoader.class.getResourceAsStream("/application.properties")) {
-            Properties prop = new Properties();
-            prop.load(is);
-            OOF_DEFAULT_ENDPOINT = prop.getProperty("oof.default.endpoint");
-            THIRD_SP_DEFAULT_ENDPOINT = prop.getProperty("third.sp.default.endpoint");
-            INVENTORY_OSS_DEFAULT_ENDPOINT = prop.getProperty("inventory.oss.default.endpoint");
+        try {
+            InputStream is = ClassLoader.class.getResourceAsStream("/application.properties");
+            if (null != is) {
+                Properties prop = new Properties();
+                prop.load(is);
+                OOF_DEFAULT_ENDPOINT = prop.getProperty("oof.default.endpoint");
+                THIRD_SP_DEFAULT_ENDPOINT = prop.getProperty("third.sp.default.endpoint");
+                INVENTORY_OSS_DEFAULT_ENDPOINT = prop.getProperty("inventory.oss.default.endpoint");
+            } else {
+                logger.error("Failed to load property file, Either property file is missing or empty!");
+            }
         } catch (IOException e) {
             logger.error("Failed to load property file!");
         }
@@ -858,23 +863,23 @@ public class ServicePluginFactory {
 
             HttpClient client = HttpClientBuilder.create().build();
 
-            if ("POST".equals(methodType.toUpperCase())) {
+            if ("POST".equalsIgnoreCase(methodType)) {
                 HttpPost httpPost = new HttpPost(msbUrl);
                 httpPost.setConfig(requestConfig);
                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
                 method = httpPost;
-            } else if ("PUT".equals(methodType.toUpperCase())) {
+            } else if ("PUT".equalsIgnoreCase(methodType)) {
                 HttpPut httpPut = new HttpPut(msbUrl);
                 httpPut.setConfig(requestConfig);
                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
                 method = httpPut;
-            } else if ("GET".equals(methodType.toUpperCase())) {
+            } else if ("GET".equalsIgnoreCase(methodType)) {
                 HttpGet httpGet = new HttpGet(msbUrl);
                 httpGet.setConfig(requestConfig);
                 httpGet.addHeader("X-FromAppId", "MSO");
                 httpGet.addHeader("Accept", "application/json");
                 method = httpGet;
-            } else if ("DELETE".equals(methodType.toUpperCase())) {
+            } else if ("DELETE".equalsIgnoreCase(methodType)) {
                 HttpDelete httpDelete = new HttpDelete(msbUrl);
                 httpDelete.setConfig(requestConfig);
                 method = httpDelete;
index f7708b6..f933277 100644 (file)
@@ -27,6 +27,7 @@ import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
 import org.onap.so.logger.LoggingAnchor;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.http.client.methods.CloseableHttpResponse;
@@ -41,7 +42,6 @@ import org.json.JSONObject;
 import org.onap.msb.sdk.discovery.common.RouteException;
 import org.onap.msb.sdk.httpclient.RestServiceCreater;
 import org.onap.msb.sdk.httpclient.msb.MSBServiceClient;
-import org.onap.so.bpmn.core.BaseTask;
 import org.onap.so.bpmn.core.UrnPropertiesReader;
 import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.GenericResourceApi;
 import org.onap.so.db.request.beans.ResourceOperationStatus;
@@ -56,7 +56,7 @@ import com.fasterxml.jackson.annotation.JsonInclude;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 
-public abstract class AbstractSdncOperationTask extends BaseTask {
+public abstract class AbstractSdncOperationTask implements JavaDelegate {
 
     private static final Logger logger = LoggerFactory.getLogger(AbstractSdncOperationTask.class);
 
@@ -284,7 +284,7 @@ public abstract class AbstractSdncOperationTask extends BaseTask {
             logger.info("exception: AbstractSdncOperationTask.updateProgress fail!");
             logger.error("exception: AbstractSdncOperationTask.updateProgress fail:", exception);
             logger.error(LoggingAnchor.FIVE, MessageEnum.GENERAL_EXCEPTION.toString(),
-                    " updateProgress catch exception: ", this.getTaskName(), ErrorCode.UnknownError.getValue(),
+                    " updateProgress catch exception: ", ErrorCode.UnknownError.getValue(),
                     exception.getClass().toString());
         }
     }
index 5b7f3bb..16bd194 100644 (file)
@@ -22,12 +22,12 @@ package org.onap.so.bpmn.infrastructure.workflow.serviceTask;
 
 import org.apache.commons.lang3.StringUtils;
 import org.camunda.bpm.engine.delegate.DelegateExecution;
-import org.onap.so.bpmn.core.BaseTask;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
 import org.onap.so.db.request.beans.ResourceOperationStatus;
 import org.springframework.stereotype.Component;
 
 @Component
-public class SdncUnderlayVpnPreprocessTask extends BaseTask {
+public class SdncUnderlayVpnPreprocessTask implements JavaDelegate {
     public static final String RESOURCE_OPER_TYPE = "resourceOperType";
 
     @Override
index 68cfd48..bd60fbe 100644 (file)
@@ -71,6 +71,7 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.stereotype.Component;
+import com.google.common.base.Strings;
 
 @Component
 public class AAICreateTasks {
@@ -184,24 +185,35 @@ public class AAICreateTasks {
             ServiceInstance serviceInstance =
                     extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
             OwningEntity owningEntity = serviceInstance.getOwningEntity();
-            String owningEntityId = owningEntity.getOwningEntityId();
-            String owningEntityName = owningEntity.getOwningEntityName();
-            if (owningEntityId == null || "".equals(owningEntityId)) {
-                String msg = "Exception in AAICreateOwningEntity. OwningEntityId is null.";
+            if (Strings.isNullOrEmpty(owningEntity.getOwningEntityId())
+                    && Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) {
+                String msg = "Exception in AAICreateOwningEntity. OwningEntityId and Name are null.";
                 execution.setVariable("ErrorCreateOEAAI", msg);
                 exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
+            } else if (Strings.isNullOrEmpty(owningEntity.getOwningEntityId())
+                    && !Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) {
+                if (aaiSIResources.existsOwningEntityName(owningEntity.getOwningEntityName())) {
+                    org.onap.aai.domain.yang.OwningEntity aaiEntity =
+                            aaiSIResources.getOwningEntityByName(owningEntity.getOwningEntityName());
+                    owningEntity.setOwningEntityId(aaiEntity.getOwningEntityId());
+                    owningEntity.setOwningEntityName(owningEntity.getOwningEntityName());
+                    aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance);
+                } else {
+                    owningEntity.setOwningEntityId(UUID.randomUUID().toString());
+                    aaiSIResources.createOwningEntityandConnectServiceInstance(owningEntity, serviceInstance);
+                }
             } else {
                 if (aaiSIResources.existsOwningEntity(owningEntity)) {
                     aaiSIResources.connectOwningEntityandServiceInstance(owningEntity, serviceInstance);
                 } else {
-                    if (owningEntityName == null || "".equals(owningEntityName)) {
+                    if (Strings.isNullOrEmpty(owningEntity.getOwningEntityName())) {
                         String msg =
                                 "Exception in AAICreateOwningEntity. Can't create an owningEntity with no owningEntityName.";
                         logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
                                 ErrorCode.UnknownError.getValue(), msg);
                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
                     } else {
-                        if (aaiSIResources.existsOwningEntityName(owningEntityName)) {
+                        if (aaiSIResources.existsOwningEntityName(owningEntity.getOwningEntityName())) {
                             String msg =
                                     "Exception in AAICreateOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)";
                             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg,
index a436f7b..9340609 100644 (file)
@@ -59,9 +59,18 @@ public class ExecuteActivity implements JavaDelegate {
     private static final String VNF_ID = "vnfId";
     private static final String SERVICE_INSTANCE_ID = "serviceInstanceId";
     private static final String WORKFLOW_SYNC_ACK_SENT = "workflowSyncAckSent";
+    private static final String BUILDING_BLOCK = "buildingBlock";
+    private static final String EXECUTE_BUILDING_BLOCK = "ExecuteBuildingBlock";
+    private static final String RETRY_COUNT = "retryCount";
+    private static final String A_LA_CARTE = "aLaCarte";
+    private static final String SUPPRESS_ROLLBACK = "suppressRollback";
+    private static final String WORKFLOW_EXCEPTION = "WorkflowException";
+    private static final String HANDLING_CODE = "handlingCode";
+    private static final String ABORT_HANDLING_CODE = "Abort";
 
     private static final String SERVICE_TASK_IMPLEMENTATION_ATTRIBUTE = "implementation";
     private static final String ACTIVITY_PREFIX = "activity:";
+    private static final String EXECUTE_ACTIVITY_ERROR_MESSAGE = "ExecuteActivityErrorMessage";
 
     private ObjectMapper mapper = new ObjectMapper();
 
@@ -75,7 +84,8 @@ public class ExecuteActivity implements JavaDelegate {
     @Override
     public void execute(DelegateExecution execution) throws Exception {
         final String requestId = (String) execution.getVariable(G_REQUEST_ID);
-
+        WorkflowException workflowException = null;
+        String handlingCode = null;
         try {
             Boolean workflowSyncAckSent = (Boolean) execution.getVariable(WORKFLOW_SYNC_ACK_SENT);
             if (workflowSyncAckSent == null || workflowSyncAckSent == false) {
@@ -95,31 +105,44 @@ public class ExecuteActivity implements JavaDelegate {
             ExecuteBuildingBlock executeBuildingBlock = buildExecuteBuildingBlock(execution, requestId, buildingBlock);
 
             Map<String, Object> variables = new HashMap<>();
-            variables.put("buildingBlock", executeBuildingBlock);
-            variables.put(G_REQUEST_ID, requestId);
-            variables.put("retryCount", 1);
-            variables.put("aLaCarte", true);
-            variables.put("suppressRollback", true);
 
-            execution.getVariables().forEach((key, value) -> {
-                if (value instanceof Serializable) {
-                    variables.put(key, (Serializable) value);
-                }
-            });
+            if (execution.getVariables() != null) {
+                execution.getVariables().forEach((key, value) -> {
+                    if (value instanceof Serializable) {
+                        variables.put(key, (Serializable) value);
+                    }
+                });
+            }
+
+            variables.put(BUILDING_BLOCK, executeBuildingBlock);
+            variables.put(G_REQUEST_ID, requestId);
+            variables.put(RETRY_COUNT, 1);
+            variables.put(A_LA_CARTE, true);
+            variables.put(SUPPRESS_ROLLBACK, true);
 
             ProcessInstanceWithVariables buildingBlockResult =
-                    runtimeService.createProcessInstanceByKey("ExecuteBuildingBlock").setVariables(variables)
+                    runtimeService.createProcessInstanceByKey(EXECUTE_BUILDING_BLOCK).setVariables(variables)
                             .executeWithVariablesInReturn();
             VariableMap variableMap = buildingBlockResult.getVariables();
 
-            WorkflowException workflowException = (WorkflowException) variableMap.get("WorklfowException");
+            workflowException = (WorkflowException) variableMap.get(WORKFLOW_EXCEPTION);
             if (workflowException != null) {
                 logger.error("Workflow exception is: {}", workflowException.getErrorMessage());
             }
-            execution.setVariable("WorkflowException", workflowException);
+
+            handlingCode = (String) variableMap.get(HANDLING_CODE);
+            logger.debug("Handling code: " + handlingCode);
+
+            execution.setVariable(WORKFLOW_EXCEPTION, workflowException);
         } catch (Exception e) {
             buildAndThrowException(execution, e.getMessage());
         }
+
+        if (workflowException != null && handlingCode != null && handlingCode.equals(ABORT_HANDLING_CODE)) {
+            logger.debug("Aborting execution of the custom workflow");
+            buildAndThrowException(execution, workflowException.getErrorMessage());
+        }
+
     }
 
     protected BuildingBlock buildBuildingBlock(String activityName) {
@@ -161,7 +184,7 @@ public class ExecuteActivity implements JavaDelegate {
 
     protected void buildAndThrowException(DelegateExecution execution, String msg) {
         logger.error(msg);
-        execution.setVariable("ExecuteActuvityErrorMessage", msg);
+        execution.setVariable(EXECUTE_ACTIVITY_ERROR_MESSAGE, msg);
         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
     }
 }
index f5bae2c..c3c0047 100644 (file)
 package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks;
 
 import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE;
+import java.io.IOException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import javax.net.ssl.SSLContext;
+import org.apache.http.client.HttpClient;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.ssl.SSLContextBuilder;
 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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.Resource;
+import org.springframework.http.client.BufferingClientHttpRequestFactory;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.web.client.RestTemplate;
 
 /**
@@ -40,13 +58,55 @@ import org.springframework.web.client.RestTemplate;
 @Configuration
 public class VnfmAdapterCreateVnfTaskConfiguration {
 
+    private static final Logger logger = LoggerFactory.getLogger(VnfmAdapterCreateVnfTaskConfiguration.class);
+
+    @Value("${rest.http.client.configuration.ssl.trustStore:#{null}}")
+    private Resource trustStore;
+
+    @Value("${rest.http.client.configuration.ssl.trustStorePassword:#{null}}")
+    private String trustStorePassword;
+
+    @Value("${rest.http.client.configuration.ssl.keyStore:#{null}}")
+    private Resource keyStoreResource;
+
+    @Value("${rest.http.client.configuration.ssl.keyStorePassword:#{null}}")
+    private String keyStorePassword;
+
     @Bean
     public HttpRestServiceProvider databaseHttpRestServiceProvider(
             @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate,
             @Autowired final VnfmBasicHttpConfigProvider etsiVnfmAdapter) {
+        if (trustStore != null) {
+            setTrustStore(restTemplate);
+        }
         return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider(etsiVnfmAdapter.getAuth()));
     }
 
+    private void setTrustStore(final RestTemplate restTemplate) {
+        SSLContext sslContext;
+        try {
+            if (keyStoreResource != null) {
+                KeyStore keystore = KeyStore.getInstance("pkcs12");
+                keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray());
+                sslContext =
+                        new SSLContextBuilder().loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray())
+                                .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build();
+            } else {
+                sslContext = new SSLContextBuilder()
+                        .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build();
+            }
+            logger.info("Setting truststore: {}", trustStore.getURL());
+            final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
+            final HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
+            final HttpComponentsClientHttpRequestFactory factory =
+                    new HttpComponentsClientHttpRequestFactory(httpClient);
+            restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory));
+        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException
+                | IOException | UnrecoverableKeyException exception) {
+            logger.error("Error reading truststore, TLS connection to VNFM will fail.", exception);
+        }
+    }
+
     private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate,
             final HttpHeadersProvider httpHeadersProvider) {
         return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider);
index eddcc94..127d21c 100644 (file)
 package org.onap.so.bpmn.infrastructure.appc.tasks;
 
 import java.util.HashMap;
+import java.util.List;
 import java.util.Optional;
 import org.onap.so.logger.LoggingAnchor;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.aai.domain.yang.Vserver;
 import org.onap.appc.client.lcm.model.Action;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -33,9 +37,14 @@ import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters;
 import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
+import org.onap.so.client.aai.AAIObjectType;
+import org.onap.so.client.aai.entities.AAIResultWrapper;
+import org.onap.so.client.aai.entities.Relationships;
+import org.onap.so.client.aai.entities.uri.AAIResourceUri;
 import org.onap.so.client.appc.ApplicationControllerAction;
 import org.onap.so.client.exception.BBObjectNotFoundException;
 import org.onap.so.client.exception.ExceptionBuilder;
+import org.onap.so.client.orchestration.AAIVnfResources;
 import org.onap.so.db.catalog.beans.ControllerSelectionReference;
 import org.onap.so.db.catalog.client.CatalogDbClient;
 import org.onap.so.logger.ErrorCode;
@@ -59,6 +68,8 @@ public class AppcRunTasks {
     private CatalogDbClient catalogDbClient;
     @Autowired
     private ApplicationControllerAction appCClient;
+    @Autowired
+    private AAIVnfResources aaiVnfResources;
 
     public void preProcessActivity(BuildingBlockExecution execution) {
         execution.setVariable("actionSnapshot", Action.Snapshot);
@@ -78,6 +89,22 @@ public class AppcRunTasks {
         execution.setVariable(ROLLBACK_VNF_STOP, false);
         execution.setVariable(ROLLBACK_VNF_LOCK, false);
         execution.setVariable(ROLLBACK_QUIESCE_TRAFFIC, false);
+        execution.setVariable("vmIdList", null);
+        execution.setVariable("vserverIdList", null);
+
+        GenericVnf vnf = null;
+        try {
+            vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID);
+        } catch (BBObjectNotFoundException e) {
+            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "No valid VNF exists");
+        }
+
+        try {
+            getVserversForAppc(execution, vnf);
+        } catch (Exception e) {
+            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Unable to retrieve vservers");
+        }
+
     }
 
     public void runAppcCommand(BuildingBlockExecution execution, Action action) {
@@ -155,7 +182,7 @@ public class AppcRunTasks {
     }
 
     protected void mapRollbackVariables(BuildingBlockExecution execution, Action action, String appcCode) {
-        if (appcCode.equals("0") && action != null) {
+        if (appcCode != null && appcCode.equals("0") && action != null) {
             if (action.equals(Action.Lock)) {
                 execution.setVariable(ROLLBACK_VNF_LOCK, true);
             } else if (action.equals(Action.Unlock)) {
@@ -184,4 +211,45 @@ public class AppcRunTasks {
         payloadInfo.put("vfModuleId", vfModuleId);
         return payloadInfo;
     }
+
+    protected void getVserversForAppc(BuildingBlockExecution execution, GenericVnf vnf) throws Exception {
+        AAIResultWrapper aaiRW = aaiVnfResources.queryVnfWrapperById(vnf);
+
+        if (aaiRW != null && aaiRW.getRelationships() != null && aaiRW.getRelationships().isPresent()) {
+            Relationships relationships = aaiRW.getRelationships().get();
+            if (relationships != null) {
+                List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER);
+                JSONArray vserverIds = new JSONArray();
+                JSONArray vserverSelfLinks = new JSONArray();
+                if (vserverUris != null) {
+                    for (AAIResourceUri j : vserverUris) {
+                        if (j != null) {
+                            if (j.getURIKeys() != null) {
+                                String vserverId = j.getURIKeys().get("vserver-id");
+                                vserverIds.put(vserverId);
+                            }
+                            Optional<Vserver> oVserver = aaiVnfResources.getVserver(j);
+                            if (oVserver.isPresent()) {
+                                Vserver vserver = oVserver.get();
+                                if (vserver != null) {
+                                    String vserverSelfLink = vserver.getVserverSelflink();
+                                    vserverSelfLinks.put(vserverSelfLink);
+                                }
+                            }
+                        }
+                    }
+                }
+
+                JSONObject vmidsArray = new JSONObject();
+                JSONObject vserveridsArray = new JSONObject();
+                vmidsArray.put("vmIds", vserverSelfLinks.toString());
+                vserveridsArray.put("vserverIds", vserverIds.toString());
+                logger.debug("vmidsArray is: {}", vmidsArray.toString());
+                logger.debug("vserveridsArray is: {}", vserveridsArray.toString());
+
+                execution.setVariable("vmIdList", vmidsArray.toString());
+                execution.setVariable("vserverIdList", vserveridsArray.toString());
+            }
+        }
+    }
 }
index 7466df5..c9a937b 100644 (file)
@@ -30,8 +30,6 @@ import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
 import org.onap.so.client.aai.entities.AAIResultWrapper;
 import org.onap.so.client.exception.ExceptionBuilder;
 import org.onap.so.client.orchestration.AAINetworkResources;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
@@ -61,10 +59,10 @@ public class UnassignNetworkBB {
      * @param execution - BuildingBlockExecution
      * @param relatedToValue - String, ex: vf-module
      * @return void - nothing
-     * @throws Exception
+     *
      */
 
-    public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) throws Exception {
+    public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) {
         try {
             L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID);
             AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network);
@@ -85,10 +83,10 @@ public class UnassignNetworkBB {
      * 
      * @param execution - BuildingBlockExecution
      * @return void - nothing
-     * @throws Exception
+     *
      */
 
-    public void getCloudSdncRegion(BuildingBlockExecution execution) throws Exception {
+    public void getCloudSdncRegion(BuildingBlockExecution execution) {
         try {
             String cloudRegionSdnc = networkBBUtils.getCloudRegion(execution, SourceSystem.SDNC);
             execution.setVariable("cloudRegionSdnc", cloudRegionSdnc);
@@ -107,7 +105,7 @@ public class UnassignNetworkBB {
         String msg;
         boolean isRollbackNeeded =
                 execution.getVariable("isRollbackNeeded") != null ? execution.getVariable("isRollbackNeeded") : false;
-        if (isRollbackNeeded == true) {
+        if (isRollbackNeeded) {
             msg = execution.getVariable("ErrorUnassignNetworkBB") + messageErrorRollback;
         } else {
             msg = execution.getVariable("ErrorUnassignNetworkBB");
index fc3f2ae..52d2949 100644 (file)
@@ -23,10 +23,10 @@ package org.onap.so.bpmn.infrastructure.validations;
 import java.util.Optional;
 import java.util.regex.Pattern;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
-import org.onap.so.bpmn.common.listener.Skip;
 import org.onap.so.bpmn.common.listener.validation.PreBuildingBlockValidator;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
 import org.onap.so.client.exception.ExceptionBuilder;
+import org.onap.so.listener.Skip;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
index f23e5cd..5c69987 100644 (file)
@@ -33,6 +33,7 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Optional;
 import javax.annotation.PostConstruct;
 import org.apache.commons.lang3.StringUtils;
@@ -210,23 +211,25 @@ public class VnfAdapterVfModuleObjectMapper {
     protected void buildDirectivesParamFromMap(Map<String, Object> paramsMap, String directive,
             Map<String, Object> srcMap) throws MissingValueTagException {
         StringBuilder directives = new StringBuilder();
-        int no_directives_size = 0;
+        int noOfDirectivesSize = 0;
         if (directive.equals(MsoMulticloudUtils.USER_DIRECTIVES)
                 && srcMap.containsKey(MsoMulticloudUtils.OOF_DIRECTIVES)) {
-            no_directives_size = 1;
+            noOfDirectivesSize = 1;
         }
-        if (srcMap.size() > no_directives_size) {
+        if (srcMap.size() > noOfDirectivesSize) {
             directives.append("{ \"attributes\": [ ");
             int i = 0;
-            for (String attributeName : srcMap.keySet()) {
+            for (Map.Entry<String, Object> attributeEntry : srcMap.entrySet()) {
+                String attributeName = attributeEntry.getKey();
+                Object attributeValue = attributeEntry.getValue();
                 if (!(MsoMulticloudUtils.USER_DIRECTIVES.equals(directive)
                         && attributeName.equals(MsoMulticloudUtils.OOF_DIRECTIVES))) {
-                    if (srcMap.get(attributeName) == null) {
+                    if (attributeValue == null) {
                         logger.error("No value tag found for attribute: {}", attributeName);
                         throw new MissingValueTagException("No value tag found for " + attributeName);
                     }
-                    directives.append(new AttributeNameValue(attributeName, srcMap.get(attributeName).toString()));
-                    if (i < (srcMap.size() - 1 + no_directives_size))
+                    directives.append(new AttributeNameValue(attributeName, attributeValue.toString()));
+                    if (i < (srcMap.size() - 1 + noOfDirectivesSize))
                         directives.append(", ");
                     i++;
                 }
diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIEntityNotFoundException.java
new file mode 100644 (file)
index 0000000..5f65e5d
--- /dev/null
@@ -0,0 +1,16 @@
+package org.onap.so.client.orchestration;
+
+public class AAIEntityNotFoundException extends Exception {
+
+    /**
+     * 
+     */
+    private static final long serialVersionUID = -107868951852460677L;
+
+    public AAIEntityNotFoundException(String error) {
+        super(error);
+    }
+
+
+
+}
index c41f3fa..fc15285 100644 (file)
@@ -22,7 +22,9 @@
 
 package org.onap.so.client.orchestration;
 
+import java.util.List;
 import java.util.Optional;
+import org.onap.aai.domain.yang.OwningEntities;
 import org.onap.so.bpmn.common.InjectionHelper;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.OwningEntity;
@@ -120,6 +122,25 @@ public class AAIServiceInstanceResources {
         return aaiRC.exists(owningEntityUri);
     }
 
+    public org.onap.aai.domain.yang.OwningEntity getOwningEntityByName(String owningEntityName)
+            throws AAIEntityNotFoundException {
+        AAIResourceUri owningEntityUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.OWNING_ENTITY)
+                .queryParam("owning-entity-name", owningEntityName);
+        AAIResourcesClient aaiRC = injectionHelper.getAaiClient();
+        Optional<OwningEntities> owningEntities = aaiRC.get(OwningEntities.class, owningEntityUri);
+        if (owningEntities.isPresent()) {
+            List<org.onap.aai.domain.yang.OwningEntity> owningEntityList = owningEntities.get().getOwningEntity();
+            if (owningEntityList.size() > 1) {
+                throw new AAIEntityNotFoundException(
+                        "Non unique result returned for owning entity name: " + owningEntityName);
+            } else {
+                return owningEntityList.get(0);
+            }
+        } else {
+            throw new AAIEntityNotFoundException("No result returned for owning entity name: " + owningEntityName);
+        }
+    }
+
     public void connectOwningEntityandServiceInstance(OwningEntity owningEntity, ServiceInstance serviceInstance) {
         AAIResourceUri owningEntityURI =
                 AAIUriFactory.createResourceUri(AAIObjectType.OWNING_ENTITY, owningEntity.getOwningEntityId());
index a9635d1..63bde79 100644 (file)
@@ -24,6 +24,7 @@ package org.onap.so.client.orchestration;
 
 import java.io.IOException;
 import java.util.Optional;
+import org.onap.aai.domain.yang.Vserver;
 import org.onap.so.bpmn.common.InjectionHelper;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
@@ -37,9 +38,8 @@ import org.onap.so.client.aai.entities.AAIResultWrapper;
 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
 import org.onap.so.client.aai.mapper.AAIObjectMapper;
+import org.onap.so.client.graphinventory.entities.uri.Depth;
 import org.onap.so.db.catalog.beans.OrchestrationStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
@@ -160,4 +160,14 @@ public class AAIVnfResources {
                 AAIUriFactory.createResourceUri(AAIObjectPlurals.GENERIC_VNF).queryParam("vnf-name", vnfName);
         return injectionHelper.getAaiClient().exists(vnfUri);
     }
+
+    public AAIResultWrapper queryVnfWrapperById(GenericVnf vnf) {
+        AAIResourceUri uri =
+                AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId()).depth(Depth.ALL);
+        return injectionHelper.getAaiClient().get(uri);
+    }
+
+    public Optional<Vserver> getVserver(AAIResourceUri uri) {
+        return injectionHelper.getAaiClient().get(uri).asBean(Vserver.class);
+    }
 }
index 12d1b0b..b8146b5 100644 (file)
@@ -36,7 +36,7 @@ public class SDNCRequest implements Serializable {
     private SDNCTopology topology;
     private String correlationValue = UUID.randomUUID().toString();
     private String correlationName = "SDNCCallback";
-    private Object SDNCPayload;
+    private Object sdncPayload;
 
 
     public String getTimeOut() {
@@ -72,11 +72,11 @@ public class SDNCRequest implements Serializable {
     }
 
     public Object getSDNCPayload() {
-        return SDNCPayload;
+        return sdncPayload;
     }
 
     public void setSDNCPayload(Object sDNCPayload) {
-        SDNCPayload = sDNCPayload;
+        this.sdncPayload = sDNCPayload;
     }
 
     @Override
index 21c0b97..d07574a 100644 (file)
@@ -57,10 +57,10 @@ public class SniroClient {
      *
      * @param homingRequest
      * @return
-     * @throws JsonProcessingException
+     * @throws BadResponseException
      * @throws BpmnError
      */
-    public void postDemands(SniroManagerRequest homingRequest) throws BadResponseException, JsonProcessingException {
+    public void postDemands(SniroManagerRequest homingRequest) throws BadResponseException {
         logger.trace("Started Sniro Client Post Demands");
         String url = managerProperties.getHost() + managerProperties.getUri().get("v2");
         logger.debug("Post demands url: {}", url);
index ed3ec75..a8550d8 100644 (file)
@@ -54,16 +54,16 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.LineOfBusiness;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.NetworkPolicy;
+import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup;
 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
 import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf;
 import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoVfModule;
+import org.onap.so.client.aai.entities.uri.AAIResourceUri;
 import org.onap.so.client.exception.BBObjectNotFoundException;
 import org.onap.so.db.catalog.beans.OrchestrationStatus;
-import org.onap.so.client.aai.entities.uri.AAIResourceUri;
-import org.onap.so.bpmn.servicedecomposition.bbobjects.Platform;
 
 public class AAICreateTasksTest extends BaseTaskTest {
 
@@ -271,24 +271,6 @@ public class AAICreateTasksTest extends BaseTaskTest {
                 .createOwningEntityandConnectServiceInstance(serviceInstance.getOwningEntity(), serviceInstance);
     }
 
-    @Test
-    public void createOwningEntityNullOwningEntityIdTest() throws Exception {
-        expectedException.expect(BpmnError.class);
-
-        serviceInstance.getOwningEntity().setOwningEntityId(null);
-
-        aaiCreateTasks.createOwningEntity(execution);
-    }
-
-    @Test
-    public void createOwningEntityEmptyOwningEntityIdTest() throws Exception {
-        expectedException.expect(BpmnError.class);
-
-        serviceInstance.getOwningEntity().setOwningEntityId("");
-
-        aaiCreateTasks.createOwningEntity(execution);
-    }
-
     @Test
     public void createOwningEntityNullOwningEntityNameTest() throws Exception {
         expectedException.expect(BpmnError.class);
index e7a8b35..8328e0e 100644 (file)
  */
 package org.onap.so.bpmn.infrastructure.appc.tasks;
 
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.HashMap;
 import java.util.Optional;
 import java.util.UUID;
@@ -39,6 +45,8 @@ import org.springframework.beans.factory.annotation.Autowired;
 
 public class AppcRunTasksIT extends BaseIntegrationTest {
 
+    private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
     @Autowired
     private AppcRunTasks appcRunTasks;
 
@@ -56,8 +64,51 @@ public class AppcRunTasksIT extends BaseIntegrationTest {
     }
 
     @Test
-    public void preProcessActivityTest() throws Exception {
+    public void preProcessActivityWithVserversTest() throws Exception {
+        final String aaiVnfJson =
+                new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnfWithVservers.json")));
+        wireMockServer.stubFor(
+                get(urlEqualTo("/aai/v15/network/generic-vnfs/generic-vnf/testVnfId1?depth=all")).willReturn(aResponse()
+                        .withHeader("Content-Type", "application/json").withBody(aaiVnfJson).withStatus(200)));
+
+        final String aaiVserverJson =
+                new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVserverFullQueryResponse.json")));
+        wireMockServer.stubFor(get(urlEqualTo(
+                "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/48bd7f11-408f-417c-b834-b41c1b98f7d7"))
+                        .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(aaiVserverJson)
+                                .withStatus(200)));
+        wireMockServer.stubFor(get(urlEqualTo(
+                "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5"))
+                        .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(aaiVserverJson)
+                                .withStatus(200)));
+        wireMockServer.stubFor(get(urlEqualTo(
+                "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/14551849-1e70-45cd-bc5d-a256d49548a2"))
+                        .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(aaiVserverJson)
+                                .withStatus(200)));
+
+        appcRunTasks.preProcessActivity(execution);
+        String vserverIdList = execution.getVariable("vserverIdList");
+        String expectedVserverIdList =
+                "{\"vserverIds\":\"[\\\"1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5\\\",\\\"14551849-1e70-45cd-bc5d-a256d49548a2\\\",\\\"48bd7f11-408f-417c-b834-b41c1b98f7d7\\\"]\"}";
+        String vmIdList = execution.getVariable("vmIdList");
+        String expectedVmIdList =
+                "{\"vmIds\":\"[\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\"]\"}";
+
+        assertEquals(vserverIdList, expectedVserverIdList);
+        assertEquals(vmIdList, expectedVmIdList);
+        assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic);
+        assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false);
+    }
+
+    @Test
+    public void preProcessActivityNoVserversTest() throws Exception {
+        final String aaiVnfJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnf.json")));
+        wireMockServer.stubFor(
+                get(urlEqualTo("/aai/v15/network/generic-vnfs/generic-vnf/testVnfId1?depth=all")).willReturn(aResponse()
+                        .withHeader("Content-Type", "application/json").withBody(aaiVnfJson).withStatus(200)));
         appcRunTasks.preProcessActivity(execution);
+        assertNull(execution.getVariable("vmIdList"));
+        assertNull(execution.getVariable("vServerIdList"));
         assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic);
         assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false);
     }
index cf673c5..cc25689 100644 (file)
@@ -26,12 +26,17 @@ import static org.junit.Assert.assertEquals;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Optional;
 import org.junit.Test;
 import org.mockito.InjectMocks;
+import org.onap.aai.domain.yang.Vserver;
 import org.onap.appc.client.lcm.model.Action;
 import org.onap.so.bpmn.BaseTaskTest;
 import org.onap.so.bpmn.common.BuildingBlockExecution;
@@ -39,11 +44,16 @@ import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
+import org.onap.so.client.aai.entities.AAIResultWrapper;
+import org.onap.so.client.aai.entities.uri.AAIResourceUri;
 import org.onap.so.client.exception.BBObjectNotFoundException;
 import org.onap.so.db.catalog.beans.ControllerSelectionReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
 
 public class AppcRunTasksTest extends BaseTaskTest {
 
+    private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
     @InjectMocks
     private AppcRunTasks appcRunTasks = new AppcRunTasks();
 
@@ -132,6 +142,32 @@ public class AppcRunTasksTest extends BaseTaskTest {
         assertEquals(true, execution.getVariable("rollbackVnfLock"));
     }
 
+    @Test
+    public void getVserversForAppcTest() throws Exception {
+
+        GenericVnf genericVnf = getTestGenericVnf();
+
+        final String aaiVnfJson =
+                new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnfWithVservers.json")));
+        final String aaiVserverJson =
+                new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVserverQueryResponse.json")));
+        AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiVnfJson);
+        ObjectMapper mapper = new ObjectMapper();
+        Vserver vserver = mapper.readValue(aaiVserverJson, Vserver.class);
+        doReturn(aaiResultWrapper).when(aaiVnfResources).queryVnfWrapperById(genericVnf);
+        doReturn(Optional.of(vserver)).when(aaiVnfResources).getVserver(any(AAIResourceUri.class));
+        appcRunTasks.getVserversForAppc(execution, genericVnf);
+        String vserverIdList = execution.getVariable("vserverIdList");
+        String expectedVserverIdList =
+                "{\"vserverIds\":\"[\\\"1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5\\\",\\\"14551849-1e70-45cd-bc5d-a256d49548a2\\\",\\\"48bd7f11-408f-417c-b834-b41c1b98f7d7\\\"]\"}";
+        String vmIdList = execution.getVariable("vmIdList");
+        String expectedVmIdList =
+                "{\"vmIds\":\"[\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\",\\\"http://VSERVER-link.com\\\"]\"}";
+
+        assertEquals(vserverIdList, expectedVserverIdList);
+        assertEquals(vmIdList, expectedVmIdList);
+    }
+
     private void mockReferenceResponse() {
         ControllerSelectionReference reference = new ControllerSelectionReference();
         reference.setControllerName("TEST-CONTROLLER-NAME");
index 0d48a29..3680eaa 100644 (file)
 
 package org.onap.so.client.orchestration;
 
+import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.eq;
@@ -31,6 +33,8 @@ import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.Optional;
 import org.junit.Before;
 import org.junit.Test;
@@ -54,11 +58,14 @@ import org.onap.so.client.aai.entities.AAIResultWrapper;
 import org.onap.so.client.aai.entities.uri.AAIResourceUri;
 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
 import org.onap.so.client.aai.mapper.AAIObjectMapper;
+import org.onap.so.client.graphinventory.entities.uri.Depth;
 import org.onap.so.db.catalog.beans.OrchestrationStatus;
 
 @RunWith(MockitoJUnitRunner.Silent.class)
 public class AAIVnfResourcesTest extends TestDataSetup {
 
+    private final static String JSON_FILE_LOCATION = "src/test/resources/__files/BuildingBlocks/";
+
     private GenericVnf genericVnf;
 
     private ServiceInstance serviceInstance;
@@ -249,4 +256,37 @@ public class AAIVnfResourcesTest extends TestDataSetup {
         boolean nameInUse = aaiVnfResources.checkNameInUse("vnfName");
         assertFalse(nameInUse);
     }
+
+    @Test
+    public void queryVnfWrapperByIdTest() throws Exception {
+        AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId").depth(Depth.ALL);
+        final String aaiResponse = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiGenericVnf.json")));
+        GenericVnf genericVnf = new GenericVnf();
+        genericVnf.setVnfId("vnfId");
+        AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse);
+        doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(eq(uri));
+        AAIResultWrapper actualResult = aaiVnfResources.queryVnfWrapperById(genericVnf);
+        assertEquals(actualResult, aaiResultWrapper);
+
+    }
+
+    @Test
+    public void getVserverTest() throws Exception {
+        final String content =
+                new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "aaiVserverQueryResponse.json")));
+        AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(content);
+        Optional<org.onap.aai.domain.yang.Vserver> oVserver = Optional.empty();
+        AAIResourceUri vserverUri = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, "ModelInvariantUUID",
+                "serviceModelVersionId", "abc", "abc");
+
+        doReturn(aaiResultWrapper).when(MOCK_aaiResourcesClient).get(isA(AAIResourceUri.class));
+        oVserver = aaiVnfResources.getVserver(vserverUri);
+
+        verify(MOCK_aaiResourcesClient, times(1)).get(any(AAIResourceUri.class));
+
+        if (oVserver.isPresent()) {
+            org.onap.aai.domain.yang.Vserver vserver = oVserver.get();
+            assertThat(aaiResultWrapper.asBean(org.onap.aai.domain.yang.Vserver.class).get(), sameBeanAs(vserver));
+        }
+    }
 }
diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnf.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnf.json
new file mode 100644 (file)
index 0000000..e997db3
--- /dev/null
@@ -0,0 +1,57 @@
+{
+       "closedLoopDisabled":false,
+       "vnf-id":"vnfId1",
+       "vnf-name":"vnfName",
+       "vnf-type":"vnfType",
+       "orchestration-status":"PRECREATED",
+       "vf-modules": {
+               "vf-module": [{
+                       "vf-module-id": "lukewarm",
+                       "vf-module-name": "testVfModuleNameGWPrim",
+                       "heat-stack-id": "fastburn",
+            "is-base-vf-module": true,
+            "orchestration-status": "Created"
+               },
+                       {
+                       "vf-module-id": "testVfModuleIdGWSec",
+                       "vf-module-name": "testVfModuleNameGWSec",
+                       "heat-stack-id": "testHeatStackIdGWSec",
+            "orchestration-status": "Created"
+               }]
+       },
+       "volume-groups":[],
+       "line-of-business":null,
+       "platform":null,
+       "cascaded":false,
+       "cloud-params":{},
+       "cloud-context":null,
+       "solution":null,
+       "vnf-name-2":null,
+       "service-id":null,
+       "regional-resource-zone":null,
+       "prov-status":null,
+       "operational-status":null,
+       "equipment-role":null,
+       "management-option":null,
+       "ipv4-oam-address":null,
+       "ipv4-loopback0-address":null,
+       "nm-lan-v6-address":null,
+       "management-v6-address":null,
+       "vcpu":null,
+       "vcpu-units":null,
+       "vmemory":null,
+       "vmemory-units":null,
+       "vdisk":null,
+       "vdisk-units":null,
+       "in-maint":false,
+       "is-closed-loop-disabled":false,
+       "summary-status":null,
+       "encrypted-access-flag":null,
+       "as-number":null,
+       "regional-resource-subzone":null,
+       "self-link":null,
+       "ipv4-oam-gateway-address":null,
+       "ipv4-oam-gateway-address-prefix-length":null,
+       "vlan-id-outer":null,"nm-profile-name":null,
+       "model-info-generic-vnf":null
+}
\ No newline at end of file
diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnfWithVservers.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiGenericVnfWithVservers.json
new file mode 100644 (file)
index 0000000..0ad0f05
--- /dev/null
@@ -0,0 +1,434 @@
+{
+  "vnf-id": "example-vnf-id-val-90603",
+  "vnf-name": "example-vnf-name-val-56838",
+  "vnf-name2": "example-vnf-name2-val-56319",
+  "vnf-type": "example-vnf-type-val-30533",
+  "service-id": "example-service-id-val-28290",
+  "regional-resource-zone": "example-regional-resource-zone-val-11059",
+  "prov-status": "example-prov-status-val-59777",
+  "operational-status": "example-operational-status-val-22513",
+  "in-maint": true,
+  "equipment-role": "example-equipment-role-val-23396",
+  "orchestration-status": "example-orchestration-status-val-59435",
+  "heat-stack-id": "example-heat-stack-id-val-96869",
+  "mso-catalog-key": "example-mso-catalog-key-val-30721",
+  "management-option": "example-management-option-val-61927",
+  "ipv4-oam-address": "192.168.10.14",
+  "ipv4-loopback0-address": "example-ipv4-loopback0-address-val-87072",
+  "nm-lan-v6-address": "example-nm-lan-v6-address-val-91063",
+  "management-v6-address": "example-management-v6-address-val-80466",
+  "vcpu": 45837298,
+  "vcpu-units": "example-vcpu-units-val-86249",
+  "vmemory": 57288956,
+  "vmemory-units": "example-vmemory-units-val-13291",
+  "vdisk": 16937143,
+  "vdisk-units": "example-vdisk-units-val-73197",
+  
+  "is-closed-loop-disabled": true,
+  "summary-status": "example-summary-status-val-86438",
+  "encrypted-access-flag": true,
+  
+  
+  
+  
+  "model-invariant-id": "example-model-invariant-id-val-14704",
+  "model-version-id": "example-model-version-id-val-47847",
+  "model-customization-id": "example-model-customization-id-val-52688",
+  "widget-model-id": "example-widget-model-id-val-20939",
+  "widget-model-version": "example-widget-model-version-val-72210",
+  "as-number": "example-as-number-val-68358",
+  "regional-resource-subzone": "example-regional-resource-subzone-val-34391",
+  "nf-type": "example-nf-type-val-54866",
+  "nf-function": "example-nf-function-val-24790",
+  "nf-role": "example-nf-role-val-4780",
+  "nf-naming-code": "example-nf-naming-code-val-25118",
+  "selflink": "example-selflink-val-68404",
+  
+  "relationship-list": {"relationship":    [
+            {
+         "related-to": "service-instance",
+         "relationship-label": "org.onap.relationships.inventory.ComposedOf",
+         "related-link": "/aai/v12/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/2c323333-af4f-4849-af03-c862c0e93e3b",
+         "relationship-data":          [
+                        {
+               "relationship-key": "customer.global-customer-id",
+               "relationship-value": "e433710f-9217-458d-a79d-1c7aff376d89"
+            },
+                        {
+               "relationship-key": "service-subscription.service-type",
+               "relationship-value": "VIRTUAL USP"
+            },
+                        {
+               "relationship-key": "service-instance.service-instance-id",
+               "relationship-value": "2c323333-af4f-4849-af03-c862c0e93e3b"
+            }
+         ],
+         "related-to-property": [         {
+            "property-key": "service-instance.service-instance-name",
+            "property-value": "kjhgfd1"
+         }]
+      },
+            {
+         "related-to": "vserver",
+         "relationship-label": "tosca.relationships.HostedOn",
+         "related-link": "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5",
+         "relationship-data":          [
+                        {
+               "relationship-key": "cloud-region.cloud-owner",
+               "relationship-value": "CloudOwner"
+            },
+                        {
+               "relationship-key": "cloud-region.cloud-region-id",
+               "relationship-value": "mtn23a"
+            },
+                        {
+               "relationship-key": "tenant.tenant-id",
+               "relationship-value": "e6beab145f6b49098277ac163ac1b4f3"
+            },
+                        {
+               "relationship-key": "vserver.vserver-id",
+               "relationship-value": "1b3f44e5-d96d-4aac-bd9a-310e8cfb0af5"
+            }
+         ],
+         "related-to-property": [         {
+            "property-key": "vserver.vserver-name",
+            "property-value": "comx5000vm003"
+         }]
+      },
+            {
+         "related-to": "vserver",
+         "relationship-label": "tosca.relationships.HostedOn",
+         "related-link": "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/14551849-1e70-45cd-bc5d-a256d49548a2",
+         "relationship-data":          [
+                        {
+               "relationship-key": "cloud-region.cloud-owner",
+               "relationship-value": "CloudOwner"
+            },
+                        {
+               "relationship-key": "cloud-region.cloud-region-id",
+               "relationship-value": "mtn23a"
+            },
+                        {
+               "relationship-key": "tenant.tenant-id",
+               "relationship-value": "e6beab145f6b49098277ac163ac1b4f3"
+            },
+                        {
+               "relationship-key": "vserver.vserver-id",
+               "relationship-value": "14551849-1e70-45cd-bc5d-a256d49548a2"
+            }
+         ],
+         "related-to-property": [         {
+            "property-key": "vserver.vserver-name",
+            "property-value": "comx5000vm002"
+         }]
+      },
+            {
+         "related-to": "vserver",
+         "relationship-label": "tosca.relationships.HostedOn",
+         "related-link": "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/mtn23a/tenants/tenant/e6beab145f6b49098277ac163ac1b4f3/vservers/vserver/48bd7f11-408f-417c-b834-b41c1b98f7d7",
+         "relationship-data":          [
+                        {
+               "relationship-key": "cloud-region.cloud-owner",
+               "relationship-value": "CloudOwner"
+            },
+                        {
+               "relationship-key": "cloud-region.cloud-region-id",
+               "relationship-value": "mtn23a"
+            },
+                        {
+               "relationship-key": "tenant.tenant-id",
+               "relationship-value": "e6beab145f6b49098277ac163ac1b4f3"
+            },
+                        {
+               "relationship-key": "vserver.vserver-id",
+               "relationship-value": "48bd7f11-408f-417c-b834-b41c1b98f7d7"
+            }
+         ],
+         "related-to-property": [         {
+            "property-key": "vserver.vserver-name",
+            "property-value": "comx5000vm001"
+         }]
+      }
+   ]},  
+  "l-interfaces": {
+    "l-interface": [
+      {
+        "interface-name": "example-interface-name-val-50593",
+        "interface-role": "example-interface-role-val-23375",
+        "v6-wan-link-ip": "example-v6-wan-link-ip-val-5921",
+        "selflink": "example-selflink-val-75663",
+        "interface-id": "example-interface-id-val-37465",
+        "macaddr": "example-macaddr-val-62657",
+        "network-name": "example-network-name-val-7252",
+        "management-option": "example-management-option-val-32963",
+        "interface-description": "example-interface-description-val-89453",
+        "is-port-mirrored": true,
+        "vlans": {
+          "vlan": [
+            {
+              "vlan-interface": "example-vlan-interface-val-16684",
+              "vlan-id-inner": 8602916,
+              "vlan-id-outer": 97348542,
+              "speed-value": "example-speed-value-val-90330",
+              "speed-units": "example-speed-units-val-15849",
+              "vlan-description": "example-vlan-description-val-46942",
+              "backdoor-connection": "example-backdoor-connection-val-78445",
+              
+              "orchestration-status": "example-orchestration-status-val-44994",
+              
+             
+             
+              "l3-interface-ipv4-address-list": [
+                {
+                  "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-90277",
+                  "l3-interface-ipv4-prefix-length": 3364150,
+                  "vlan-id-inner": 44021171,
+                  "vlan-id-outer": 55708677,
+                  "is-floating": true,
+                  "neutron-network-id": "example-neutron-network-id-val-43267",
+                  "neutron-subnet-id": "example-neutron-subnet-id-val-62870"
+                }
+              ],
+              "l3-interface-ipv6-address-list": [
+                {
+                  "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-45323",
+                  "l3-interface-ipv6-prefix-length": 56688923,
+                  "vlan-id-inner": 5703071,
+                  "vlan-id-outer": 86682265,
+                  "is-floating": true,
+                  "neutron-network-id": "example-neutron-network-id-val-28366",
+                  "neutron-subnet-id": "example-neutron-subnet-id-val-53034"
+                }
+              ]
+            }
+          ]
+        },
+        "sriov-vfs": {
+          "sriov-vf": [
+            {
+              "pci-id": "example-pci-id-val-4720",
+              "vf-vlan-filter": "example-vf-vlan-filter-val-42594",
+              "vf-mac-filter": "example-vf-mac-filter-val-13375",
+              "vf-vlan-strip": true,
+              "vf-vlan-anti-spoof-check": true,
+              "vf-mac-anti-spoof-check": true,
+              "vf-mirrors": "example-vf-mirrors-val-6057",
+              "vf-broadcast-allow": true,
+              "vf-unknown-multicast-allow": true,
+              "vf-unknown-unicast-allow": true,
+              "vf-insert-stag": true,
+              "vf-link-status": "example-vf-link-status-val-81448",
+              "neutron-network-id": "example-neutron-network-id-val-9504"
+            }
+          ]
+        },
+        "l-interfaces": {
+          "l-interface": [
+            {
+              "interface-name": "example-interface-name-val-16738",
+              "interface-role": "example-interface-role-val-13943",
+              "v6-wan-link-ip": "example-v6-wan-link-ip-val-63173",
+              "selflink": "example-selflink-val-43085",
+              "interface-id": "example-interface-id-val-51379",
+              "macaddr": "example-macaddr-val-16195",
+              "network-name": "example-network-name-val-45683",
+              "management-option": "example-management-option-val-78983",
+              "interface-description": "example-interface-description-val-34414",
+              "is-port-mirrored": true
+            }
+          ]
+        },
+        "l3-interface-ipv4-address-list": [
+          {
+            "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-99078",
+            "l3-interface-ipv4-prefix-length": 55755841,
+            "vlan-id-inner": 81525473,
+            "vlan-id-outer": 90908072,
+            "is-floating": true,
+            "neutron-network-id": "example-neutron-network-id-val-47919",
+            "neutron-subnet-id": "example-neutron-subnet-id-val-84236"
+          }
+        ],
+        "l3-interface-ipv6-address-list": [
+          {
+            "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-21939",
+            "l3-interface-ipv6-prefix-length": 50057584,
+            "vlan-id-inner": 75774660,
+            "vlan-id-outer": 4421090,
+            "is-floating": true,
+            "neutron-network-id": "example-neutron-network-id-val-46377",
+            "neutron-subnet-id": "example-neutron-subnet-id-val-16585"
+          }
+        ]
+      }
+    ]
+  },
+  "lag-interfaces": {
+    "lag-interface": [
+      {
+        "interface-name": "example-interface-name-val-39234",
+        "interface-description": "example-interface-description-val-1037",
+        "speed-value": "example-speed-value-val-1929",
+        "speed-units": "example-speed-units-val-74937",
+        "interface-id": "example-interface-id-val-91265",
+        "interface-role": "example-interface-role-val-19613",
+       
+       
+        "l-interfaces": {
+          "l-interface": [
+            {
+              "interface-name": "example-interface-name-val-10722",
+              "interface-role": "example-interface-role-val-95194",
+              "v6-wan-link-ip": "example-v6-wan-link-ip-val-24328",
+              "selflink": "example-selflink-val-24987",
+              "interface-id": "example-interface-id-val-75726",
+              "macaddr": "example-macaddr-val-36940",
+              "network-name": "example-network-name-val-65359",
+              "management-option": "example-management-option-val-49521",
+              "interface-description": "example-interface-description-val-70528",
+              "is-port-mirrored": true,
+              "vlans": {
+                "vlan": [
+                  {
+                    "vlan-interface": "example-vlan-interface-val-70827",
+                    "vlan-id-inner": 55659612,
+                    "vlan-id-outer": 90335612,
+                    "speed-value": "example-speed-value-val-54761",
+                    "speed-units": "example-speed-units-val-91398",
+                    "vlan-description": "example-vlan-description-val-17018",
+                    "backdoor-connection": "example-backdoor-connection-val-4021",
+                    
+                    "orchestration-status": "example-orchestration-status-val-18315",
+                    
+                  
+                    "l3-interface-ipv4-address-list": [
+                      {
+                        "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-59336",
+                        "l3-interface-ipv4-prefix-length": 57636053,
+                        "vlan-id-inner": 34068397,
+                        "vlan-id-outer": 48570286,
+                        "is-floating": true,
+                        "neutron-network-id": "example-neutron-network-id-val-69862",
+                        "neutron-subnet-id": "example-neutron-subnet-id-val-75795"
+                      }
+                    ],
+                    "l3-interface-ipv6-address-list": [
+                      {
+                        "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-15038",
+                        "l3-interface-ipv6-prefix-length": 42694503,
+                        "vlan-id-inner": 15929806,
+                        "vlan-id-outer": 87413856,
+                        "is-floating": true,
+                        "neutron-network-id": "example-neutron-network-id-val-52519",
+                        "neutron-subnet-id": "example-neutron-subnet-id-val-24471"
+                      }
+                    ]
+                  }
+                ]
+              },
+              "sriov-vfs": {
+                "sriov-vf": [
+                  {
+                    "pci-id": "example-pci-id-val-44669",
+                    "vf-vlan-filter": "example-vf-vlan-filter-val-53436",
+                    "vf-mac-filter": "example-vf-mac-filter-val-71902",
+                    "vf-vlan-strip": true,
+                    "vf-vlan-anti-spoof-check": true,
+                    "vf-mac-anti-spoof-check": true,
+                    "vf-mirrors": "example-vf-mirrors-val-54963",
+                    "vf-broadcast-allow": true,
+                    "vf-unknown-multicast-allow": true,
+                    "vf-unknown-unicast-allow": true,
+                    "vf-insert-stag": true,
+                    "vf-link-status": "example-vf-link-status-val-1546",
+                    "neutron-network-id": "example-neutron-network-id-val-92159"
+                  }
+                ]
+              },
+              "l-interfaces": {
+                "l-interface": [
+                  {
+                    "interface-name": "example-interface-name-val-9327",
+                    "interface-role": "example-interface-role-val-21859",
+                    "v6-wan-link-ip": "example-v6-wan-link-ip-val-21445",
+                    "selflink": "example-selflink-val-6085",
+                    "interface-id": "example-interface-id-val-39854",
+                    "macaddr": "example-macaddr-val-14433",
+                    "network-name": "example-network-name-val-3722",
+                    "management-option": "example-management-option-val-64739",
+                    "interface-description": "example-interface-description-val-5814",
+                    "is-port-mirrored": true
+                    
+                   
+                    
+                  }
+                ]
+              },
+              "l3-interface-ipv4-address-list": [
+                {
+                  "l3-interface-ipv4-address": "example-l3-interface-ipv4-address-val-64531",
+                  "l3-interface-ipv4-prefix-length": 66545882,
+                  "vlan-id-inner": 12194134,
+                  "vlan-id-outer": 29589286,
+                  "is-floating": true,
+                  "neutron-network-id": "example-neutron-network-id-val-91108",
+                  "neutron-subnet-id": "example-neutron-subnet-id-val-56984"
+                }
+              ],
+              "l3-interface-ipv6-address-list": [
+                {
+                  "l3-interface-ipv6-address": "example-l3-interface-ipv6-address-val-37408",
+                  "l3-interface-ipv6-prefix-length": 5116459,
+                  "vlan-id-inner": 39229896,
+                  "vlan-id-outer": 15091934,
+                  "is-floating": true,
+                  "neutron-network-id": "example-neutron-network-id-val-87700",
+                  "neutron-subnet-id": "example-neutron-subnet-id-val-37352"
+                }
+              ]
+            }
+          ]
+        }
+      }
+    ]
+  },
+  "vf-modules": {
+    "vf-module": [
+      {
+        "vf-module-id": "example-vf-module-id-val-56249",
+        "vf-module-name": "example-vf-module-name-val-18987",
+        "heat-stack-id": "example-heat-stack-id-val-80110",
+        "orchestration-status": "example-orchestration-status-val-8226",
+        "is-base-vf-module": true,
+        "model-invariant-id": "example-model-invariant-id-val-5071",
+        "model-version-id": "example-model-version-id-val-80793",
+        "model-customization-id": "example-model-customization-id-val-83277",
+        "widget-model-id": "example-widget-model-id-val-99814",
+        "widget-model-version": "example-widget-model-version-val-22799",
+        "contrail-service-instance-fqdn": "example-contrail-service-instance-fqdn-val-52133",
+        "module-index": 1933,
+        "selflink": "example-selflink-val-69992"
+      }
+    ]
+  },
+  "licenses": {
+    "license": [
+      {
+        "group-uuid": "example-group-uuid-val-73012",
+        "resource-uuid": "example-resource-uuid-val-80045"
+      }
+    ]
+  },
+  "entitlements": {
+    "entitlement": [
+      {
+        "group-uuid": "example-group-uuid-val-14874",
+        "resource-uuid": "example-resource-uuid-val-49146"
+      }
+    ]
+  }
+
+}
\ No newline at end of file
diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverFullQueryResponse.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverFullQueryResponse.json
new file mode 100644 (file)
index 0000000..1c7e1fb
--- /dev/null
@@ -0,0 +1,13 @@
+{
+       "in-maint": null, 
+    "is-closed-loop-disabled": null, 
+       "linterfaces": null, 
+       "prov-status": null, 
+       "relationship-list": null, 
+       "resource-version": null, 
+       "volumes": null, 
+    "vserver-id": "VServerId",
+    "vserver-name": "VServerName",
+    "vserver-name2": "VServerName2",
+    "vserver-selflink": "http://VSERVER-link.com"
+ }
\ No newline at end of file
diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverQueryResponse.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/aaiVserverQueryResponse.json
new file mode 100644 (file)
index 0000000..eca735b
--- /dev/null
@@ -0,0 +1,6 @@
+{
+    "vserverId": "VServerId",
+    "vserverName": "VServerName",
+    "vserverName2": "VServerName2",
+    "vserverSelflink": "http://VSERVER-link.com"
+ }
\ No newline at end of file
index 3bd646f..d15fbf9 100644 (file)
@@ -135,7 +135,7 @@ public class CloudifyClient {
      * @return An object of Class <R>
      */
     public <R> CloudifyRequest<R> get(String path, Class<R> returnType) {
-        return new CloudifyRequest<R>(this, HttpMethod.GET, path, null, returnType);
+        return new CloudifyRequest<>(this, HttpMethod.GET, path, null, returnType);
     }
 
 }
index df63bd1..006768f 100644 (file)
@@ -37,7 +37,7 @@ public class CloudifyRequest<R> {
 
     private StringBuilder path = new StringBuilder();
 
-    private Map<String, List<Object>> headers = new HashMap<String, List<Object>>();
+    private Map<String, List<Object>> headers = new HashMap<>();
 
     private Entity<?> entity;
 
@@ -100,7 +100,7 @@ public class CloudifyRequest<R> {
     }
 
     public <T> Entity<T> entity(T entity, String contentType) {
-        return new Entity<T>(entity, contentType);
+        return new Entity<>(entity, contentType);
     }
 
     public Entity<?> entity() {
@@ -160,7 +160,7 @@ public class CloudifyRequest<R> {
                 + headers + ", entity=" + entity + ", returnType=" + returnType + "]";
     }
 
-    private Map<String, List<Object>> queryParams = new LinkedHashMap<String, List<Object>>();
+    private Map<String, List<Object>> queryParams = new LinkedHashMap<>();
 
     public Map<String, List<Object>> queryParams() {
         return queryParams;
@@ -171,7 +171,7 @@ public class CloudifyRequest<R> {
             List<Object> values = queryParams.get(key);
             values.add(value);
         } else {
-            List<Object> values = new ArrayList<Object>();
+            List<Object> values = new ArrayList<>();
             values.add(value);
             queryParams.put(key, values);
         }
index a528971..2553038 100644 (file)
       <version>${grpc.version}</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.javatuples</groupId>
+      <artifactId>javatuples</artifactId>
+      <version>1.2</version>
+    </dependency>
 
   </dependencies>
   <dependencyManagement>
index f7f5d78..e301edb 100644 (file)
@@ -32,9 +32,9 @@ public class DSLNodeKey implements QueryStep {
     private boolean not = false;
     private final StringBuilder query = new StringBuilder();
     private final String keyName;
-    private final List<String> values;
+    private final List<Object> values;
 
-    public DSLNodeKey(String keyName, String... value) {
+    public DSLNodeKey(String keyName, Object... value) {
 
         this.keyName = keyName;
         this.values = Arrays.asList(value);
@@ -54,14 +54,18 @@ public class DSLNodeKey implements QueryStep {
             result.append(" !");
         }
         result.append("('").append(keyName).append("', ");
-        List<String> temp = new ArrayList<>();
-        for (String item : values) {
+        List<Object> temp = new ArrayList<>();
+        for (Object item : values) {
             if ("null".equals(item)) {
                 temp.add(String.format("' %s '", item));
             } else if ("".equals(item)) {
                 temp.add("' '");
             } else {
-                temp.add(String.format("'%s'", item));
+                if (item instanceof String) {
+                    temp.add(String.format("'%s'", item));
+                } else {
+                    temp.add(item);
+                }
             }
         }
         result.append(Joiner.on(", ").join(temp)).append(")");
index 2fdd657..87d4d84 100644 (file)
@@ -45,7 +45,7 @@ public class __ {
         return __.<DSLNode>start(new DSLNode(name, key));
     }
 
-    public static DSLNodeKey key(String keyName, String... value) {
+    public static DSLNodeKey key(String keyName, Object... value) {
         return new DSLNodeKey(keyName, value);
     }
 
@@ -18,7 +18,7 @@
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.so.bpmn.common.listener;
+package org.onap.so.listener;
 
 import java.lang.annotation.Annotation;
 import java.util.Comparator;
@@ -27,7 +27,6 @@ import java.util.Optional;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
 import javax.annotation.Priority;
-import org.onap.so.client.exception.ExceptionBuilder;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.ApplicationContext;
 
@@ -36,10 +35,7 @@ public abstract class ListenerRunner {
     @Autowired
     protected ApplicationContext context;
 
-    @Autowired
-    protected ExceptionBuilder exceptionBuilder;
-
-    protected <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) {
+    public <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) {
         return validators.stream().filter(item -> {
             return !item.getClass().isAnnotationPresent(Skip.class) && predicate.test(item);
         }).sorted(Comparator.comparing(item -> {
@@ -18,7 +18,7 @@
  * ============LICENSE_END=========================================================
  */
 
-package org.onap.so.bpmn.common.listener;
+package org.onap.so.listener;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
index 9fceed1..a72229a 100644 (file)
@@ -57,6 +57,9 @@ public class RequestParameters implements Serializable {
     @JsonProperty("rebuildVolumeGroups")
     private Boolean rebuildVolumeGroups;
 
+    @JsonProperty("enforceValidNfValues")
+    private Boolean enforceValidNfValues = false;
+
     @Override
     public String toString() {
         return new ToStringBuilder(this).append("subscriptionServiceType", subscriptionServiceType)
@@ -64,7 +67,15 @@ public class RequestParameters implements Serializable {
                 .append("usePreload", usePreload).append("autoBuildVfModules", autoBuildVfModules)
                 .append("cascadeDelete", cascadeDelete).append("testApi", testApi)
                 .append("retainAssignments", retainAssignments).append("rebuildVolumeGroups", rebuildVolumeGroups)
-                .toString();
+                .append("enforceValidNfValues", enforceValidNfValues).toString();
+    }
+
+    public Boolean getEnforceValidNfValues() {
+        return enforceValidNfValues;
+    }
+
+    public void setEnforceValidNfValues(Boolean enforceValidNfValues) {
+        this.enforceValidNfValues = enforceValidNfValues;
     }
 
     public String getSubscriptionServiceType() {
index 94385ec..67016a1 100644 (file)
@@ -20,6 +20,8 @@
 
 package org.onap.so.utils;
 
-public interface TargetEntities {
+import java.io.Serializable;
+
+public interface TargetEntities extends Serializable {
 
 }
index 6e55fe1..590e838 100644 (file)
@@ -108,4 +108,14 @@ public class DSLQueryBuilderTest {
                 builder.equals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')"));
         assertTrue(builder.equals(builder));
     }
+
+
+    @Test
+    public void mixedTypeTest() {
+        DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION,
+                __.key("cloud-owner", "owner"), __.key("cloud-region-id", "id")));
+        builder.to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", 167), __.key("my-boolean", true)).output());
+        assertTrue(builder.equals(
+                "cloud-region('cloud-owner', 'owner')('cloud-region-id', 'id') > vlan-tag*('vlan-id-outer', 167)('my-boolean', true)"));
+    }
 }
index c7f6459..ab2ce10 100644 (file)
@@ -29,7 +29,7 @@ public abstract class ApiException extends Exception {
     * 
     */
     private static final long serialVersionUID = 683162058616691134L;
-    private int httpResponseCode;
+    private int httpResponseCode = 500;
     private String messageID;
     private ErrorLoggerInfo errorLoggerInfo;
 
@@ -49,6 +49,15 @@ public abstract class ApiException extends Exception {
         super(message, cause);
     }
 
+    public ApiException(String message, int httpResponseCode) {
+        super(message);
+        this.httpResponseCode = httpResponseCode;
+    }
+
+    public ApiException(String message) {
+        super(message);
+    }
+
     public String getMessageID() {
         return messageID;
     }
index 66b86a6..6a56b58 100644 (file)
@@ -70,7 +70,7 @@ public class ApiExceptionMapper implements ExceptionMapper<ApiException> {
 
     @Override
     public Response toResponse(ApiException exception) {
-
+        logger.error("Error During API Call", exception);
         return Response.status(exception.getHttpResponseCode()).entity(buildErrorString(exception)).build();
     }
 
index 42198e2..cbbfa16 100644 (file)
@@ -22,7 +22,7 @@ package org.onap.so.apihandlerinfra.exceptions;
 
 public class DuplicateRequestException extends ApiException {
 
-    private static final String duplicateFailMessage = "Error: Locked instance - This %s (%s) "
+    private static final String DUPLICATE_FAIL_MESSAGE = "Error: Locked instance - This %s (%s) "
             + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
 
     private DuplicateRequestException(Builder builder) {
@@ -36,7 +36,7 @@ public class DuplicateRequestException extends ApiException {
 
         public Builder(String requestScope, String instance, String requestStatus, String requestID,
                 int httpResponseCode, String messageID) {
-            super(String.format(duplicateFailMessage, requestScope, instance, requestStatus, requestID),
+            super(String.format(DUPLICATE_FAIL_MESSAGE, requestScope, instance, requestStatus, requestID),
                     httpResponseCode, messageID);
 
         }
index 577a146..a8f868d 100644 (file)
@@ -22,7 +22,7 @@ package org.onap.so.apihandlerinfra.exceptions;
 
 public class RequestDbFailureException extends ApiException {
 
-    private static final String requestDbFailMessage = "Unable to %s due to error contacting requestDb: %s";
+    private static final String REQUEST_DB_FAIL_MESSAGE = "Unable to %s due to error contacting requestDb: %s";
 
     private RequestDbFailureException(Builder builder) {
         super(builder);
@@ -32,7 +32,7 @@ public class RequestDbFailureException extends ApiException {
 
 
         public Builder(String action, String error, int httpResponseCode, String messageID) {
-            super(requestDbFailMessage.format(requestDbFailMessage, action, error), httpResponseCode, messageID);
+            super(REQUEST_DB_FAIL_MESSAGE.format(REQUEST_DB_FAIL_MESSAGE, action, error), httpResponseCode, messageID);
         }
 
         public RequestDbFailureException build() {
index 372ed30..ae8256e 100644 (file)
@@ -28,6 +28,11 @@ public class ValidateException extends ApiException {
     }
 
 
+    public ValidateException(String errorMessage, int httpResponseCode) {
+        super(errorMessage, httpResponseCode);
+    }
+
+
     public static class Builder extends ApiException.Builder<Builder> {
 
         public Builder(String message, int httpResponseCode, String messageID) {
index 451fa64..e56eb42 100644 (file)
@@ -115,7 +115,7 @@ public class CamundaRequestHandler {
 
         List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody();
 
-        if (historicProcessInstanceList != null) {
+        if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) {
             Collections.reverse(historicProcessInstanceList);
             processInstanceId = historicProcessInstanceList.get(0).getId();
         } else {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GenericStringConverter.java
new file mode 100644 (file)
index 0000000..80144d8
--- /dev/null
@@ -0,0 +1,33 @@
+package org.onap.so.apihandlerinfra;
+
+import java.net.URI;
+import java.util.Set;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
+import org.springframework.core.convert.TypeDescriptor;
+import org.springframework.core.convert.converter.GenericConverter;
+import org.springframework.stereotype.Component;
+import com.google.common.collect.ImmutableSet;
+
+@Component
+@ConfigurationPropertiesBinding
+public class GenericStringConverter implements GenericConverter {
+
+    @Autowired
+    private HealthCheckConverter converter;
+
+    @Override
+    public Set<ConvertiblePair> getConvertibleTypes() {
+
+        ConvertiblePair[] pairs = new ConvertiblePair[] {new ConvertiblePair(String.class, Subsystem.class),
+                new ConvertiblePair(String.class, URI.class)};
+        return ImmutableSet.copyOf(pairs);
+    }
+
+    @Override
+    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
+
+        return converter.convert(source, sourceType, targetType);
+
+    }
+}
index 3d4b2c7..0379ae3 100644 (file)
@@ -25,11 +25,8 @@ package org.onap.so.apihandlerinfra;
 
 import java.net.URI;
 import java.util.Collections;
-import org.onap.so.logger.LoggingAnchor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
+import java.util.List;
+import java.util.stream.Collectors;
 import javax.annotation.PostConstruct;
 import javax.transaction.Transactional;
 import javax.ws.rs.DefaultValue;
@@ -42,14 +39,20 @@ import javax.ws.rs.core.Context;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriBuilder;
 import org.apache.http.HttpStatus;
+import org.onap.so.apihandlerinfra.HealthCheckConfig.Endpoint;
+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.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.RestTemplate;
-import org.springframework.http.HttpMethod;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 
@@ -59,45 +62,38 @@ import io.swagger.annotations.ApiOperation;
 @Api(value = "/globalhealthcheck", description = "APIH Infra Global Health Check")
 public class GlobalHealthcheckHandler {
     private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class);
-    private static final String CONTEXTPATH_PROPERTY = "management.context-path";
-    private static final String PROPERTY_DOMAIN = "mso.health.endpoints";
-    private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb";
-    private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb";
-    private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc";
-    private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack";
-    private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn";
-    private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc";
-    private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc";
-    private static final String DEFAULT_PROPERTY_VALUE = "";
+    protected static final String CONTEXTPATH_PROPERTY = "management.endpoints.web.base-path";
+    protected static final String PROPERTY_DOMAIN = "mso.health";
+    protected static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".endpoints.catalogdb";
+    protected static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".endpoints.requestdb";
+    protected static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.sdnc";
+    protected static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".endpoints.openstack";
+    protected static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".endpoints.bpmn";
+    protected static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.asdc";
+    protected static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".endpoints.requestdbattsvc";
+    protected static final String MSO_AUTH_PROPERTY = PROPERTY_DOMAIN + ".auth";
+    protected static final String DEFAULT_PROPERTY_VALUE = "";
 
     // e.g. /manage
     private String actuatorContextPath;
-    private String endpointCatalogdb;
-    private String endpointRequestdb;
-    private String endpointSdnc;
-    private String endpointOpenstack;
-    private String endpointBpmn;
-    private String endpointAsdc;
-    private String endpointRequestdbAttsvc;
 
     @Autowired
     private Environment env;
 
     @Autowired
     private RestTemplate restTemplate;
-    private final String health = "/health";
 
+    @Autowired
+    private HealthCheckConfig config;
+
+    private static final String HEALTH = "/health";
+
+    private String msoAuth;
 
     @PostConstruct
     protected void init() {
         actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
-        endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
+        msoAuth = env.getProperty(MSO_AUTH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE);
     }
 
     @GET
@@ -108,29 +104,25 @@ public class GlobalHealthcheckHandler {
             @Context ContainerRequestContext requestContext) {
         Response HEALTH_CHECK_RESPONSE = null;
         // Build internal response object
-        HealthcheckResponse rsp = new HealthcheckResponse();
+        HealthCheckResponse rsp = new HealthCheckResponse();
 
         try {
             // Generated RequestId
             String requestId = requestContext.getProperty("requestId").toString();
             logger.info(LoggingAnchor.TWO, MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId);
 
-            // set APIH status, this is the main entry point
-            rsp.setApih(HealthcheckStatus.UP.toString());
-            // set BPMN
-            rsp.setBpmn(querySubsystemHealth(MsoSubsystems.BPMN));
-            // set SDNCAdapter
-            rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC));
-            // set ASDCController
-            rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC));
-            // set CatalogDbAdapter
-            rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB));
-            // set RequestDbAdapter
-            rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB));
-            // set OpenStackAdapter
-            rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK));
-            // set RequestDbAdapterAttSvc
-            rsp.setRequestdbAdapterAttsvc(querySubsystemHealth(MsoSubsystems.REQUESTDBATT));
+            List<Endpoint> endpoints = config.getEndpoints().stream().filter(item -> {
+                if (!enableBpmn && SoSubsystems.BPMN.equals(item.getSubsystem())) {
+                    return false;
+                } else {
+                    return true;
+                }
+            }).collect(Collectors.toList());
+
+            for (Endpoint endpoint : endpoints) {
+                rsp.getSubsystems().add(querySubsystemHealth(endpoint));
+            }
+
             // set Message
             rsp.setMessage(String.format("HttpStatus: %s", HttpStatus.SC_OK));
             logger.info(rsp.toString());
@@ -149,70 +141,51 @@ public class GlobalHealthcheckHandler {
     protected HttpEntity<String> buildHttpEntityForRequest() {
         HttpHeaders headers = new HttpHeaders();
         headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
-        headers.set("Content-Type", "application/json");
+        headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
+        headers.set(HttpHeaders.AUTHORIZATION, msoAuth);
         HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
         return entity;
     }
 
-    protected String querySubsystemHealth(MsoSubsystems subsystem) {
+    protected HealthCheckSubsystem querySubsystemHealth(Endpoint subsystem) {
+        HealthCheckStatus status = HealthCheckStatus.DOWN;
+        URI uri = subsystem.getUri();
         try {
             // get port number for the subsystem
-            String ept = getEndpointUrlForSubsystemEnum(subsystem);
-
             // build final endpoint url
-            UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health);
-            URI uri = builder.build();
-            logger.info("Calculated URL: {}", uri.toString());
+            uri = UriBuilder.fromUri(subsystem.getUri()).path(actuatorContextPath).path(HEALTH).build();
+            logger.info("Calculated URL: {}", uri);
 
             ResponseEntity<SubsystemHealthcheckResponse> result = restTemplate.exchange(uri, HttpMethod.GET,
                     buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class);
 
-            return processResponseFromSubsystem(result, subsystem);
+            status = processResponseFromSubsystem(result, subsystem);
+
 
         } catch (Exception ex) {
             logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex);
-            return HealthcheckStatus.DOWN.toString();
         }
+
+        return new HealthCheckSubsystem(subsystem.getSubsystem(), uri, status);
     }
 
-    protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result,
-            MsoSubsystems subsystem) {
+    protected HealthCheckStatus processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result,
+            Endpoint endpoint) {
         if (result == null || result.getStatusCodeValue() != HttpStatus.SC_OK) {
             logger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s",
-                    subsystem, result == null ? "NULL" : result));
-            return HealthcheckStatus.DOWN.toString();
+                    endpoint.getSubsystem(), result == null ? "NULL" : result));
+            return HealthCheckStatus.DOWN;
         }
 
         SubsystemHealthcheckResponse body = result.getBody();
 
         String status = body.getStatus();
         if ("UP".equalsIgnoreCase(status)) {
-            return HealthcheckStatus.UP.toString();
+            return HealthCheckStatus.UP;
         } else {
-            logger.error("{}, query health endpoint did not return UP status!", subsystem);
-            return HealthcheckStatus.DOWN.toString();
+            logger.error("{}, query health endpoint did not return UP status!", endpoint.getSubsystem());
+            return HealthCheckStatus.DOWN;
         }
     }
 
-
-    protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem) {
-        switch (subsystem) {
-            case SDNC:
-                return this.endpointSdnc;
-            case ASDC:
-                return this.endpointAsdc;
-            case BPMN:
-                return this.endpointBpmn;
-            case CATALOGDB:
-                return this.endpointCatalogdb;
-            case OPENSTACK:
-                return this.endpointOpenstack;
-            case REQUESTDB:
-                return this.endpointRequestdb;
-            case REQUESTDBATT:
-                return this.endpointRequestdbAttsvc;
-            default:
-                return "";
-        }
-    }
 }
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheck.java
new file mode 100644 (file)
index 0000000..1899cdd
--- /dev/null
@@ -0,0 +1,84 @@
+package org.onap.so.apihandlerinfra;
+
+import java.net.URI;
+import javax.ws.rs.core.UriBuilder;
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ConfigurationProperties(prefix = "mso.health.enpoints")
+public class HealthCheck {
+
+    private Subsystem subsystem;
+    private URI uri;
+    private HealthCheckStatus status = HealthCheckStatus.DOWN;
+
+    public HealthCheck() {
+
+    }
+
+    public HealthCheck(String subsystem, String uri) {
+        this.subsystem = SoSubsystems.valueOf(subsystem.toUpperCase());
+        this.uri = UriBuilder.fromUri(uri).build();
+    }
+
+    public HealthCheck(Subsystem subsystem, URI uri) {
+        this.subsystem = subsystem;
+        this.uri = uri;
+    }
+
+    public HealthCheck(Subsystem subsystem, URI uri, HealthCheckStatus status) {
+        this.subsystem = subsystem;
+        this.uri = uri;
+        this.status = status;
+    }
+
+    public Subsystem getSubsystem() {
+        return subsystem;
+    }
+
+    public void setSubsystem(Subsystem component) {
+        this.subsystem = component;
+    }
+
+    public URI getUri() {
+        return uri;
+    }
+
+    public void setUri(URI uri) {
+        this.uri = uri;
+    }
+
+    public HealthCheckStatus getStatus() {
+        return status;
+    }
+
+    public void setStatus(HealthCheckStatus status) {
+        this.status = status;
+    }
+
+    @Override
+    public String toString() {
+        return new ToStringBuilder(this).append("subsystem", subsystem).append("uri", uri).append("status", status)
+                .toString();
+    }
+
+    @Override
+    public boolean equals(final Object other) {
+        if (!(other instanceof HealthCheck)) {
+            return false;
+        }
+        HealthCheck castOther = (HealthCheck) other;
+        return new EqualsBuilder().append(subsystem, castOther.subsystem).append(uri, castOther.uri)
+                .append(status, castOther.status).isEquals();
+    }
+
+    @Override
+    public int hashCode() {
+        return new HashCodeBuilder().append(subsystem).append(uri).append(status).toHashCode();
+    }
+
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConfig.java
new file mode 100644 (file)
index 0000000..11fd94b
--- /dev/null
@@ -0,0 +1,83 @@
+/*-
+ * ============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.apihandlerinfra;
+
+import java.net.URI;
+import java.util.List;
+import javax.validation.constraints.NotNull;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.validation.annotation.Validated;
+
+@Configuration
+@ConfigurationProperties(prefix = "mso.health")
+@Validated
+public class HealthCheckConfig {
+
+    @NotNull
+    private List<Endpoint> endpoints;
+
+    public List<Endpoint> getEndpoints() {
+        return endpoints;
+    }
+
+    public void setEndpoints(List<Endpoint> endpoints) {
+        this.endpoints = endpoints;
+    }
+
+    @Override
+    public String toString() {
+        return new ToStringBuilder(this).append("endpoints", this.endpoints).toString();
+    }
+
+    @Validated
+    public static class Endpoint {
+        @NotNull
+        private Subsystem subsystem;
+        @NotNull
+        private URI uri;
+
+        public Endpoint() {
+
+        }
+
+        public Endpoint(Subsystem subsystem, URI uri) {
+            this.subsystem = subsystem;
+            this.uri = uri;
+        }
+
+        public Subsystem getSubsystem() {
+            return subsystem;
+        }
+
+        public void setSubsystem(Subsystem subsystem) {
+            this.subsystem = subsystem;
+        }
+
+        public URI getUri() {
+            return uri;
+        }
+
+        public void setUri(URI uri) {
+            this.uri = uri;
+        }
+    }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckConverter.java
new file mode 100644 (file)
index 0000000..ed06018
--- /dev/null
@@ -0,0 +1,22 @@
+package org.onap.so.apihandlerinfra;
+
+import java.net.URI;
+import javax.ws.rs.core.UriBuilder;
+import org.springframework.core.convert.TypeDescriptor;
+import org.springframework.stereotype.Component;
+
+@Component
+public class HealthCheckConverter {
+
+
+    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
+        if (sourceType.getType() == String.class && targetType.getType() == Subsystem.class) {
+            return SoSubsystems.valueOf(((String) source).toUpperCase());
+        } else if (sourceType.getType() == String.class && targetType.getType() == URI.class) {
+            return UriBuilder.fromUri((String) source).build();
+        } else {
+            return source;
+        }
+    }
+
+}
  * limitations under the License.
  * ============LICENSE_END=========================================================
  */
+package org.onap.so.apihandlerinfra;
 
-package org.onap.so.bpmn.common.util;
+import java.util.ArrayList;
+import java.util.List;
 
-public interface ICryptoHandler {
-    public String getMsoAaiPassword();
+public class HealthCheckResponse {
+
+
+    private List<HealthCheckSubsystem> subsystems = new ArrayList<>();
+    private String message;
+
+
+    public List<HealthCheckSubsystem> getSubsystems() {
+        return subsystems;
+    }
+
+    public void setSubsystems(List<HealthCheckSubsystem> subsystems) {
+        this.subsystems = subsystems;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
 
-    public String encryptMsoPassword(String plainPwd);
 
-    public String decryptMsoPassword(String encryptedPwd);
 }
  */
 package org.onap.so.apihandlerinfra;
 
-public enum HealthcheckStatus {
+public enum HealthCheckStatus {
     UP("UP"), DOWN("DOWN");
 
     private String status;
 
-    private HealthcheckStatus(String status) {
+    private HealthCheckStatus(String status) {
         this.status = status;
     }
 
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthCheckSubsystem.java
new file mode 100644 (file)
index 0000000..e1335b9
--- /dev/null
@@ -0,0 +1,40 @@
+package org.onap.so.apihandlerinfra;
+
+import java.net.URI;
+
+public class HealthCheckSubsystem {
+
+    private Subsystem subsystem;
+    private URI uri;
+    private HealthCheckStatus status;
+
+    public HealthCheckSubsystem(Subsystem subsystem, URI uri, HealthCheckStatus status) {
+        this.subsystem = subsystem;
+        this.uri = uri;
+        this.status = status;
+    }
+
+    public Subsystem getSubsystem() {
+        return subsystem;
+    }
+
+    public void setSubsystem(Subsystem subsystem) {
+        this.subsystem = subsystem;
+    }
+
+    public URI getUri() {
+        return uri;
+    }
+
+    public void setUri(URI uri) {
+        this.uri = uri;
+    }
+
+    public HealthCheckStatus getStatus() {
+        return status;
+    }
+
+    public void setStatus(HealthCheckStatus status) {
+        this.status = status;
+    }
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java
deleted file mode 100644 (file)
index fad3dd4..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-/*-
- * ============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.apihandlerinfra;
-
-import org.apache.commons.lang3.builder.ToStringBuilder;
-
-public class HealthcheckResponse {
-    private String apih;
-    private String bpmn;
-    private String sdncAdapter;
-    private String asdcController;
-    private String catalogdbAdapter;
-    private String requestdbAdapter;
-    private String openstackAdapter;
-    private String requestdbAdapterAttsvc;
-    private String message = "";
-
-    public String getApih() {
-        return apih;
-    }
-
-    public void setApih(String apih) {
-        this.apih = apih;
-    }
-
-    public String getBpmn() {
-        return bpmn;
-    }
-
-    public void setBpmn(String bpmn) {
-        this.bpmn = bpmn;
-    }
-
-    public String getSdncAdapter() {
-        return sdncAdapter;
-    }
-
-    public void setSdncAdapter(String sdncAdapter) {
-        this.sdncAdapter = sdncAdapter;
-    }
-
-    public String getAsdcController() {
-        return asdcController;
-    }
-
-    public void setAsdcController(String asdcController) {
-        this.asdcController = asdcController;
-    }
-
-    public String getCatalogdbAdapter() {
-        return catalogdbAdapter;
-    }
-
-    public void setCatalogdbAdapter(String catalogdbAdapter) {
-        this.catalogdbAdapter = catalogdbAdapter;
-    }
-
-    public String getRequestdbAdapter() {
-        return requestdbAdapter;
-    }
-
-    public void setRequestdbAdapter(String requestdbAdapter) {
-        this.requestdbAdapter = requestdbAdapter;
-    }
-
-    public String getOpenstackAdapter() {
-        return openstackAdapter;
-    }
-
-    public void setOpenstackAdapter(String openstackAdapter) {
-        this.openstackAdapter = openstackAdapter;
-    }
-
-    public String getRequestdbAdapterAttsvc() {
-        return requestdbAdapterAttsvc;
-    }
-
-    public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) {
-        this.requestdbAdapterAttsvc = requestdbAdapterAttsvc;
-    }
-
-    public String getMessage() {
-        return message;
-    }
-
-    public void setMessage(String message) {
-        this.message = message;
-    }
-
-    @Override
-    public String toString() {
-        return new ToStringBuilder(this).append("apih", this.apih).append("pbmn", this.bpmn)
-                .append("sdncAdapter", this.sdncAdapter).append("asdcController", this.asdcController)
-                .append("catalogdbAdapter", this.catalogdbAdapter).append("requestdbAdapter", this.requestdbAdapter)
-                .append("openstackAdapter", this.openstackAdapter)
-                .append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc).append("message", this.message)
-                .toString();
-    }
-}
index 554c794..15572f2 100644 (file)
@@ -216,7 +216,7 @@ public class InstanceManagement {
 
         try {
             recipeLookupResult = getCustomWorkflowUri(workflowUuid);
-        } catch (IOException e) {
+        } catch (Exception e) {
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
@@ -243,7 +243,7 @@ public class InstanceManagement {
         return recipeLookupResult;
     }
 
-    private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException {
+    private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) {
 
         String recipeUri = null;
         Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
index 6f36fb2..a5ccb1b 100644 (file)
@@ -42,6 +42,7 @@ import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriInfo;
 import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.EnumUtils;
 import org.apache.http.HttpStatus;
 import org.onap.so.apihandler.common.ErrorNumbers;
 import org.onap.so.apihandler.common.ResponseBuilder;
@@ -411,7 +412,11 @@ public class OrchestrationRequests {
 
     protected String mapRequestStatusToRequest(InfraActiveRequests iar, String format) {
         if (iar.getRequestStatus() != null) {
-            if (!StringUtils.isBlank(format) && OrchestrationRequestFormat.DETAIL.toString().equalsIgnoreCase(format)) {
+            boolean requestFormat = false;
+            if (format != null) {
+                requestFormat = EnumUtils.isValidEnum(OrchestrationRequestFormat.class, format.toUpperCase());
+            }
+            if (requestFormat) {
                 return iar.getRequestStatus();
             } else {
                 if (Status.ABORTED.toString().equalsIgnoreCase(iar.getRequestStatus())
index 9ab95a2..2fddfd9 100644 (file)
@@ -295,7 +295,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
         InfraActiveRequests dup = null;
         try {
-            if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance
+            if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
                     || action == Action.activateInstance || action == Action.assignInstance))) {
                 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
             }
@@ -334,7 +334,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
         }
         for (HistoricProcessInstance instance : response.getBody()) {
-            if (instance.getState().equals("ACTIVE")) {
+            if (("ACTIVE").equals(instance.getState())) {
                 return true;
             } else {
                 updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
@@ -479,24 +479,11 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             boolean isAlaCarte, Actions action) throws IOException {
         ObjectMapper mapper = new ObjectMapper();
         mapper.setSerializationInclusion(Include.NON_NULL);
-        if (msoRawRequest != null) {
-            ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class);
-            if (serviceInstRequest != null && serviceInstRequest.getRequestDetails() != null
-                    && serviceInstRequest.getRequestDetails().getRequestParameters() != null) {
-                if (!isAlaCarte && Action.createInstance.equals(action)) {
-                    sir.getRequestDetails()
-                            .setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration());
-                    sir.getRequestDetails().getRequestParameters().setUserParams(
-                            serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams());
-                }
-                sir.getRequestDetails().getRequestParameters()
-                        .setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload());
-            }
-
-            logger.debug("Value as string: {}", mapper.writeValueAsString(sir));
-            return mapper.writeValueAsString(sir);
+        if (serviceInstRequest != null) {
+            return mapper.writeValueAsString(serviceInstRequest);
+        } else {
+            return msoRawRequest;
         }
-        return null;
     }
 
     public Optional<String> retrieveModelName(RequestParameters requestParams) {
index 5b827d9..b1d3898 100644 (file)
@@ -51,6 +51,7 @@ import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
 import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler;
+import org.onap.so.apihandlerinfra.infra.rest.validators.RequestValidatorListenerRunner;
 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
 import org.onap.so.constants.Status;
 import org.onap.so.db.catalog.beans.NetworkResource;
@@ -124,6 +125,9 @@ public class ServiceInstances extends AbstractRestHandler {
     @Autowired
     private RequestHandlerUtils requestHandlerUtils;
 
+    @Autowired
+    private RequestValidatorListenerRunner requestValidatorListenerRunner;
+
     @POST
     @Path("/{version:[vV][5-7]}/serviceInstances")
     @Consumes(MediaType.APPLICATION_JSON)
@@ -764,6 +768,13 @@ public class ServiceInstances extends AbstractRestHandler {
 
     public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap,
             String version, String requestId, String requestUri) throws ApiException {
+        return serviceInstances(requestJSON, action, instanceIdMap, version, requestId, requestUri, null);
+
+    }
+
+    public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap,
+            String version, String requestId, String requestUri, HashMap<String, String> queryParams)
+            throws ApiException {
         String serviceInstanceId;
         Boolean aLaCarte = null;
         ServiceInstancesRequest sir;
@@ -771,6 +782,8 @@ public class ServiceInstances extends AbstractRestHandler {
 
         sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri);
         action = handleReplaceInstance(action, sir);
+        requestValidatorListenerRunner.runValidations(requestUri, instanceIdMap, sir, queryParams);
+
         String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
         InfraActiveRequests currentActiveReq =
                 msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
  */
 package org.onap.so.apihandlerinfra;
 
-public enum MsoSubsystems {
+public enum SoSubsystems implements Subsystem {
     APIH("API Handler"),
     ASDC("ASDC Controller"),
     BPMN("BPMN Infra"),
     CATALOGDB("CatalogDb Adapter"),
     OPENSTACK("Openstack Adapter"),
     REQUESTDB("RequestDB Adapter"),
-    REQUESTDBATT("RequestDB Adapter ATT Svc"),
     SDNC("SDNC Adapter");
+
     private String subsystem;
 
-    private MsoSubsystems(String subsystem) {
+    private SoSubsystems(String subsystem) {
         this.subsystem = subsystem;
     }
 
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Subsystem.java
new file mode 100644 (file)
index 0000000..88626f3
--- /dev/null
@@ -0,0 +1,5 @@
+package org.onap.so.apihandlerinfra;
+
+public interface Subsystem {
+
+}
index 7bd7f95..3c4c90c 100644 (file)
@@ -91,7 +91,7 @@ public class TasksHandler {
             @QueryParam("originalRequestDate") String originalRequestDate,
             @QueryParam("originalRequestorId") String originalRequestorId, @PathParam("version") String version)
             throws ApiException {
-        Response responseBack = null;
+
         String apiVersion = version.substring(1);
 
         // Prepare the query string to /task interface
@@ -159,60 +159,49 @@ public class TasksHandler {
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
                             .build();
+            throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+                    HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo)
+                            .build();
 
-
-            ValidateException validateException =
-                    new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
-                            HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
-                                    .errorInfo(errorLoggerInfo).build();
-
-            throw validateException;
         } catch (IOException e) {
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
                             .build();
-            BPMNFailureException bpmnFailureException =
-                    new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
-                            HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
-            throw bpmnFailureException;
+            throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY,
+                    ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
         }
         TasksGetResponse trr = new TasksGetResponse();
         List<TaskList> taskList = new ArrayList<>();
 
         ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
         int bpelStatus = respHandler.getStatus();
-        if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) {
-            String respBody = respHandler.getResponseBody();
-            if (respBody != null) {
-                JSONArray data = new JSONArray(respBody);
+        String respBody = respHandler.getResponseBody();
+        if ((bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) && (null != respBody)) {
 
-                for (int i = 0; i < data.length(); i++) {
-                    JSONObject taskEntry = data.getJSONObject(i);
-                    String id = taskEntry.getString("id");
-                    if (taskId != null && !taskId.equals(id)) {
-                        continue;
-                    }
-                    // Get variables info for each task ID
-                    TaskList taskListEntry = null;
-                    taskListEntry = getTaskInfo(id);
-
-                    taskList.add(taskListEntry);
+            JSONArray data = new JSONArray(respBody);
 
+            for (int i = 0; i < data.length(); i++) {
+                JSONObject taskEntry = data.getJSONObject(i);
+                String id = taskEntry.getString("id");
+                if (taskId != null && !taskId.equals(id)) {
+                    continue;
                 }
-                trr.setTaskList(taskList);
+                // Get variables info for each task ID
+                TaskList taskListEntry = null;
+                taskListEntry = getTaskInfo(id);
+
+                taskList.add(taskListEntry);
+
             }
+            trr.setTaskList(taskList);
 
         } else {
 
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
                             .build();
-
-
-            BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
-                    bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
-
-            throw bpmnFailureException;
+            throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus,
+                    ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
         }
 
         String jsonResponse = null;
@@ -223,14 +212,10 @@ public class TasksHandler {
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
                             .build();
+            throw new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
+                    HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo)
+                            .build();
 
-
-            ValidateException validateException =
-                    new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
-                            HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
-                                    .errorInfo(errorLoggerInfo).build();
-
-            throw validateException;
         }
 
         return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion);
@@ -250,10 +235,8 @@ public class TasksHandler {
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
                             .build();
-            BPMNFailureException validateException =
-                    new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
-                            HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
-            throw validateException;
+            throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY,
+                    ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
         }
         ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType());
         int bpelStatus = respHandler.getStatus();
@@ -264,14 +247,10 @@ public class TasksHandler {
             } else {
                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
                         ErrorCode.AvailabilityError).build();
+                throw new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
+                        HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo)
+                                .build();
 
-
-
-                BPMNFailureException bpmnFailureException =
-                        new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),
-                                HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
-
-                throw bpmnFailureException;
             }
 
         } else {
@@ -279,20 +258,15 @@ public class TasksHandler {
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
                             .build();
 
-
-
-            BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
-                    bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
-
-
-            throw bpmnFailureException;
+            throw new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus,
+                    ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
         }
 
         return taskList;
 
     }
 
-    private TaskList buildTaskList(String taskId, String respBody) throws JSONException {
+    private TaskList buildTaskList(String taskId, String respBody) {
         TaskList taskList = new TaskList();
         JSONObject variables = new JSONObject(respBody);
 
@@ -317,7 +291,7 @@ public class TasksHandler {
         return taskList;
     }
 
-    private String getOptVariableValue(JSONObject variables, String name) throws JSONException {
+    private String getOptVariableValue(JSONObject variables, String name) {
         String variableEntry = variables.optString(name);
         String value = "";
         if (!variableEntry.isEmpty()) {
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java
new file mode 100644 (file)
index 0000000..344e543
--- /dev/null
@@ -0,0 +1,85 @@
+package org.onap.so.apihandlerinfra.infra.rest;
+
+import java.util.Optional;
+import org.onap.aai.domain.yang.GenericVnf;
+import org.onap.aai.domain.yang.L3Network;
+import org.onap.aai.domain.yang.ServiceInstance;
+import org.onap.aai.domain.yang.VfModule;
+import org.onap.aai.domain.yang.VolumeGroup;
+import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound;
+import org.onap.so.client.aai.AAIObjectType;
+import org.onap.so.client.aai.AAIResourcesClient;
+import org.onap.so.client.aai.entities.AAIResultWrapper;
+import org.onap.so.client.aai.entities.uri.AAIUriFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+@Component
+public class AAIDataRetrieval {
+
+    private static final String VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID = "VF Module Not Found In Inventory, VnfId: ";
+
+    private AAIResourcesClient aaiResourcesClient;
+
+    private static final Logger logger = LoggerFactory.getLogger(AAIDataRetrieval.class);
+
+    public ServiceInstance getServiceInstance(String serviceInstanceId) {
+        return this.getAaiResourcesClient()
+                .get(ServiceInstance.class,
+                        AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId))
+                .orElseGet(() -> {
+                    logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId);
+                    return null;
+                });
+    }
+
+
+    public VfModule getAAIVfModule(String vnfId, String vfModuleId) {
+        return this.getAaiResourcesClient()
+                .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId))
+                .orElseGet(() -> {
+                    logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId);
+                    return null;
+                });
+    }
+
+    public GenericVnf getGenericVnf(String vnfId) {
+        return this.getAaiResourcesClient()
+                .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
+                .orElseGet(() -> {
+                    logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId);
+                    return null;
+                });
+    }
+
+    public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound {
+        AAIResultWrapper wrapper =
+                this.getAaiResourcesClient().get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)
+                        .relatedTo(AAIObjectType.VOLUME_GROUP, volumeGroupId));
+        Optional<VolumeGroup> volume = wrapper.asBean(VolumeGroup.class);
+        if (volume.isPresent()) {
+            return volume.get();
+        } else {
+            logger.debug("No VolumeGroup in A&AI found: {}", vnfId);
+            return null;
+        }
+    }
+
+    public L3Network getNetwork(String networkId) {
+        return this.getAaiResourcesClient()
+                .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId))
+                .orElseGet(() -> {
+                    logger.debug("No Network found in A&AI NetworkId: {}", networkId);
+                    return null;
+                });
+    }
+
+    protected AAIResourcesClient getAaiResourcesClient() {
+        if (aaiResourcesClient == null) {
+            aaiResourcesClient = new AAIResourcesClient();
+        }
+        return aaiResourcesClient;
+    }
+
+}
index bb5b4ed..ee2bb58 100644 (file)
@@ -33,10 +33,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants;
 import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound;
 import org.onap.so.apihandlerinfra.infra.rest.exception.CloudConfigurationNotFoundException;
 import org.onap.so.client.aai.AAIObjectType;
-import org.onap.so.client.aai.AAIResourcesClient;
 import org.onap.so.client.aai.entities.AAIResultWrapper;
-import org.onap.so.client.aai.entities.uri.AAIResourceUri;
-import org.onap.so.client.aai.entities.uri.AAIUriFactory;
 import org.onap.so.constants.Status;
 import org.onap.so.db.request.beans.InfraActiveRequests;
 import org.onap.so.db.request.client.RequestsDbClient;
@@ -75,17 +72,19 @@ public class BpmnRequestBuilder {
     @Autowired
     private RequestsDbClient infraActiveRequestsClient;
 
+    @Autowired
+    private AAIDataRetrieval aaiDataRet;
+
     private ObjectMapper mapper = new ObjectMapper();
 
-    private AAIResourcesClient aaiResourcesClient;
 
     public ServiceInstancesRequest buildVFModuleDeleteRequest(String vnfId, String vfModuleId, ModelType modelType)
             throws AAIEntityNotFound {
-        GenericVnf vnf = getGenericVnf(vnfId);
+        GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId);
         if (vnf == null) {
             throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId);
         }
-        VfModule vfModule = getAAIVfModule(vnfId, vfModuleId);
+        VfModule vfModule = aaiDataRet.getAAIVfModule(vnfId, vfModuleId);
         if (vfModule == null) {
             throw new AAIEntityNotFound(VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " vfModuleId: " + vfModuleId);
         }
@@ -94,11 +93,11 @@ public class BpmnRequestBuilder {
 
     public ServiceInstancesRequest buildVolumeGroupDeleteRequest(String vnfId, String volumeGroupId)
             throws AAIEntityNotFound {
-        GenericVnf vnf = getGenericVnf(vnfId);
+        GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId);
         if (vnf == null) {
             throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId);
         }
-        VolumeGroup volumeGroup = getVolumeGroup(vnfId, volumeGroupId);
+        VolumeGroup volumeGroup = aaiDataRet.getVolumeGroup(vnfId, volumeGroupId);
         if (volumeGroup == null) {
             throw new AAIEntityNotFound(
                     VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId);
@@ -107,7 +106,7 @@ public class BpmnRequestBuilder {
     }
 
     public ServiceInstancesRequest buildServiceDeleteRequest(String serviceInstanceId) throws AAIEntityNotFound {
-        ServiceInstance serviceInstance = getServiceInstance(serviceInstanceId);
+        ServiceInstance serviceInstance = aaiDataRet.getServiceInstance(serviceInstanceId);
         if (serviceInstance == null) {
             throw new AAIEntityNotFound(
                     "ServiceInstance Not Found In Inventory, ServiceInstanceId: " + serviceInstanceId);
@@ -116,7 +115,7 @@ public class BpmnRequestBuilder {
     }
 
     public ServiceInstancesRequest buildVnfDeleteRequest(String vnfId) throws AAIEntityNotFound {
-        GenericVnf vnf = getGenericVnf(vnfId);
+        GenericVnf vnf = aaiDataRet.getGenericVnf(vnfId);
         if (vnf == null) {
             throw new AAIEntityNotFound(GENERIC_VNF_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId);
         }
@@ -124,7 +123,7 @@ public class BpmnRequestBuilder {
     }
 
     public ServiceInstancesRequest buildNetworkDeleteRequest(String networkId) throws AAIEntityNotFound {
-        L3Network network = getNetwork(networkId);
+        L3Network network = aaiDataRet.getNetwork(networkId);
         if (network == null) {
             throw new AAIEntityNotFound("Network Not Found In Inventory, NetworkId: " + networkId);
         }
@@ -407,72 +406,5 @@ public class BpmnRequestBuilder {
         return requestParams;
     }
 
-    public VfModule getAAIVfModule(String vnfId, String vfModuleId) {
-        return this.getAaiResourcesClient()
-                .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId))
-                .orElseGet(() -> {
-                    logger.debug("No Vf Module found in A&AI VnfId: {}" + ", VfModuleId: {}", vnfId, vfModuleId);
-                    return null;
-                });
-    }
-
-    public GenericVnf getGenericVnf(String vnfId) {
-        return this.getAaiResourcesClient()
-                .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId))
-                .orElseGet(() -> {
-                    logger.debug("No Generic VNF found in A&AI VnfId: {}", vnfId);
-                    return null;
-                });
-    }
-
-    public VolumeGroup getVolumeGroup(String vnfId, String volumeGroupId) throws AAIEntityNotFound {
-        GenericVnf vnf = getGenericVnf(vnfId);
-        AAIResultWrapper wrapper = new AAIResultWrapper(vnf);
-        List<AAIResourceUri> listVserverWrapper;
-        Optional<AAIResourceUri> volumeGroupURI;
-        if (wrapper.getRelationships().isPresent()) {
-            listVserverWrapper = wrapper.getRelationships().get().getRelatedUris(AAIObjectType.VOLUME_GROUP);
-            volumeGroupURI = listVserverWrapper.stream()
-                    .filter(resourceURI -> resourceURI.getURIKeys().get("volume-group-id").equals(volumeGroupId))
-                    .findFirst();
-        } else {
-            throw new AAIEntityNotFound(
-                    VF_MODULE_NOT_FOUND_IN_INVENTORY_VNF_ID + vnfId + " volumeGroupId: " + volumeGroupId);
-        }
-        return this.getAaiResourcesClient().get(VolumeGroup.class, volumeGroupURI.get()).orElseGet(() -> {
-            logger.debug("No VolumeGroup in A&AI found: {}", vnfId);
-            return null;
-        });
-    }
-
-    public ServiceInstance getServiceInstance(String serviceInstanceId) {
-        return this.getAaiResourcesClient()
-                .get(ServiceInstance.class,
-                        AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId))
-                .orElseGet(() -> {
-                    logger.debug("No Service Instance found in A&AI ServiceInstanceId: {}", serviceInstanceId);
-                    return null;
-                });
-    }
-
-    public L3Network getNetwork(String networkId) {
-        return this.getAaiResourcesClient()
-                .get(L3Network.class, AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId))
-                .orElseGet(() -> {
-                    logger.debug("No Network found in A&AI NetworkId: {}", networkId);
-                    return null;
-                });
-    }
-
-    public AAIResourcesClient getAaiResourcesClient() {
-        if (aaiResourcesClient == null) {
-            aaiResourcesClient = new AAIResourcesClient();
-        }
-        return aaiResourcesClient;
-    }
-
-    public void setAaiResourcesClient(AAIResourcesClient aaiResourcesClient) {
-        this.aaiResourcesClient = aaiResourcesClient;
-    }
 
 }
index b5b548a..e11732d 100644 (file)
@@ -23,7 +23,7 @@ package org.onap.so.apihandlerinfra.infra.rest.handler;
 import java.io.IOException;
 import java.net.URL;
 import java.sql.Timestamp;
-import java.util.HashMap;
+import java.util.Map;
 import java.util.Optional;
 import javax.ws.rs.container.ContainerRequestContext;
 import org.apache.http.HttpStatus;
@@ -63,7 +63,7 @@ public abstract class AbstractRestHandler {
 
     private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class);
 
-    public static final String conflictFailMessage = "Error: Locked instance - This %s (%s) "
+    public static final String CONFLICT_FAIL_MESSAGE = "Error: Locked instance - This %s (%s) "
             + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
 
 
@@ -95,22 +95,19 @@ public abstract class AbstractRestHandler {
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
-            ValidateException validateException =
-                    new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
-                            HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
-                                    .errorInfo(errorLoggerInfo).build();
-
-            throw validateException;
+            throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
+                    HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
+                            .build();
         }
     }
 
-    public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
+    public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
             MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
             throws ApiException {
         return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq);
     }
 
-    public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime,
+    public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
         InfraActiveRequests dup = null;
         try {
@@ -134,19 +131,19 @@ public abstract class AbstractRestHandler {
 
     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
             throws RequestDbFailureException {
-        if (aq != null) {
-            if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
-                aq.setStatusMessage(errorMessage);
-                aq.setProgress(100L);
-                aq.setRequestStatus(status.toString());
-                Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
-                aq.setEndTime(endTimeStamp);
-                try {
-                    infraActiveRequestsClient.updateInfraActiveRequests(aq);
-                } catch (Exception e) {
-                    logger.error("Error updating status", e);
-                }
+        if ((aq != null) && ((status == Status.FAILED) || (status == Status.COMPLETE))) {
+
+            aq.setStatusMessage(errorMessage);
+            aq.setProgress(100L);
+            aq.setRequestStatus(status.toString());
+            Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
+            aq.setEndTime(endTimeStamp);
+            try {
+                infraActiveRequestsClient.updateInfraActiveRequests(aq);
+            } catch (Exception e) {
+                logger.error("Error updating status", e);
             }
+
         }
     }
 
@@ -178,15 +175,15 @@ public abstract class AbstractRestHandler {
             selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
         } catch (Exception e) {
             selfLinkUrl = Optional.empty(); // ignore
-            logger.info(e.getMessage());
+            logger.error(e.getMessage());
         }
         return selfLinkUrl;
     }
 
     /**
-     * @param vfmoduleInstanceId
+     * @param instanceId
      * @param requestId
-     * @param response
+     * @param requestContext
      */
     public ServiceInstancesResponse createResponse(String instanceId, String requestId,
             ContainerRequestContext requestContext) {
@@ -202,13 +199,13 @@ public abstract class AbstractRestHandler {
         return response;
     }
 
-    public void checkDuplicateRequest(HashMap<String, String> instanceIdMap, ModelType modelType, String instanceName,
+    public void checkDuplicateRequest(Map<String, String> instanceIdMap, ModelType modelType, String instanceName,
             String requestId) throws RequestConflictedException {
         InfraActiveRequests conflictedRequest =
                 infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString());
         if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) {
-            throw new RequestConflictedException(String.format(conflictFailMessage, modelType.toString(), instanceName,
-                    conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId()));
+            throw new RequestConflictedException(String.format(CONFLICT_FAIL_MESSAGE, modelType.toString(),
+                    instanceName, conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId()));
         }
     }
 
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidator.java
new file mode 100644 (file)
index 0000000..4aa6015
--- /dev/null
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.apihandlerinfra.infra.rest.validators;
+
+import java.util.Map;
+import java.util.Optional;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+
+public interface RequestValidator {
+
+
+    /**
+     * Should this validator run for given request
+     * 
+     * @return
+     */
+    public boolean shouldRunFor(String uri, ServiceInstancesRequest request);
+
+
+    public Optional<String> validate(Map<String, String> instanceIdMap, ServiceInstancesRequest request,
+            Map<String, String> queryParams);
+}
diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/validators/RequestValidatorListenerRunner.java
new file mode 100644 (file)
index 0000000..d689c6b
--- /dev/null
@@ -0,0 +1,80 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.apihandlerinfra.infra.rest.validators;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
+import org.javatuples.Pair;
+import org.onap.so.apihandlerinfra.exceptions.ApiException;
+import org.onap.so.apihandlerinfra.exceptions.ValidateException;
+import org.onap.so.listener.ListenerRunner;
+import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+@Component
+public class RequestValidatorListenerRunner extends ListenerRunner {
+
+    private static Logger logger = LoggerFactory.getLogger(RequestValidatorListenerRunner.class);
+
+    protected List<RequestValidator> requestValidators;
+
+    @PostConstruct
+    protected void init() {
+        requestValidators = new ArrayList<>(
+                Optional.ofNullable(context.getBeansOfType(RequestValidator.class)).orElse(new HashMap<>()).values());
+    }
+
+    public boolean runValidations(String requestURI, Map<String, String> instanceIdMap, ServiceInstancesRequest request,
+            Map<String, String> queryParams) throws ApiException {
+        logger.info("Running local validations");
+        List<Pair<String, Optional<String>>> results =
+                runValidations(requestValidators, instanceIdMap, request, queryParams, requestURI);
+        if (!results.isEmpty()) {
+            throw new ValidateException("Failed Validations:\n"
+                    + results.stream().map(item -> String.format("%s: %s", item.getValue0(), item.getValue1().get()))
+                            .collect(Collectors.joining("\n")),
+                    400);
+        }
+
+        return true;
+    }
+
+    protected List<Pair<String, Optional<String>>> runValidations(List<? extends RequestValidator> validators,
+            Map<String, String> instanceIdMap, ServiceInstancesRequest request, Map<String, String> queryParams,
+            String requestURI) {
+
+        List<? extends RequestValidator> filtered =
+                filterListeners(validators, (item -> item.shouldRunFor(requestURI, request)));
+
+        List<Pair<String, Optional<String>>> results = new ArrayList<>();
+        filtered.forEach(item -> results
+                .add(new Pair<>(item.getClass().getName(), item.validate(instanceIdMap, request, queryParams))));
+
+        return results.stream().filter(item -> item.getValue1().isPresent()).collect(Collectors.toList());
+    }
+}
index 2165884..ef5abe9 100644 (file)
@@ -137,10 +137,8 @@ public class ModelDistributionRequest {
         se.setMessageId(messageId);
         se.setText(text);
         if (variables != null) {
-            if (variables != null) {
-                for (String variable : variables) {
-                    se.getVariables().add(variable);
-                }
+            for (String variable : variables) {
+                se.getVariables().add(variable);
             }
         }
         re.setServiceException(se);
index 71405b0..20be2b5 100644 (file)
@@ -43,7 +43,8 @@ public class PlatformLOBValidation implements ValidationRule {
 
         platform = info.getSir().getRequestDetails().getPlatform();
         lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness();
-        if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) {
+        if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance
+                && !info.getReqParameters().getEnforceValidNfValues()) {
             if (reqVersion > 5 && platform == null) {
                 throw new ValidationException("platform");
             }
index 5842697..cebbd63 100644 (file)
@@ -41,10 +41,12 @@ public class ProjectOwningEntityValidation implements ValidationRule {
         String requestScope = info.getRequestScope();
         Actions action = info.getAction();
 
+
         project = info.getSir().getRequestDetails().getProject();
         owningEntity = info.getSir().getRequestDetails().getOwningEntity();
         if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name())
-                && action == Action.createInstance || action == Action.assignInstance) {
+                && !info.getReqParameters().getEnforceValidNfValues() && action == Action.createInstance
+                || action == Action.assignInstance) {
             if (reqVersion > 5 && owningEntity == null) {
                 throw new ValidationException("owningEntity");
             }
index e6b5163..830f38f 100644 (file)
@@ -30,6 +30,7 @@ import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity;
 import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
@@ -119,7 +120,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameTest() throws IOException {
+    public void getActivityNameTest() {
         String expectedActivityName = "Last task executed: BB to Execute";
         String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
 
@@ -127,7 +128,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameNullActivityNameTest() throws IOException {
+    public void getActivityNameNullActivityNameTest() {
         String expectedActivityName = "Task name is null.";
         HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity();
         List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>();
@@ -139,7 +140,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameNullListTest() throws IOException {
+    public void getActivityNameNullListTest() {
         String expectedActivityName = "No results returned on activityInstance history lookup.";
         List<HistoricActivityInstanceEntity> activityInstanceList = null;
         String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
@@ -148,7 +149,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameEmptyListTest() throws IOException {
+    public void getActivityNameEmptyListTest() {
         String expectedActivityName = "No results returned on activityInstance history lookup.";
         List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>();
         String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
@@ -157,7 +158,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameTest() throws IOException, ContactCamundaException {
+    public void getTaskNameTest() throws ContactCamundaException {
         doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID);
         doReturn(activityInstanceResponse).when(camundaRequestHandler)
                 .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID);
@@ -170,7 +171,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException {
+    public void getTaskNameNullProcessInstanceListTest() throws ContactCamundaException {
         ResponseEntity<List<HistoricProcessInstanceEntity>> response = new ResponseEntity<>(null, HttpStatus.OK);
         doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID);
         String expected = "No processInstances returned for requestId: " + REQUEST_ID;
@@ -181,7 +182,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException {
+    public void getTaskNameNullProcessInstanceIdTest() throws ContactCamundaException {
         HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity();
         List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>();
         processInstanceList.add(processInstance);
@@ -196,7 +197,19 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException {
+    public void getTaskNameEmptyProcessInstanceListTest() throws ContactCamundaException {
+        ResponseEntity<List<HistoricProcessInstanceEntity>> response =
+                new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
+        doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID);
+        String expected = "No processInstances returned for requestId: " + REQUEST_ID;
+
+        String actual = camundaRequestHandler.getTaskName(REQUEST_ID);
+
+        assertEquals(expected, actual);
+    }
+
+    @Test
+    public void getTaskNameProcessInstanceLookupFailureTest() throws ContactCamundaException {
         doThrow(HttpClientErrorException.class).when(camundaRequestHandler)
                 .getCamundaProcessInstanceHistory(REQUEST_ID);
 
@@ -205,7 +218,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException {
+    public void getCamundaActivityHistoryTest() throws ContactCamundaException {
         HttpHeaders headers = setHeaders();
         HttpEntity<?> requestEntity = new HttpEntity<>(headers);
         String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId="
@@ -239,7 +252,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException {
+    public void getCamundaProccesInstanceHistoryTest() {
         HttpHeaders headers = setHeaders();
         HttpEntity<?> requestEntity = new HttpEntity<>(headers);
         String targetUrl =
@@ -292,7 +305,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException {
+    public void getCamundaProccesInstanceHistoryFailThenSuccessTest() {
         HttpHeaders headers = setHeaders();
         HttpEntity<?> requestEntity = new HttpEntity<>(headers);
         String targetUrl =
@@ -310,7 +323,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException {
+    public void setCamundaHeadersTest() {
         String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password
         String key = "07a7159d3bf51a0e53be7a8f89699be7";
 
index 928b488..0291cfd 100644 (file)
 
 package org.onap.so.apihandlerinfra;
 
-import static org.junit.Assert.assertArrayEquals;
+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.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyObject;
+import static org.junit.Assert.assertThat;
 import static org.mockito.ArgumentMatchers.anyString;
 import java.net.URI;
-import java.util.Collections;
-import java.util.List;
-import org.springframework.test.util.ReflectionTestUtils;
 import javax.ws.rs.container.ContainerRequestContext;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriBuilder;
-import org.springframework.core.ParameterizedTypeReference;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
 import org.json.JSONException;
-import org.junit.Rule;
 import org.junit.Test;
-import org.mockito.InjectMocks;
+import org.junit.runner.RunWith;
 import org.mockito.ArgumentMatchers;
-import org.mockito.Mock;
 import org.mockito.Mockito;
-import org.mockito.Spy;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoRule;
+import org.onap.so.apihandlerinfra.HealthCheckConfig.Endpoint;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.boot.test.mock.mockito.SpyBean;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.util.ReflectionTestUtils;
 import org.springframework.web.client.RestTemplate;
+import com.fasterxml.jackson.core.JsonProcessingException;
 
 
+@RunWith(SpringRunner.class)
+@ContextConfiguration(classes = {GenericStringConverter.class, HealthCheckConverter.class},
+        initializers = {ConfigFileApplicationContextInitializer.class})
+@ActiveProfiles("test")
+@EnableConfigurationProperties({HealthCheckConfig.class})
 public class GlobalHealthcheckHandlerTest {
-    @Mock
-    RestTemplate restTemplate;
+    @MockBean
+    private RestTemplate restTemplate;
 
-    @Mock
-    ContainerRequestContext requestContext;
+    @MockBean
+    private ContainerRequestContext requestContext;
 
-    @InjectMocks
-    @Spy
-    GlobalHealthcheckHandler globalhealth;
-
-    @Rule
-    public MockitoRule mockitoRule = MockitoJUnit.rule();
+    @SpyBean
+    private GlobalHealthcheckHandler globalhealth;
 
     @Test
     public void testQuerySubsystemHealthNullResult() {
         ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
-        ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080");
 
         Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class),
                 ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(null);
 
-        String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN);
-        System.out.println(result);
-        assertEquals(HealthcheckStatus.DOWN.toString(), result);
+        HealthCheckSubsystem result = globalhealth
+                .querySubsystemHealth(new Endpoint(SoSubsystems.BPMN, UriBuilder.fromPath("http://localhost").build()));
+        assertEquals(HealthCheckStatus.DOWN, result.getStatus());
     }
 
     @Test
     public void testQuerySubsystemHealthNotNullResult() {
         ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
-        ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
 
         SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
         subSystemResponse.setStatus("UP");
@@ -92,20 +89,13 @@ public class GlobalHealthcheckHandlerTest {
         Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class),
                 ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r);
 
-        String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC);
-        System.out.println(result);
-        assertEquals(HealthcheckStatus.UP.toString(), result);
+        HealthCheckSubsystem result = globalhealth
+                .querySubsystemHealth(new Endpoint(SoSubsystems.ASDC, UriBuilder.fromPath("http://localhost").build()));
+        assertEquals(HealthCheckStatus.UP, result.getStatus());
     }
 
     private Response globalHealthcheck(String status) {
         ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
-        ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
-        ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081");
-        ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082");
-        ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083");
-        ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084");
-        ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085");
-        ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086");
 
         SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
 
@@ -116,70 +106,41 @@ public class GlobalHealthcheckHandlerTest {
 
         Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890");
         Response response = globalhealth.globalHealthcheck(true, requestContext);
-
         return response;
     }
 
     @Test
-    public void globalHealthcheckAllUPTest() throws JSONException {
-        Response response = globalHealthcheck("UP");
-        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
-        HealthcheckResponse root;
-        root = (HealthcheckResponse) response.getEntity();
-        String apistatus = root.getApih();
-        assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
-        String bpmnstatus = root.getBpmn();
-        assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
-        String sdncstatus = root.getSdncAdapter();
-        assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+    public void globalHealthcheckAllUPTest() throws JSONException, JsonProcessingException {
 
-        String asdcstatus = root.getAsdcController();
-        assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+        HealthCheckResponse expected = new HealthCheckResponse();
 
-        String catastatus = root.getCatalogdbAdapter();
-        assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
-        String reqdbstatus = root.getRequestdbAdapter();
-        assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
-        String openstatus = root.getOpenstackAdapter();
-        assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
+        for (Subsystem system : SoSubsystems.values()) {
+            expected.getSubsystems().add(new HealthCheckSubsystem(system,
+                    UriBuilder.fromUri("http://localhost").build(), HealthCheckStatus.UP));
+        }
+        expected.setMessage("HttpStatus: 200");
+        Response response = globalHealthcheck("UP");
+        assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+        HealthCheckResponse root;
+        root = (HealthCheckResponse) response.getEntity();
+        assertThat(root, sameBeanAs(expected).ignoring("subsystems.uri").ignoring("subsystems.subsystem"));
 
-        String reqdbattstatus = root.getRequestdbAdapterAttsvc();
-        assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
     }
 
     @Test
     public void globalHealthcheckAllDOWNTest() throws JSONException {
+        HealthCheckResponse expected = new HealthCheckResponse();
+
+        for (Subsystem system : SoSubsystems.values()) {
+            expected.getSubsystems().add(new HealthCheckSubsystem(system,
+                    UriBuilder.fromUri("http://localhost").build(), HealthCheckStatus.DOWN));
+        }
+        expected.setMessage("HttpStatus: 200");
         Response response = globalHealthcheck("DOWN");
         assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
-        HealthcheckResponse root;
-        root = (HealthcheckResponse) response.getEntity();
-        String apistatus = root.getApih();
-        assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString()));
-
-        String bpmnstatus = root.getBpmn();
-        assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
-        String sdncstatus = root.getSdncAdapter();
-        assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
-        String asdcstatus = root.getAsdcController();
-        assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
-        String catastatus = root.getCatalogdbAdapter();
-        assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
-        String reqdbstatus = root.getRequestdbAdapter();
-        assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
-        String openstatus = root.getOpenstackAdapter();
-        assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
-
-        String reqdbattstatus = root.getRequestdbAdapterAttsvc();
-        assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString()));
+        HealthCheckResponse root;
+        root = (HealthCheckResponse) response.getEntity();
+        assertThat(root, sameBeanAs(expected).ignoring("subsystems.uri").ignoring("subsystems.subsystem"));
     }
 
     @Test
@@ -189,40 +150,15 @@ public class GlobalHealthcheckHandlerTest {
         assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getContentType());
     }
 
-    @Test
-    public void getEndpointUrlForSubsystemEnumTest() {
-        ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage");
-        ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080");
-        ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081");
-        ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082");
-        ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083");
-        ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084");
-        ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085");
-        ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086");
-
-        String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC);
-        assertEquals("http://localhost:8080", result);
-        result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC);
-        assertEquals("http://localhost:8081", result);
-        result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN);
-        assertEquals("http://localhost:8082", result);
-        result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB);
-        assertEquals("http://localhost:8083", result);
-        result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK);
-        assertEquals("http://localhost:8084", result);
-        result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB);
-        assertEquals("http://localhost:8085", result);
-        result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT);
-        assertEquals("http://localhost:8086", result);
-    }
 
     @Test
     public void processResponseFromSubsystemTest() {
         SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse();
         subSystemResponse.setStatus("UP");
         ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK);
-        String result = globalhealth.processResponseFromSubsystem(r, MsoSubsystems.BPMN);
-        assertEquals("UP", result);
+        Endpoint endpoint = new Endpoint(SoSubsystems.BPMN, UriBuilder.fromUri("http://localhost").build());
+        HealthCheckStatus result = globalhealth.processResponseFromSubsystem(r, endpoint);
+        assertEquals(HealthCheckStatus.UP, result);
     }
 
 }
index 5023155..f672648 100644 (file)
@@ -295,6 +295,14 @@ public class OrchestrationRequestsUnitTest {
         assertEquals(Status.ABORTED.toString(), result);
     }
 
+    @Test
+    public void mapRequestStatusToRequestForFormatStatusDetailTest() throws ApiException {
+        iar.setRequestStatus(Status.ABORTED.toString());
+        String result = orchestrationRequests.mapRequestStatusToRequest(iar, "statusDetail");
+
+        assertEquals(Status.ABORTED.toString(), result);
+    }
+
 
     @Test
     public void mapRequestStatusToRequestForFormatEmptyStringTest() throws ApiException {
index e28e36d..a79aeb2 100644 (file)
@@ -2934,15 +2934,5 @@ public class ServiceInstancesTest extends BaseTest {
         Actions action = servInstances.handleReplaceInstance(Action.replaceInstance, sir);
         assertEquals(Action.replaceInstanceRetainAssignments, action);
     }
-    /*
-     * @Test public void buildSelfLinkUrlTest() throws Exception { // v - version String incomingUrl =
-     * "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; String expectedSelfLink =
-     * "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; String requestId =
-     * "efce3167-5e45-4666-9d4d-22e23648e5d1"; Optional<URL> actualSelfLinkUrl = buildSelfLinkUrl(incomingUrl,
-     * requestId); assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); // V - Version String
-     * incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; String
-     * expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1";
-     * Optional<URL> actualSelfLinkUrlV = buildSelfLinkUrl(incomingUrlV, requestId); assertEquals(expectedSelfLinkV,
-     * actualSelfLinkUrlV.get().toString()); }
-     */
 }
+
index 3644dd8..f73da49 100644 (file)
@@ -23,6 +23,7 @@ package org.onap.so.apihandlerinfra.infra.rest;
 import static com.shazam.shazamcrest.MatcherAssert.assertThat;
 import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
 import java.io.File;
 import java.util.Optional;
 import org.junit.Before;
@@ -32,7 +33,6 @@ import org.junit.rules.ExpectedException;
 import org.junit.runner.RunWith;
 import org.mockito.InjectMocks;
 import org.mockito.Mock;
-import org.mockito.Spy;
 import org.mockito.junit.MockitoJUnitRunner;
 import org.onap.aai.domain.yang.GenericVnf;
 import org.onap.aai.domain.yang.ServiceInstance;
@@ -40,6 +40,7 @@ import org.onap.aai.domain.yang.VfModule;
 import org.onap.aai.domain.yang.VolumeGroup;
 import org.onap.so.client.aai.AAIObjectType;
 import org.onap.so.client.aai.AAIResourcesClient;
+import org.onap.so.client.aai.entities.AAIResultWrapper;
 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
 import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider;
 import org.onap.so.db.request.client.RequestsDbClient;
@@ -55,15 +56,19 @@ public class BpmnRequestBuilderTest {
     @Rule
     public ExpectedException exceptionRule = ExpectedException.none();
 
+
+    @Mock
+    private AAIResourcesClient aaiResourcesClient;
+
     @InjectMocks
-    @Spy
-    BpmnRequestBuilder reqBuilder;
+    private AAIDataRetrieval aaiData = spy(AAIDataRetrieval.class);
 
     @Mock
     private RequestsDbClient requestDBClient;
 
-    @Mock
-    private AAIResourcesClient aaiResourcesClient;
+    @InjectMocks
+    private BpmnRequestBuilder reqBuilder = spy(BpmnRequestBuilder.class);
+
 
     private ObjectMapper mapper = new ObjectMapper();
 
@@ -71,8 +76,7 @@ public class BpmnRequestBuilderTest {
 
     @Before
     public void setup() {
-        reqBuilder.setAaiResourcesClient(aaiResourcesClient);
-
+        // aaiData.setAaiResourcesClient(aaiResourcesClient);
     }
 
     @Test
@@ -80,11 +84,11 @@ public class BpmnRequestBuilderTest {
         ServiceInstance service =
                 provider.getMapper().readValue(new File(RESOURCE_PATH + "ServiceInstance.json"), ServiceInstance.class);
 
-        doReturn(service).when(reqBuilder).getServiceInstance("serviceId");
+        doReturn(service).when(aaiData).getServiceInstance("serviceId");
         ServiceInstancesRequest expectedRequest = mapper
                 .readValue(new File(RESOURCE_PATH + "ExpectedServiceRequest.json"), ServiceInstancesRequest.class);
-        expectedRequest.getRequestDetails().getModelInfo().setModelId(null);
-        // bad getter/setter setting multiple fields
+        expectedRequest.getRequestDetails().getModelInfo().setModelId(null); // bad getter/setter setting multiple
+                                                                             // fields
         ServiceInstancesRequest actualRequest = reqBuilder.buildServiceDeleteRequest("serviceId");
         assertThat(actualRequest, sameBeanAs(expectedRequest));
     }
@@ -128,13 +132,16 @@ public class BpmnRequestBuilderTest {
                 AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId"));
         VolumeGroup volumeGroup =
                 provider.getMapper().readValue(new File(RESOURCE_PATH + "VolumeGroup.json"), VolumeGroup.class);
-
-        doReturn(Optional.of(volumeGroup)).when(aaiResourcesClient).get(VolumeGroup.class, AAIUriFactory
-                .createResourceUri(AAIObjectType.VOLUME_GROUP, "cloudOwner", "regionOne", "volumeGroupId"));
+        AAIResultWrapper wrapper = new AAIResultWrapper(volumeGroup);
+        doReturn(wrapper).when(aaiResourcesClient)
+                .get(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "vnfId")
+                        .relatedTo(AAIObjectType.VOLUME_GROUP, "volumeGroupId"));
 
         ServiceInstancesRequest expectedRequest = mapper
                 .readValue(new File(RESOURCE_PATH + "ExpectedVolumeGroupRequest.json"), ServiceInstancesRequest.class);
         ServiceInstancesRequest actualRequest = reqBuilder.buildVolumeGroupDeleteRequest("vnfId", "volumeGroupId");
         assertThat(actualRequest, sameBeanAs(expectedRequest));
     }
+
 }
+
diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ServiceInstanceNoOE.json
new file mode 100644 (file)
index 0000000..a6aa3e1
--- /dev/null
@@ -0,0 +1,33 @@
+{
+       "serviceInstanceId":"1882939",
+       "vnfInstanceId":"1882938",
+       "networkInstanceId":"1882937",
+       "volumeGroupInstanceId":"1882935",
+       "vfModuleInstanceId":"1882934",
+       "requestDetails": {
+               "requestInfo": {
+                       "source": "VID", 
+                       "requestorId": "xxxxxx",
+                       "instanceName": "testService9"
+               },
+               "requestParameters": {
+                       "aLaCarte": true,
+                       "autoBuildVfModules": false,
+                       "subscriptionServiceType": "test",
+                       "disableOwningEntityProject": true
+               },
+               "modelInfo":{
+                       "modelInvariantId": "f7ce78bb-423b-11e7-93f8-0050569a7965",
+                       "modelVersion":"1", 
+                       "modelVersionId":"10", 
+                       "modelType":"service",
+                       "modelName":"serviceModel",
+                       "modelInstanceName":"modelInstanceName",
+                       "modelCustomizationId":"f7ce78bb-423b-11e7-93f8-0050569a796"
+               },
+               "subscriberInfo": {
+               "globalSubscriberId": "someTestId", 
+               "subscriberName": "someTestId"
+       }
+       }
+}
index 09f6d81..0b03f56 100644 (file)
                                        },
                                        {
                                                "relationship-key": "volume-group.volume-group-id",
-                                               "relationship-value": "18b220c8-af84-4b82-a8c0-41bbea6328a6"
+                                               "relationship-value": "volumeGroupId"
                                        }
                                ]
                        },
index 2e1c6a9..27e1ae9 100644 (file)
@@ -9,14 +9,20 @@ server:
 mso:
   health:
     endpoints:
-      catalogdb: http://localhost:${wiremock.server.port}
-      requestdb: http://localhost:${wiremock.server.port}
-      sdnc: http://localhost:${wiremock.server.port}
-      openstack: http://localhost:${wiremock.server.port}
-      bpmn: http://localhost:${wiremock.server.port}
-      asdc: http://localhost:${wiremock.server.port}
-      requestdbattsvc: http://localhost:${wiremock.server.port}
-      
+      - subsystem: apih
+        uri: http://localhost:${wiremock.server.port}
+      - subsystem: asdc
+        uri: http://localhost:${wiremock.server.port}
+      - subsystem: bpmn
+        uri: http://localhost:${wiremock.server.port}
+      - subsystem: catalogdb
+        uri: http://localhost:${wiremock.server.port}
+      - subsystem: openstack
+        uri: http://localhost:${wiremock.server.port}
+      - subsystem: requestdb
+        uri: http://localhost:${wiremock.server.port}
+      - subsystem: sdnc
+        uri: http://localhost:${wiremock.server.port}
   infra-requests:
     archived:
       period: 180
@@ -118,7 +124,13 @@ mariaDB4j:
   port: 3307
   databaseName: catalogdb
   databaseName2: requestdb
-
+#Actuator
+management:
+  endpoints:
+    web:
+      base-path: /manage
+      exposure:
+        include: "*"
 
 org:
   onap:
index 731d2be..ee53e49 100644 (file)
@@ -1111,6 +1111,7 @@ CREATE TABLE `vnf_resource_customization` (
   `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL,
   `SERVICE_MODEL_UUID` varchar(200) NOT NULL,
+  `NF_DATA_VALID` tinyint(1) DEFAULT '0',
   `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL,
   PRIMARY KEY (`ID`),
   UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`),
index 47f8c6b..5a8e2e2 100644 (file)
@@ -33,7 +33,7 @@ public interface InfraActiveRequestsRepositoryCustom {
 
     public InfraActiveRequests getRequestFromInfraActive(String requestId);
 
-    public InfraActiveRequests checkInstanceNameDuplicate(HashMap<String, String> instanceIdMap, String instanceName,
+    public InfraActiveRequests checkInstanceNameDuplicate(Map<String, String> instanceIdMap, String instanceName,
             String requestScope);
 
     public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(Map<String, List<String>> orchestrationMap);
index d8c7c8f..9cf7153 100644 (file)
@@ -117,14 +117,11 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
         final long startTime = System.currentTimeMillis();
         logger.debug("Execute query on infra active request table");
 
-        List<InfraActiveRequests> results = new ArrayList<InfraActiveRequests>();
-
         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
         crit.where(cb.and(predicates.toArray(new Predicate[0])));
         crit.orderBy(order);
-        results = entityManager.createQuery(crit).getResultList();
 
-        return results;
+        return entityManager.createQuery(crit).getResultList();
     }
 
     /*
@@ -152,7 +149,7 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep
      * java.lang.String, java.lang.String)
      */
     @Override
-    public InfraActiveRequests checkInstanceNameDuplicate(final HashMap<String, String> instanceIdMap,
+    public InfraActiveRequests checkInstanceNameDuplicate(final Map<String, String> instanceIdMap,
             final String instanceName, final String requestScope) {
 
         final List<Predicate> predicates = new LinkedList<>();
index 4d16d9c..9be92ad 100644 (file)
@@ -217,7 +217,7 @@ public class RequestsDbClient {
         return restTemplate.exchange(uri, HttpMethod.GET, entity, InfraActiveRequests.class).getBody();
     }
 
-    public InfraActiveRequests checkInstanceNameDuplicate(HashMap<String, String> instanceIdMap, String instanceName,
+    public InfraActiveRequests checkInstanceNameDuplicate(Map<String, String> instanceIdMap, String instanceName,
             String requestScope) {
         HttpHeaders headers = getHttpHeaders();
         URI uri = getUri(checkInstanceNameDuplicate);
index 548bc25..169d235 100644 (file)
 
 package org.onap.so.db.request.data.controller;
 
-import java.util.HashMap;
+import java.util.Map;
 
 public class InstanceNameDuplicateCheckRequest {
 
-    private HashMap<String, String> instanceIdMap;
+    private Map<String, String> instanceIdMap;
     private String instanceName;
     private String requestScope;
 
     public InstanceNameDuplicateCheckRequest() {}
 
-    public InstanceNameDuplicateCheckRequest(HashMap<String, String> instanceIdMap, String instanceName,
+    public InstanceNameDuplicateCheckRequest(Map<String, String> instanceIdMap, String instanceName,
             String requestScope) {
         this.instanceIdMap = instanceIdMap;
         this.instanceName = instanceName;
         this.requestScope = requestScope;
     }
 
-    public HashMap<String, String> getInstanceIdMap() {
+    public Map<String, String> getInstanceIdMap() {
         return instanceIdMap;
     }
 
-    public void setInstanceIdMap(HashMap<String, String> instanceIdMap) {
+    public void setInstanceIdMap(Map<String, String> instanceIdMap) {
         this.instanceIdMap = instanceIdMap;
     }
 
index 36c9251..aec1c7f 100644 (file)
@@ -23,9 +23,7 @@ package org.onap.so.db.catalog.beans;
 import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.Date;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Set;
 import javax.persistence.CascadeType;
 import javax.persistence.Column;
 import javax.persistence.Entity;
@@ -34,7 +32,6 @@ import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
 import javax.persistence.ManyToOne;
 import javax.persistence.OneToMany;
 import javax.persistence.PrePersist;
@@ -124,6 +121,9 @@ public class VnfResourceCustomization implements Serializable {
     @Column(name = "VNFCINSTANCEGROUP_ORDER")
     private String vnfcInstanceGroupOrder;
 
+    @Column(name = "NF_DATA_VALID")
+    private Boolean nfDataValid;
+
     @Override
     public boolean equals(final Object other) {
         if (!(other instanceof VnfResourceCustomization)) {
@@ -336,4 +336,14 @@ public class VnfResourceCustomization implements Serializable {
     public void setVnfcInstanceGroupOrder(String vnfcInstanceGroupOrder) {
         this.vnfcInstanceGroupOrder = vnfcInstanceGroupOrder;
     }
+
+    public Boolean getNfDataValid() {
+        return nfDataValid;
+    }
+
+    public void setNfDataValid(Boolean nfDataValid) {
+        this.nfDataValid = nfDataValid;
+    }
+
+
 }
index 1882ad5..39217c7 100644 (file)
@@ -77,12 +77,16 @@ public class RainyDayHandlerStatus implements Serializable {
     @Column(name = "SECONDARY_POLICY")
     private String secondaryPolicy;
 
+    @BusinessKey
+    @Column(name = "SERVICE_ROLE")
+    private String serviceRole;
+
     @Override
     public String toString() {
         return new ToStringBuilder(this).append("id", id).append("flowName", flowName)
                 .append("serviceType", serviceType).append("vnfType", vnfType).append("errorCode", errorCode)
                 .append("errorMessage", errorMessage).append("workStep", workStep).append("policy", policy)
-                .append("secondaryPolicy", secondaryPolicy).toString();
+                .append("secondaryPolicy", secondaryPolicy).append("serviceRole", serviceRole).toString();
     }
 
     @Override
@@ -93,13 +97,14 @@ public class RainyDayHandlerStatus implements Serializable {
         RainyDayHandlerStatus castOther = (RainyDayHandlerStatus) other;
         return new EqualsBuilder().append(flowName, castOther.flowName).append(serviceType, castOther.serviceType)
                 .append(vnfType, castOther.vnfType).append(errorCode, castOther.errorCode)
-                .append(workStep, castOther.workStep).append(policy, castOther.policy).isEquals();
+                .append(workStep, castOther.workStep).append(policy, castOther.policy)
+                .append(serviceRole, castOther.serviceRole).isEquals();
     }
 
     @Override
     public int hashCode() {
         return new HashCodeBuilder().append(flowName).append(serviceType).append(vnfType).append(errorCode)
-                .append(workStep).append(policy).toHashCode();
+                .append(workStep).append(policy).append(serviceRole).toHashCode();
     }
 
     public Integer getId() {
@@ -174,5 +179,12 @@ public class RainyDayHandlerStatus implements Serializable {
         this.errorMessage = errorMessage;
     }
 
+    public String getServiceRole() {
+        return serviceRole;
+    }
+
+    public void setServiceRole(String serviceRole) {
+        this.serviceRole = serviceRole;
+    }
 
 }
index a18f870..23539b0 100644 (file)
@@ -27,7 +27,9 @@ import java.util.List;
 import java.util.stream.Collectors;
 import javax.annotation.PostConstruct;
 import javax.persistence.EntityNotFoundException;
+import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.UriBuilder;
+import org.apache.http.HttpStatus;
 import org.onap.so.db.catalog.beans.BuildingBlockDetail;
 import org.onap.so.db.catalog.beans.CloudSite;
 import org.onap.so.db.catalog.beans.CloudifyManager;
@@ -67,13 +69,18 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
 import org.springframework.http.client.BufferingClientHttpRequestFactory;
 import org.springframework.http.client.ClientHttpRequestFactory;
 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.stereotype.Component;
+import org.springframework.web.client.HttpClientErrorException;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.util.UriComponentsBuilder;
+import com.google.common.base.Strings;
 import uk.co.blackpepper.bowman.Client;
 import uk.co.blackpepper.bowman.ClientFactory;
 import uk.co.blackpepper.bowman.Configuration;
@@ -137,6 +144,7 @@ public class CatalogDbClient {
     private static final String CLOUD_OWNER = "cloudOwner";
     private static final String FLOW_NAME = "flowName";
     private static final String ERROR_MESSAGE = "errorMessage";
+    private static final String SERVICE_ROLE = "serviceRole";
     private static final String SERVICE_TYPE = "serviceType";
     private static final String VNF_TYPE = "vnfType";
     private static final String ERROR_CODE = "errorCode";
@@ -638,7 +646,7 @@ public class CatalogDbClient {
     }
 
     public RainyDayHandlerStatus getRainyDayHandlerStatus(String flowName, String serviceType, String vnfType,
-            String errorCode, String workStep, String errorMessage) {
+            String errorCode, String workStep, String errorMessage, String serviceRole) {
         logger.debug(
                 "Get Rainy Day Status - Flow Name {}, Service Type: {} , vnfType {} , errorCode {}, workStep {}, errorMessage {}",
                 flowName, serviceType, vnfType, errorCode, workStep, errorMessage);
@@ -646,7 +654,8 @@ public class CatalogDbClient {
                 UriComponentsBuilder.fromUriString(endpoint + RAINY_DAY_HANDLER_MACRO + SEARCH + findRainyDayHandler)
                         .queryParam(FLOW_NAME, flowName).queryParam(SERVICE_TYPE, serviceType)
                         .queryParam(VNF_TYPE, vnfType).queryParam(ERROR_CODE, errorCode).queryParam(WORK_STEP, workStep)
-                        .queryParam(ERROR_MESSAGE, errorMessage).build().encode().toUri());
+                        .queryParam(ERROR_MESSAGE, errorMessage).queryParam(SERVICE_ROLE, serviceRole).build().encode()
+                        .toUri());
     }
 
     public ServiceRecipe getFirstByServiceModelUUIDAndAction(String modelUUID, String action) {
@@ -886,6 +895,90 @@ public class CatalogDbClient {
                     "Unable to find CvnfcConfigurationCustomization ModelCustomizationUUID:" + cvnfcCustomizationUuid);
     }
 
+    public org.onap.so.rest.catalog.beans.Service getServiceModelInformation(String serviceModelUUID, String depth) {
+        if (Strings.isNullOrEmpty(serviceModelUUID)) {
+            throw new EntityNotFoundException("Service Model UUID passed as Null or Empty String");
+        }
+        try {
+            HttpEntity<?> entity = getHttpEntity();
+            return restTemplate.exchange(
+                    UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID)
+                            .queryParam("depth", depth).build().encode().toString(),
+                    HttpMethod.GET, entity, org.onap.so.rest.catalog.beans.Service.class).getBody();
+        } catch (HttpClientErrorException e) {
+            logger.warn("Entity Not found in DLP", e);
+            if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+                throw new EntityNotFoundException("Unable to find Service with ServiceModelUUID:" + serviceModelUUID);
+            }
+            throw e;
+        }
+    }
+
+    public List<org.onap.so.rest.catalog.beans.Service> getServices() {
+        try {
+            HttpEntity<?> entity = getHttpEntity();
+            return restTemplate
+                    .exchange(
+                            UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services").build()
+                                    .encode().toString(),
+                            HttpMethod.GET, entity,
+                            new ParameterizedTypeReference<List<org.onap.so.rest.catalog.beans.Service>>() {})
+                    .getBody();
+        } catch (HttpClientErrorException e) {
+            logger.error("Error Calling catalog database", e);
+            throw e;
+        }
+    }
+
+    public org.onap.so.rest.catalog.beans.Vnf getVnfModelInformation(String serviceModelUUID,
+            String vnfCustomizationUUID, String depth) {
+        if (Strings.isNullOrEmpty(serviceModelUUID)) {
+            throw new EntityNotFoundException("Service Model UUID passed as Null or Empty String");
+        }
+        if (Strings.isNullOrEmpty(vnfCustomizationUUID)) {
+            throw new EntityNotFoundException("Vnf Customization UUID passed as Null or Empty String");
+        }
+        try {
+            HttpEntity<?> entity = getHttpEntity();
+            return restTemplate
+                    .exchange(
+                            UriComponentsBuilder
+                                    .fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID
+                                            + "/vnfs/" + vnfCustomizationUUID)
+                                    .queryParam("depth", depth).build().encode().toString(),
+                            HttpMethod.GET, entity, org.onap.so.rest.catalog.beans.Vnf.class)
+                    .getBody();
+        } catch (HttpClientErrorException e) {
+            if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+                throw new EntityNotFoundException(
+                        "Unable to find Vnf with Vnf Customization UUID:" + vnfCustomizationUUID);
+            }
+            throw e;
+        }
+    }
+
+    public void updateVnf(String serviceModelUUID, org.onap.so.rest.catalog.beans.Vnf vnf) {
+        if (vnf == null) {
+            throw new EntityNotFoundException("Vnf passed as null");
+        }
+        try {
+            HttpHeaders headers = getHttpHeaders();
+            HttpEntity<org.onap.so.rest.catalog.beans.Vnf> entity = new HttpEntity<>(vnf, headers);
+
+            restTemplate.exchange(
+                    UriComponentsBuilder.fromUriString(endpoint + "/ecomp/mso/catalog/v1/services/" + serviceModelUUID
+                            + "/vnfs/" + vnf.getModelCustomizationId()).build().encode().toString(),
+                    HttpMethod.PUT, entity, org.onap.so.rest.catalog.beans.Vnf.class).getBody();
+        } catch (HttpClientErrorException e) {
+            if (HttpStatus.SC_NOT_FOUND == e.getStatusCode().value()) {
+                throw new EntityNotFoundException(
+                        "Unable to find Vnf with Vnf Customization UUID:" + vnf.getModelCustomizationId());
+            }
+            throw e;
+        }
+    }
+
+
     public Workflow findWorkflowByArtifactUUID(String artifactUUID) {
         return this.getSingleResource(workflowClient, getUri(UriBuilder.fromUri(findWorkflowByArtifactUUID)
                 .queryParam(ARTIFACT_UUID, artifactUUID).build().toString()));
@@ -908,4 +1001,18 @@ public class CatalogDbClient {
     public void setEndpoint(String endpoint) {
         this.endpoint = endpoint;
     }
+
+    private HttpHeaders getHttpHeaders() {
+        HttpHeaders headers = new HttpHeaders();
+        headers.set(HttpHeaders.AUTHORIZATION, msoAdaptersAuth);
+        headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
+        headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
+        headers.set(LogConstants.TARGET_ENTITY_HEADER, TARGET_ENTITY);
+        return headers;
+    }
+
+    private HttpEntity<?> getHttpEntity() {
+        HttpHeaders headers = getHttpHeaders();
+        return new HttpEntity<>(headers);
+    }
 }
index 6819657..efe078b 100644 (file)
@@ -32,10 +32,11 @@ public interface RainyDayHandlerStatusRepository extends JpaRepository<RainyDayH
     @Query(value = "SELECT * FROM rainy_day_handler_macro WHERE (FLOW_NAME = :flowName ) AND SERVICE_TYPE IN (:serviceType ,'*') "
             + " AND VNF_TYPE IN ( :vnfType , '*') AND ERROR_CODE IN (:errorCode  ,'*') AND WORK_STEP IN (:workStep , '*' ) "
             + " AND ( :errorMessage REGEXP rainy_day_handler_macro.REG_EX_ERROR_MESSAGE OR REG_EX_ERROR_MESSAGE = '*') "
-            + " ORDER BY CASE WHEN :errorMessage REGEXP REG_EX_ERROR_MESSAGE THEN 0 WHEN ERROR_CODE != '*' THEN 1 WHEN VNF_TYPE != '*' THEN 2 WHEN SERVICE_TYPE != '*' THEN 3 ELSE 4 END LIMIT 1;",
+            + " AND SERVICE_ROLE IN ( :serviceRole , '*') "
+            + " ORDER BY CASE WHEN :errorMessage REGEXP REG_EX_ERROR_MESSAGE THEN 0 WHEN ERROR_CODE != '*' THEN 1 WHEN VNF_TYPE != '*' THEN 2 WHEN SERVICE_TYPE != '*' THEN 3 WHEN SERVICE_ROLE != '*' THEN 4 ELSE 5 END LIMIT 1;",
             nativeQuery = true)
     RainyDayHandlerStatus findRainyDayHandler(@Param("flowName") String flowName,
             @Param("serviceType") String serviceType, @Param("vnfType") String vnfType,
             @Param("errorCode") String errorCode, @Param("workStep") String workStep,
-            @Param("errorMessage") String errorMessage);
+            @Param("errorMessage") String errorMessage, @Param("serviceRole") String serviceRole);
 }
diff --git a/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java b/mso-catalog-db/src/main/java/org/onap/so/rest/catalog/beans/Cvnfc.java
new file mode 100644 (file)
index 0000000..e22f366
--- /dev/null
@@ -0,0 +1,136 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.rest.catalog.beans;
+
+import java.util.Date;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+
+@JsonInclude(Include.NON_DEFAULT)
+public class Cvnfc {
+
+    private String modelCustomizationId;
+    private String modelInstanceName;
+    private String modelVersionId;
+    private String modelInvariantId;
+    private String modelVersion;
+    private String modelName;
+    private String description;
+    private String nfcFunction;
+    private String nfcNamingCode;
+
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
+    private Date created;
+
+    public String getModelCustomizationId() {
+        return modelCustomizationId;
+    }
+
+    public void setModelCustomizationId(String modelCustomizationId) {
+        this.modelCustomizationId = modelCustomizationId;
+    }
+
+    public String getModelInstanceName() {
+        return modelInstanceName;
+    }
+
+    public void setModelInstanceName(String modelInstanceName) {
+        this.modelInstanceName = modelInstanceName;
+    }
+
+    public String getModelVersionId() {
+        return modelVersionId;
+    }
+
+    public void setModelVersionId(String modelVersionId) {
+        this.modelVersionId = modelVersionId;
+    }
+
+    public String getModelInvariantId() {
+        return modelInvariantId;
+    }
+
+    public void setModelInvariantId(String modelInvariantId) {
+        this.modelInvariantId = modelInvariantId;
+    }
+
+    public String getModelVersion() {
+        return modelVersion;
+    }
+
+    public void setModelVersion(String modelVersion) {
+        this.modelVersion = modelVersion;
+    }
+
+    public String getModelName() {
+        return modelName;
+    }
+
+    public void setModelName(String modelName) {
+        this.modelName = modelName;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public String getNfcFunction() {
+        return nfcFunction;
+    }
+
+    public void setNfcFunction(String nfcFunction) {
+        this.nfcFunction = nfcFunction;
+    }
+
+    public String getNfcNamingCode() {
+        return nfcNamingCode;
+    }
+
+    public void setNfcNamingCode(String nfcNamingCode) {
+        this.nfcNamingCode = nfcNamingCode;
+    }
+
+    public Date getCreated() {
+        return created;
+    }
+
+    public void setCreated(Date created) {
+        this.created = created;
+    }
+
+
+
+    @Override
+    public String toString() {
+        return new ToStringBuilder(this).append("modelCustomizationId", modelCustomizationId)
+                .append("modelInstanceName", modelInstanceName).append("modelVersionId", modelVersionId)
+                .append("modelInvariantId", modelInvariantId).append("modelVersion", modelVersion)
+                .append("modelName", modelName).append("description", description).append("nfcFunction", nfcFunction)
+                .append("nfcNamingCode", nfcNamingCode).append("created", created).toString();
+    }
+
+}
index 1620058..1108904 100644 (file)
@@ -24,6 +24,7 @@ import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
+import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonInclude;
 import com.fasterxml.jackson.annotation.JsonInclude.Include;
 
@@ -40,6 +41,7 @@ public class Service implements Serializable {
 
     private String modelInvariantId;
 
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
     private Date created;
 
     private String modelVersion;
index 8e18f94..f2a2c77 100644 (file)
 
 package org.onap.so.rest.catalog.beans;
 
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import org.onap.so.db.catalog.beans.HeatEnvironment;
+import com.fasterxml.jackson.annotation.JsonFormat;
 import com.fasterxml.jackson.annotation.JsonInclude;
 import com.fasterxml.jackson.annotation.JsonInclude.Include;
 
@@ -37,6 +39,7 @@ public class VfModule {
     private String description;
     private Boolean isBase;
     private HeatTemplate heatTemplate;
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
     private Date created;
     private List<HeatFile> heatFile;
 
@@ -50,9 +53,7 @@ public class VfModule {
     private HeatEnvironment heatEnv;
     private Boolean isVolumeGroup;
 
-
-    // Add in cvnfcCustomization
-
+    private List<Cvnfc> vnfc = new ArrayList<>();
 
 
     public String getModelName() {
@@ -191,6 +192,12 @@ public class VfModule {
         this.isVolumeGroup = isVolumeGroup;
     }
 
+    public List<Cvnfc> getVnfc() {
+        return vnfc;
+    }
 
+    public void setVnfc(List<Cvnfc> vnfc) {
+        this.vnfc = vnfc;
+    }
 
 }
index 40d701c..febf69b 100644 (file)
@@ -47,12 +47,14 @@ public class Vnf implements Serializable {
     private String nfFunction;
     private String nfRole;
     private String nfNamingCode;
+    private String nfType;
     private String multiStageDesign;
     private String orchestrationMode;
     private String cloudVersionMin;
     private String cloudVersionMax;
     private String category;
     private String subCategory;
+    private Boolean nfDataValid;
     private List<VfModule> vfModule = new ArrayList<>();
 
     public List<VfModule> getVfModule() {
@@ -215,4 +217,21 @@ public class Vnf implements Serializable {
     public void setMultiStageDesign(String multiStepDesign) {
         this.multiStageDesign = multiStepDesign;
     }
+
+    public String getNfType() {
+        return nfType;
+    }
+
+    public void setNfType(String nfType) {
+        this.nfType = nfType;
+    }
+
+    public Boolean getNfDataValid() {
+        return nfDataValid;
+    }
+
+    public void setNfDataValid(Boolean nfDataValid) {
+        this.nfDataValid = nfDataValid;
+    }
+
 }
index 612963d..8bf47e7 100644 (file)
@@ -37,6 +37,7 @@ public class VnfcCustomizationRepositoryTest extends BaseTest {
     private VnfcCustomizationRepository vnfcCustomizationRepository;
 
     @Test
+    @Transactional
     public void findAllTest() throws Exception {
         List<VnfcCustomization> vnfcCustomizationList = vnfcCustomizationRepository.findAll();
         Assert.assertFalse(CollectionUtils.isEmpty(vnfcCustomizationList));
index 7cd13a3..7468f62 100644 (file)
@@ -1109,6 +1109,7 @@ CREATE TABLE `vnf_resource_customization` (
   `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
   `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL,
   `SERVICE_MODEL_UUID` varchar(200) NOT NULL,
+  `NF_DATA_VALID` tinyint(1) DEFAULT '0',
   `VNFCINSTANCEGROUP_ORDER` varchar(200) default NULL,
   PRIMARY KEY (`ID`),
   UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`),
index 99af342..f78f30b 100644 (file)
@@ -4,7 +4,7 @@
 
 major=1
 minor=5
-patch=0
+patch=1
 
 base_version=${major}.${minor}.${patch}
 
index 32c05eb..a1abb05 100644 (file)
@@ -1,6 +1,5 @@
 package org.onap.svnfm.simulator.config;
 
-import java.net.InetAddress;
 import java.util.Arrays;
 import org.onap.svnfm.simulator.constants.Constant;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -23,6 +22,9 @@ public class ApplicationConfig implements ApplicationRunner {
     @Value("${server.dns.name:so-vnfm-simulator.onap}")
     private String serverDnsName;
 
+    @Value("${server.request.grant.auth:oauth}")
+    private String grantAuth;
+
     @Autowired
     private Environment environment;
 
@@ -37,6 +39,10 @@ public class ApplicationConfig implements ApplicationRunner {
         return baseUrl;
     }
 
+    public String getGrantAuth() {
+        return grantAuth;
+    }
+
     @Bean
     public CacheManager cacheManager() {
         final Cache inlineResponse201 = new ConcurrentMapCache(Constant.IN_LINE_RESPONSE_201_CACHE);
index eed6278..6e9478b 100644 (file)
@@ -8,10 +8,17 @@ import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.UUID;
 import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
 import javax.ws.rs.core.MediaType;
 import org.apache.commons.codec.binary.Base64;
 import org.modelmapper.ModelMapper;
@@ -44,12 +51,16 @@ import org.onap.svnfm.simulator.repository.VnfOperationRepository;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
 
 public abstract class OperationProgressor implements Runnable {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(OperationProgressor.class);
     private static final String CERTIFICATE_TO_TRUST = "so-vnfm-adapter.crt.pem";
 
+    private Resource keyStoreResource = new ClassPathResource("so-vnfm-simulator.p12");
+    private String keyStorePassword = "7Em3&j4.19xYiMelhD5?xbQ.";
+
     protected final VnfOperation operation;
     protected final SvnfmService svnfmService;
     private final VnfOperationRepository vnfOperationRepository;
@@ -73,12 +84,14 @@ public abstract class OperationProgressor implements Runnable {
         String callBackUrl = subscriptionService.getSubscriptions().iterator().next().getCallbackUri();
         callBackUrl = callBackUrl.substring(0, callBackUrl.indexOf("/lcn/"));
         apiClient.setBasePath(callBackUrl);
+        apiClient.setKeyManagers(getKeyManagers());
         apiClient.setSslCaCert(getCertificateToTrust());
         notificationClient = new DefaultApi(apiClient);
 
         final org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiClient grantApiClient =
                 new org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.ApiClient();
         grantApiClient.setBasePath(callBackUrl);
+        grantApiClient.setKeyManagers(getKeyManagers());
         grantApiClient.setSslCaCert(getCertificateToTrust());
         grantClient = new org.onap.so.adapters.vnfmadapter.extclients.vnfm.grant.api.DefaultApi(grantApiClient);
     }
@@ -92,6 +105,22 @@ public abstract class OperationProgressor implements Runnable {
         }
     }
 
+    private KeyManager[] getKeyManagers() {
+        KeyStore keystore;
+        try {
+            keystore = KeyStore.getInstance("pkcs12");
+            keystore.load(keyStoreResource.getInputStream(), keyStorePassword.toCharArray());
+            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
+            keyManagerFactory.init(keystore, keyStorePassword.toCharArray());
+            return keyManagerFactory.getKeyManagers();
+        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException
+                | UnrecoverableKeyException exception) {
+            LOGGER.error("Error reading certificate, https calls using two way TLS to VNFM adapter will fail",
+                    exception);
+            return new KeyManager[0];
+        }
+    }
+
     @Override
     public void run() {
         try {
@@ -247,8 +276,10 @@ public abstract class OperationProgressor implements Runnable {
             final SubscriptionsAuthenticationParamsOauth2ClientCredentials subscriptionAuthentication =
                     subscriptionService.getSubscriptions().iterator().next().getAuthentication()
                             .getParamsOauth2ClientCredentials();
-            final String authHeader =
-                    "Bearer " + getToken(notificationClient.getApiClient(), subscriptionAuthentication);
+
+            final String authHeader = applicationConfig.getGrantAuth().equals("oauth")
+                    ? "Bearer " + getToken(notificationClient.getApiClient(), subscriptionAuthentication)
+                    : null;
 
             final ApiResponse<InlineResponse201> response = grantClient.grantsPostWithHttpInfo(grantRequest,
                     MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, authHeader);