From 6ad41e3ccd398a2721f41ad61c80b7bb03f7d127 Mon Sep 17 00:00:00 2001 From: Ittay Stern Date: Mon, 31 Dec 2018 17:21:27 +0200 Subject: Merge from ECOMP's repository Main Features -------------- - Async-Instantiation jobs mechanism major update; still WIP (package `org.onap.vid.job`) - New features in View/Edit: Activate fabric configuration; show related networks; soft delete - Support AAI service-tree traversal (`AAIServiceTree`) - In-memory cache for SDC models and certain A&AI queries (`CacheProviderWithLoadingCache`) - Upgrade TOSCA Parser and add parsing options; fix malformed TOSCA models - Resolve Cloud-Owner values for MSO - Pass X-ONAP headers to MSO Infrastructure -------------- - Remove codehaus' jackson mapper; use soley fasterxml 2.9.7 - Surefire invokes both TestNG and JUnit tests - Support Kotlin source files - AaiController2 which handles errors in a "Spring manner" - Inline generated-sources and remove jsonschema2pojo Quality -------- - Cumulative bug fixes (A&AI API, UI timeouts, and many more) - Many Sonar issues cleaned-up - Some unused classes removed - Minor changes in vid-automation project, allowing some API verification to run Hard Merges ------------ - HTTP Clients (MSO, A&AI, WebConfig, OutgoingRequestHeadersTest) - Moved `package org.onap.vid.controllers` to `controller`, without plural -- just to keep semantic sync with ECOMP. Reference commit in ECOMP: 3d1141625 Issue-ID: VID-378 Change-Id: I9c8d1e74caa41815891d441fc0760bb5f29c5788 Signed-off-by: Ittay Stern --- epsdk-app-onap/pom.xml | 4 +- .../org/onap/portalapp/conf/ExternalAppConfig.java | 42 +- .../portalapp/conf/ExternalAppInitializer.java | 6 +- pom.xml | 498 ++++---- vid-app-common/TestNg-BE-UnitTest.xml | 11 + vid-app-common/pom.xml | 177 ++- .../src/main/java/org/onap/vid/RelatedTo.java | 39 - .../src/main/java/org/onap/vid/aai/AaiClient.java | 425 +++++-- .../java/org/onap/vid/aai/AaiClientInterface.java | 27 +- .../java/org/onap/vid/aai/AaiGetVnfResponse.java | 3 +- .../java/org/onap/vid/aai/AaiOverTLSClient.java | 43 +- .../onap/vid/aai/AaiOverTLSClientInterface.java | 3 +- .../org/onap/vid/aai/AaiResponseTranslator.java | 4 +- .../onap/vid/aai/AaiResponseWithRequestInfo.java | 3 +- .../org/onap/vid/aai/ExceptionWithRequestInfo.java | 4 +- .../org/onap/vid/aai/OperationalEnvironment.java | 39 +- .../java/org/onap/vid/aai/PombaClientImpl.java | 23 +- .../java/org/onap/vid/aai/PombaRestInterface.java | 6 +- .../java/org/onap/vid/aai/ServiceInstance.java | 12 +- .../java/org/onap/vid/aai/ServiceInstances.java | 4 +- .../vid/aai/ServiceInstancesSearchResults.java | 5 +- .../java/org/onap/vid/aai/ServiceSubscription.java | 4 +- .../org/onap/vid/aai/ServiceSubscriptions.java | 4 +- .../src/main/java/org/onap/vid/aai/Services.java | 6 +- .../org/onap/vid/aai/SubscriberWithFilter.java | 2 +- .../onap/vid/aai/model/AaiGetAicZone/AicZones.java | 4 +- .../org/onap/vid/aai/model/AaiGetAicZone/Zone.java | 6 +- .../CloudRegion.java | 55 + .../AaiGetNetworkCollectionDetails/Network.java | 16 +- .../ServiceInstance.java | 42 +- .../model/AaiGetNetworkCollectionDetails/Vlan.java | 41 + .../model/AaiGetNetworkCollectionDetails/Vnf.java | 84 ++ .../OperationalEnvironmentList.java | 7 +- .../org/onap/vid/aai/model/AaiGetPnfResponse.java | 7 +- .../org/onap/vid/aai/model/AaiGetPnfs/Pnf.java | 32 +- .../aai/model/AaiGetPortMirroringSourcePorts.java | 2 +- .../GetServicesAAIRespone.java | 3 +- .../model/AaiGetServicesRequestModel/Service.java | 4 +- .../model/AaiGetTenatns/GetTenantsResponse.java | 23 +- .../onap/vid/aai/model/AaiRelationResponse.java | 16 +- .../vid/aai/model/CustomQuerySimpleResult.java | 18 + ...tServiceModelsByDistributionStatusResponse.java | 4 +- .../onap/vid/aai/model/LogicalLinkResponse.java | 14 +- .../main/java/org/onap/vid/aai/model/Model.java | 20 +- .../main/java/org/onap/vid/aai/model/ModelVer.java | 28 +- .../java/org/onap/vid/aai/model/ModelVers.java | 8 +- .../java/org/onap/vid/aai/model/OwningEntity.java | 10 +- .../onap/vid/aai/model/OwningEntityResponse.java | 6 +- .../java/org/onap/vid/aai/model/Permissions.kt | 6 + .../java/org/onap/vid/aai/model/PnfProperties.java | 47 +- .../java/org/onap/vid/aai/model/PnfResult.java | 40 +- .../onap/vid/aai/model/PortDetailsTranslator.java | 42 +- .../main/java/org/onap/vid/aai/model/Project.java | 6 +- .../org/onap/vid/aai/model/ProjectResponse.java | 5 - .../java/org/onap/vid/aai/model/Properties.java | 77 +- .../java/org/onap/vid/aai/model/RelatedTo.java | 14 +- .../org/onap/vid/aai/model/RelatedToProperty.java | 8 +- .../java/org/onap/vid/aai/model/Relationship.java | 15 +- .../org/onap/vid/aai/model/RelationshipData.java | 42 +- .../org/onap/vid/aai/model/RelationshipList.java | 4 +- .../java/org/onap/vid/aai/model/ResourceType.java | 10 +- .../main/java/org/onap/vid/aai/model/Result.java | 4 +- .../org/onap/vid/aai/model/ServiceProperties.java | 25 +- .../onap/vid/aai/model/ServiceRelationships.java | 62 +- .../java/org/onap/vid/aai/model/SimpleResult.java | 32 +- .../java/org/onap/vid/aai/model/VnfResult.java | 34 +- .../interfaces/AaiModelWithRelationships.java | 7 + .../org/onap/vid/aai/util/AAIRestInterface.java | 108 +- .../org/onap/vid/aai/util/AAITreeConverter.java | 89 ++ .../main/java/org/onap/vid/aai/util/CacheConfig.kt | 52 + .../java/org/onap/vid/aai/util/CacheProvider.java | 37 + .../aai/util/CacheProviderWithLoadingCache.java | 100 ++ .../org/onap/vid/aai/util/HttpsAuthClient.java | 28 +- .../onap/vid/aai/util/HttpsComponentsClient.java | 117 -- .../JettyObfuscationConversionCommandLineUtil.java | 4 +- .../vid/aai/util/ServiceInstanceStandardQuery.java | 93 ++ .../onap/vid/aai/util/SystemPropertyHelper.java | 11 + .../main/java/org/onap/vid/asdc/AsdcClient.java | 1 + .../org/onap/vid/asdc/beans/SecureServices.java | 1 - .../java/org/onap/vid/asdc/beans/tosca/Input.java | 17 +- .../onap/vid/asdc/beans/tosca/InputProperties.java | 3 - .../onap/vid/asdc/beans/tosca/NodeTemplate.java | 4 +- .../org/onap/vid/asdc/beans/tosca/Property.java | 2 +- .../vid/asdc/beans/tosca/SubstitutionMappings.java | 4 +- .../vid/asdc/beans/tosca/TopologyTemplate.java | 6 +- .../org/onap/vid/asdc/beans/tosca/ToscaCsar.java | 2 +- .../org/onap/vid/asdc/beans/tosca/ToscaMeta.java | 11 +- .../org/onap/vid/asdc/local/LocalAsdcClient.java | 60 +- .../onap/vid/asdc/parser/ServiceModelInflator.kt | 43 + .../onap/vid/asdc/parser/ToscaNamingPolicy.java | 28 + .../org/onap/vid/asdc/parser/ToscaParserImpl.java | 5 +- .../org/onap/vid/asdc/parser/ToscaParserImpl2.java | 449 ++++--- .../onap/vid/asdc/parser/VidNotionsBuilder.java | 130 ++ .../changeManagement/ChangeManagementRequest.java | 21 +- .../vid/changeManagement/CloudConfiguration.java | 10 +- .../changeManagement/LeanCloudConfiguration.java | 9 +- .../org/onap/vid/changeManagement/ModelInfo.java | 13 +- .../ModelInfoOfRelatedInstance.java | 10 +- .../onap/vid/changeManagement/RequestDetails.java | 5 + .../org/onap/vid/changeManagement/RequestInfo.java | 10 +- .../vid/changeManagement/UpdateRequestInfo.java | 4 +- .../org/onap/vid/changeManagement/VnfDetails.java | 1 - .../changeManagement/VnfDetailsWithWorkflows.java | 10 +- .../onap/vid/changeManagement/WorkflowsDetail.java | 1 - .../java/org/onap/vid/client/HttpBasicClient.java | 5 - .../java/org/onap/vid/client/HttpsBasicClient.java | 111 -- .../java/org/onap/vid/client/SyncRestClient.java | 8 +- .../org/onap/vid/controller/AaiController.java | 731 +++++++++++ .../org/onap/vid/controller/AaiController2.java | 98 ++ .../AaiServiceInstanceStandardQueryController.java | 173 +++ .../vid/controller/AsyncControllerForTests.java | 48 + .../controller/AsyncInstantiationController.java | 104 ++ .../vid/controller/ChangeManagementController.java | 213 ++++ .../org/onap/vid/controller/ControllersUtils.java | 45 + .../vid/controller/FeatureTogglingController.java | 29 + .../onap/vid/controller/HealthCheckController.java | 135 ++ .../java/org/onap/vid/controller/HealthStatus.java | 31 + .../org/onap/vid/controller/LoggerController.java | 115 ++ .../onap/vid/controller/MaintenanceController.java | 152 +++ .../java/org/onap/vid/controller/MsoConfig.java | 66 + .../org/onap/vid/controller/MsoController.java | 705 +++++++++++ .../OperationalEnvironmentController.java | 362 ++++++ .../org/onap/vid/controller/ProbeController.java | 42 + .../onap/vid/controller/PropertyController.java | 126 ++ .../vid/controller/RoleGeneratorController.java | 26 + .../org/onap/vid/controller/VersionController.java | 63 + .../org/onap/vid/controller/VidController.java | 114 ++ .../controller/VidRestrictedBaseController.java | 42 + .../org/onap/vid/controller/ViewLogController.java | 65 + .../java/org/onap/vid/controller/WebConfig.java | 193 +++ .../controller/filter/ClientCredentialsFilter.java | 10 +- .../filter/PromiseEcompRequestIdFilter.java | 17 +- .../vid/controller/test/TestAaiController.java | 2 +- .../vid/controller/test/TestAsdcController.java | 2 +- .../vid/controller/test/TestMsoController.java | 2 +- .../org/onap/vid/controllers/AaiController.java | 763 ------------ .../vid/controllers/AsyncControllerForTests.java | 56 - .../controllers/AsyncInstantiationController.java | 78 -- .../controllers/ChangeManagementController.java | 227 ---- .../org/onap/vid/controllers/ControllersUtils.java | 47 - .../vid/controllers/FeatureTogglingController.java | 29 - .../vid/controllers/HealthCheckController.java | 135 -- .../org/onap/vid/controllers/HealthStatus.java | 31 - .../org/onap/vid/controllers/LoggerController.java | 115 -- .../vid/controllers/MaintenanceController.java | 156 --- .../java/org/onap/vid/controllers/MsoConfig.java | 68 -- .../org/onap/vid/controllers/MsoController.java | 693 ----------- .../OperationalEnvironmentController.java | 362 ------ .../org/onap/vid/controllers/PolicyController.java | 84 -- .../org/onap/vid/controllers/ProbeController.java | 27 - .../onap/vid/controllers/PropertyController.java | 132 -- .../vid/controllers/RoleGeneratorController.java | 26 - .../org/onap/vid/controllers/VidController.java | 114 -- .../controllers/VidRestrictedBaseController.java | 43 - .../onap/vid/controllers/ViewLogController.java | 65 - .../java/org/onap/vid/controllers/WebConfig.java | 226 ---- .../src/main/java/org/onap/vid/job/Job.java | 28 +- .../src/main/java/org/onap/vid/job/JobAdapter.java | 11 +- .../src/main/java/org/onap/vid/job/JobCommand.java | 9 +- .../main/java/org/onap/vid/job/JobException.java | 16 + .../src/main/java/org/onap/vid/job/JobType.java | 24 +- .../java/org/onap/vid/job/JobsBrokerService.java | 2 + .../onap/vid/job/command/ALaCarteServiceCommand.kt | 122 ++ .../ALaCarteServiceInstantiationCommand.java | 21 + .../job/command/BaseInProgressStatusCommand.java | 95 ++ .../vid/job/command/BaseInstantiationCommand.java | 18 + .../org/onap/vid/job/command/BaseRootCommand.java | 41 + .../onap/vid/job/command/BaseWatchingCommand.java | 70 ++ .../java/org/onap/vid/job/command/CommandBase.java | 27 + .../onap/vid/job/command/CommandParentData.java | 80 ++ .../org/onap/vid/job/command/CommandUtils.java | 46 + .../org/onap/vid/job/command/ExpiryChecker.java | 8 + .../org/onap/vid/job/command/HttpCallCommand.java | 8 +- .../vid/job/command/InProgressStatusCommand.java | 137 --- .../vid/job/command/InProgressStatusService.java | 87 ++ .../onap/vid/job/command/InstanceGroupCommand.kt | 59 + .../command/InstanceGroupInstantiationCommand.java | 47 + .../onap/vid/job/command/JobCommandFactory.java | 2 +- .../command/MacroServiceInstantiationCommand.java | 26 + .../java/org/onap/vid/job/command/MsoResult.kt | 9 + .../vid/job/command/MsoResultHandlerService.kt | 66 + .../job/command/NetworkInstantiationCommand.java | 41 + .../org/onap/vid/job/command/ResourceCommand.kt | 324 +++++ .../command/ResourceInProgressStatusCommand.java | 32 + .../job/command/ResourceInstantiationCommand.java | 87 ++ .../ResourceWithChildrenInProgressCommand.java | 65 + .../command/ServiceInProgressStatusCommand.java | 100 ++ .../job/command/ServiceInstantiationCommand.java | 146 +-- .../job/command/VfmoduleInstantiationCommand.java | 44 + .../job/command/VnfInProgressStatusCommand.java | 87 ++ .../vid/job/command/VnfInstantiationCommand.java | 50 + .../VolumeGroupInProgressStatusCommand.java | 65 + .../command/VolumeGroupInstantiationCommand.java | 83 ++ .../onap/vid/job/command/WatchChildrenJobsBL.kt | 61 + .../org/onap/vid/job/command/WatchingCommand.java | 33 + .../vid/job/command/WatchingCommandBaseModule.java | 93 ++ .../java/org/onap/vid/job/impl/JobAdapterImpl.java | 55 +- .../java/org/onap/vid/job/impl/JobDaoImpl.java | 40 +- .../main/java/org/onap/vid/job/impl/JobData.java | 54 + .../onap/vid/job/impl/JobSchedulerInitializer.java | 4 +- .../java/org/onap/vid/job/impl/JobSharedData.java | 84 ++ .../main/java/org/onap/vid/job/impl/JobWorker.java | 35 +- .../job/impl/JobsBrokerServiceInDatabaseImpl.java | 75 +- .../src/main/java/org/onap/vid/model/Action.java | 15 + .../src/main/java/org/onap/vid/model/CR.java | 2 +- .../java/org/onap/vid/model/CommandProperty.java | 5 +- .../src/main/java/org/onap/vid/model/Group.java | 21 +- .../java/org/onap/vid/model/GroupProperties.java | 9 + .../java/org/onap/vid/model/JobAuditStatus.java | 75 +- .../main/java/org/onap/vid/model/MinimalNode.kt | 8 + .../java/org/onap/vid/model/ModelConstants.java | 12 +- .../main/java/org/onap/vid/model/NameCounter.java | 2 +- .../main/java/org/onap/vid/model/NewNetwork.java | 2 - .../src/main/java/org/onap/vid/model/NewNode.java | 18 +- .../java/org/onap/vid/model/NewServiceModel.java | 91 +- .../src/main/java/org/onap/vid/model/NewVNF.java | 41 +- .../src/main/java/org/onap/vid/model/Node.java | 44 +- .../org/onap/vid/model/PortMirroringConfig.java | 10 - .../onap/vid/model/RequestReferencesContainer.java | 4 +- .../src/main/java/org/onap/vid/model/Resource.java | 28 - .../main/java/org/onap/vid/model/ResourceGroup.kt | 13 + .../src/main/java/org/onap/vid/model/Service.java | 14 +- .../main/java/org/onap/vid/model/ServiceInfo.java | 75 +- .../main/java/org/onap/vid/model/ServiceModel.java | 41 +- .../main/java/org/onap/vid/model/ServiceProxy.java | 11 - .../java/org/onap/vid/model/SoftDeleteRequest.java | 42 + .../main/java/org/onap/vid/model/Subscriber.java | 2 +- .../java/org/onap/vid/model/SubscriberList.java | 2 - .../src/main/java/org/onap/vid/model/VNF.java | 29 +- .../src/main/java/org/onap/vid/model/VfModule.java | 14 +- .../src/main/java/org/onap/vid/model/VidNotions.kt | 34 + .../org/onap/vid/model/aaiTree/AAITreeNode.java | 178 +++ .../org/onap/vid/model/aaiTree/AbstractNode.java | 53 + .../onap/vid/model/aaiTree/FailureAAITreeNode.java | 31 + .../java/org/onap/vid/model/aaiTree/Network.java | 20 + .../main/java/org/onap/vid/model/aaiTree/Node.java | 139 +++ .../org/onap/vid/model/aaiTree/RelatedVnf.java | 52 + .../onap/vid/model/aaiTree/ServiceInstance.java | 193 +++ .../java/org/onap/vid/model/aaiTree/VfModule.java | 41 + .../main/java/org/onap/vid/model/aaiTree/Vnf.java | 54 + .../java/org/onap/vid/model/aaiTree/VnfGroup.java | 52 + .../vid/model/probes/ExternalComponentStatus.java | 2 +- .../onap/vid/model/probes/HttpRequestMetadata.java | 61 +- .../model/serviceInstantiation/BaseResource.java | 115 ++ .../model/serviceInstantiation/InstanceGroup.java | 22 + .../vid/model/serviceInstantiation/Network.java | 74 ++ .../serviceInstantiation/ServiceInstantiation.java | 90 +- .../vid/model/serviceInstantiation/VfModule.java | 60 +- .../onap/vid/model/serviceInstantiation/Vnf.java | 81 +- .../java/org/onap/vid/mso/MsoBusinessLogic.java | 18 +- .../org/onap/vid/mso/MsoBusinessLogicImpl.java | 148 ++- .../main/java/org/onap/vid/mso/MsoInterface.java | 41 +- .../main/java/org/onap/vid/mso/MsoProperties.java | 30 +- .../java/org/onap/vid/mso/MsoResponseWrapper.java | 4 +- .../java/org/onap/vid/mso/MsoResponseWrapper2.java | 6 +- .../onap/vid/mso/MsoResponseWrapperInterface.java | 4 +- .../src/main/java/org/onap/vid/mso/MsoUtil.java | 40 +- .../org/onap/vid/mso/RestMsoImplementation.java | 237 ++-- .../src/main/java/org/onap/vid/mso/RestObject.java | 17 +- .../onap/vid/mso/RestObjectWithRequestInfo.java | 61 + .../BaseResourceInstantiationRequestDetails.java | 142 +++ .../org/onap/vid/mso/model/CloudConfiguration.java | 173 +++ .../InstanceGroupInstantiationRequestDetails.java | 48 + .../java/org/onap/vid/mso/model/ModelInfo.java | 279 +++++ .../model/NetworkInstantiationRequestDetails.java | 86 ++ .../model/OperationalEnvironmentActivateInfo.java | 3 +- .../java/org/onap/vid/mso/model/RequestInfo.java | 376 ++++++ .../org/onap/vid/mso/model/RequestParameters.java | 123 ++ .../org/onap/vid/mso/model/RequestReferences.java | 121 ++ .../vid/mso/model/ServiceDeletionRequestDetails.kt | 15 + .../model/ServiceInstantiationRequestDetails.java | 84 +- .../java/org/onap/vid/mso/model/UserParam.java | 98 ++ .../org/onap/vid/mso/model/UserParamTypes.java | 4 + .../model/VfModuleInstantiationRequestDetails.java | 111 ++ .../java/org/onap/vid/mso/model/VfModuleMacro.java | 71 ++ .../mso/model/VnfInstantiationRequestDetails.java | 87 ++ .../vid/mso/model/VolumeGroupRequestDetails.java | 18 + .../org/onap/vid/mso/rest/AsyncRequestStatus.java | 27 +- .../onap/vid/mso/rest/AsyncRequestStatusList.java | 17 + .../java/org/onap/vid/mso/rest/InstanceIds.java | 202 +++ .../org/onap/vid/mso/rest/MsoRestClientNew.java | 186 ++- .../org/onap/vid/mso/rest/RelatedInstance.java | 84 +- .../java/org/onap/vid/mso/rest/RelatedModel.java | 125 -- .../main/java/org/onap/vid/mso/rest/Request.java | 231 +++- .../java/org/onap/vid/mso/rest/RequestDetails.java | 41 +- .../java/org/onap/vid/mso/rest/RequestList.java | 23 +- .../java/org/onap/vid/mso/rest/RequestStatus.java | 208 ++++ .../java/org/onap/vid/mso/rest/RestInterface.java | 25 +- .../java/org/onap/vid/mso/rest/SubscriberInfo.java | 144 +++ .../java/org/onap/vid/policy/PolicyProperties.java | 26 - .../org/onap/vid/policy/PolicyResponseWrapper.java | 56 - .../java/org/onap/vid/policy/PolicyRestInt.java | 66 - .../org/onap/vid/policy/PolicyRestInterface.java | 230 ---- .../vid/policy/PolicyRestInterfaceFactory.java | 14 - .../onap/vid/policy/PolicyRestInterfaceIfc.java | 58 - .../main/java/org/onap/vid/policy/PolicyUtil.java | 71 -- .../main/java/org/onap/vid/policy/RestObject.java | 68 -- .../org/onap/vid/policy/rest/RequestDetails.java | 107 -- .../java/org/onap/vid/properties/Features.java | 27 +- .../properties/FeaturesTogglingConfiguration.java | 6 +- .../org/onap/vid/properties/VidProperties.java | 34 +- .../main/java/org/onap/vid/roles/RoleProvider.java | 61 +- .../java/org/onap/vid/scheduler/RestObject.java | 44 - .../onap/vid/scheduler/RestObjects/RestObject.java | 39 - .../onap/vid/scheduler/SchedulerRestInterface.java | 62 +- .../vid/scheduler/SchedulerRestInterfaceIfc.java | 7 +- .../org/onap/vid/scheduler/SchedulerService.java | 7 + .../onap/vid/scheduler/SchedulerServiceImpl.java | 43 + .../java/org/onap/vid/services/AAIServiceTree.java | 247 ++++ .../org/onap/vid/services/AAITreeNodeBuilder.java | 281 +++++ .../java/org/onap/vid/services/AaiService.java | 10 +- .../java/org/onap/vid/services/AaiServiceImpl.java | 138 ++- .../services/AsyncInstantiationBusinessLogic.java | 39 +- .../AsyncInstantiationBusinessLogicImpl.java | 767 ++++++++---- .../java/org/onap/vid/services/AuditService.java | 11 +- .../org/onap/vid/services/AuditServiceImpl.java | 127 +- .../vid/services/BulkInstantiationService.java | 4 - .../vid/services/BulkInstantiationServiceImpl.java | 10 - .../onap/vid/services/ChangeManagementService.java | 6 +- .../vid/services/ChangeManagementServiceImpl.java | 61 +- .../org/onap/vid/services/CloudOwnerService.java | 12 + .../onap/vid/services/CloudOwnerServiceImpl.java | 76 ++ .../java/org/onap/vid/services/CsvService.java | 1 - .../java/org/onap/vid/services/CsvServiceImpl.java | 9 +- .../vid/services/RoleGenaratorServiceImpl.java | 16 +- .../java/org/onap/vid/services/VidServiceImpl.java | 6 +- .../org/onap/vid/services/WorkflowService.java | 1 - .../main/java/org/onap/vid/utils/KotlinUtils.kt | 10 + .../src/main/java/org/onap/vid/utils/Logging.java | 4 +- .../src/main/java/org/onap/vid/utils/Multival.java | 54 + .../src/main/java/org/onap/vid/utils/Streams.java | 11 +- .../main/java/org/onap/vid/utils/TimeUtils.java | 21 + .../src/main/java/org/onap/vid/utils/Tree.kt | 44 + .../main/java/org/onap/vid/utils/Unchecked.java | 23 + vid-app-common/src/main/resources/1712_ADIOD.zip | Bin 89316 -> 89573 bytes vid-app-common/src/main/resources/2f80c596.zip | Bin 87214 -> 87488 bytes vid-app-common/src/main/resources/adiod.zip | Bin 79510 -> 79927 bytes vid-app-common/src/main/resources/cacheConfig.json | 17 + .../src/main/resources/csar317927061915233480.zip | Bin 61779 -> 62196 bytes .../src/main/resources/csar3933948645405128424.zip | Bin 102261 -> 102599 bytes .../src/main/resources/json/mso/cloudConfiguration | 19 - .../src/main/resources/json/mso/instanceIds | 29 - .../src/main/resources/json/mso/modelInfo | 42 - .../src/main/resources/json/mso/relatedInstance | 16 - .../src/main/resources/json/mso/relatedModel | 15 - vid-app-common/src/main/resources/json/mso/request | 32 - .../src/main/resources/json/mso/requestDetails | 13 - .../src/main/resources/json/mso/requestError | 27 - .../src/main/resources/json/mso/requestInfo | 52 - .../src/main/resources/json/mso/requestParameters | 23 - .../src/main/resources/json/mso/requestReferences | 18 - .../src/main/resources/json/mso/requestStatus | 32 - .../src/main/resources/json/mso/response | 13 - .../src/main/resources/json/mso/subscriberInfo | 19 - vid-app-common/src/main/resources/pnf.zip | Bin 33299 -> 33397 bytes vid-app-common/src/main/resources/sdcservices.json | 42 + .../src/main/resources/service-AmpPhSvc-csar.zip | Bin 67244 -> 67661 bytes .../src/main/resources/service-vf-csar.zip | Bin 57116 -> 57455 bytes .../main/resources/service-vf-with-annotations.zip | Bin 117760 -> 118031 bytes .../src/main/resources/service-vl-csar.zip | Bin 34490 -> 34965 bytes .../webapp/WEB-INF/conf/dev.features.properties | 28 +- .../main/webapp/WEB-INF/conf/features.properties | 40 +- .../vid/scripts/constants/componentConstants.js | 21 +- .../app/vid/scripts/constants/fieldConstants.js | 5 +- .../app/vid/scripts/constants/vidConfiguration.js | 5 +- .../scripts/controller/InstantiationController.js | 131 +- .../scripts/controller/ServiceModelController.js | 13 +- .../controller/ServiceProxyConfigController.js | 21 +- .../webapp/app/vid/scripts/controller/VidApp.js | 2 +- .../scripts/controller/aaiSubscriberController.js | 132 +- .../scripts/controller/creationDialogController.js | 2 +- .../scripts/controller/msoCommitModalController.js | 9 +- .../scripts/controller/statusDialogController.js | 2 - .../app/vid/scripts/controller/subscriberSearch.js | 6 +- .../scripts/directives/parameterBlockDirective.js | 6 +- .../new-change-management.controller.js | 16 +- .../vf-module-homing-data-action.controller.js | 138 +++ .../vf-module-homing-data-action.css | 62 + .../vf-module-homing-data-action.html | 78 ++ .../webapp/app/vid/scripts/services/aaiService.js | 77 +- .../webapp/app/vid/scripts/services/asdcService.js | 59 +- .../app/vid/scripts/services/creationService.js | 6 + .../webapp/app/vid/scripts/services/dataService.js | 12 +- .../vid/scripts/services/deleteResumeService.js | 6 + .../webapp/app/vid/scripts/services/msoService.js | 38 +- .../app/vid/scripts/services/propertyService.js | 9 +- .../app/vid/scripts/view-models/aaiGetSubs.htm | 3 +- .../vid/scripts/view-models/change-management.html | 6 +- .../app/vid/scripts/view-models/instantiate.htm | 40 +- .../app/vid/scripts/view-models/serviceModels.htm | 6 +- .../vid/scripts/view-models/serviceProxyConfig.htm | 4 +- .../src/main/webapp/app/vid/test/testMso.js | 1 - .../src/main/webapp/app/vid/test/testViewEdit.js | 1 - vid-app-common/src/main/webapp/test.jsp | 29 - .../org/onap/ecomp/vid/selenium/FirstClass.java | 606 --------- .../onap/ecomp/vid/selenium/LogOutLeftPane.java | 242 ---- .../core/MockApplicationContextTestSuite.java | 177 --- .../org/onap/fusionapp/controller/NetMapTest.java | 49 - .../onap/fusionapp/service/ProfileServiceTest.java | 75 -- .../src/test/java/org/onap/vid/RelatedToTest.java | 37 - .../test/java/org/onap/vid/aai/AaiClientTest.java | 531 ++++++-- .../onap/vid/aai/AaiOverTLSClientServerTest.java | 72 +- .../org/onap/vid/aai/AaiOverTLSClientTest.java | 12 +- .../onap/vid/aai/OperationalEnvironmentTest.java | 18 +- .../test/java/org/onap/vid/aai/VnfResultTest.java | 5 +- .../onap/vid/aai/model/AaiGetPnfResponseTest.java | 10 +- .../org/onap/vid/aai/model/PnfPropertiesTest.java | 4 +- .../java/org/onap/vid/aai/model/PnfResultTest.java | 6 +- .../org/onap/vid/aai/util/CacheConfigTest.java | 32 + .../org/onap/vid/aai/util/CacheProviderTest.java | 41 + .../util/CacheProviderWithLoadingCacheTest.java | 313 +++++ .../org/onap/vid/aai/util/HttpsAuthClientTest.java | 41 +- .../onap/vid/aai/util/NonCachingCacheProvider.java | 14 + .../aai/util/ServiceInstanceStandardQueryTest.java | 405 ++++++ .../vid/aai/util/SingleAAIRestInterfaceTest.java | 75 +- .../onap/vid/asdc/beans/tosca/PropertyTest.java | 112 -- .../onap/vid/asdc/parser/ToscaParserImpl2Test.java | 281 +++-- .../vid/asdc/parser/ToscaParserInflatorTest.java | 120 ++ .../vid/asdc/parser/VidNotionsBuilderTest.java | 290 +++++ .../test/java/org/onap/vid/bl/AaiServiceTest.java | 2 +- .../org/onap/vid/client/HttpsBasicClientTest.java | 17 - .../java/org/onap/vid/config/DataSourceConfig.java | 7 +- .../vid/config/JobCommandsConfigWithMockedMso.java | 207 ++-- .../org/onap/vid/controller/AaiControllerTest.java | 12 +- ...ServiceInstanceStandardQueryControllerTest.java | 120 ++ .../controller/ChangeManagementControllerTest.java | 448 +++++++ .../controller/ClientCredentialsFilterTest.java | 1 - .../vid/controller/HealthCheckControllerTest.java | 101 ++ .../org/onap/vid/controller/LocalWebConfig.java | 23 +- .../onap/vid/controller/LoggerControllerTest.java | 49 + .../vid/controller/MaintenanceControllerTest.java | 339 ++++++ .../onap/vid/controller/MsoControllerNewTest.java | 394 ++++++ .../org/onap/vid/controller/MsoControllerTest.java | 17 +- .../vid/controller/PropertyControllerTest.java | 39 + .../controller/RoleGeneratorControllerTest.java | 26 + .../vid/controller/ServicePermissionsTest.java | 48 + .../onap/vid/controller/ToscaParserMockHelper.java | 37 +- .../onap/vid/controller/VersionControllerTest.java | 31 + .../org/onap/vid/controller/VidControllerTest.java | 204 ++++ .../vid/controller/ViewEditSubControllerTest.java | 46 + .../onap/vid/controllers/AaiControllerTest.java | 440 ------- .../ChangeManagementControllerTest.java | 455 ------- .../vid/controllers/HealthCheckControllerTest.java | 101 -- .../org/onap/vid/controllers/LocalWebConfig.java | 70 -- .../onap/vid/controllers/LoggerControllerTest.java | 54 - .../vid/controllers/MaintenanceControllerTest.java | 339 ------ .../onap/vid/controllers/MsoControllerNewTest.java | 391 ------ .../onap/vid/controllers/MsoControllerTest.java | 109 -- .../onap/vid/controllers/PolicyControllerTest.java | 30 - .../PromiseEcompRequestIdFilterTest.java | 169 --- .../vid/controllers/PropertyControllerTest.java | 40 - .../controllers/RoleGeneratorControllerTest.java | 26 - .../vid/controllers/ToscaParserMockHelper.java | 42 - .../onap/vid/controllers/VidControllerTest.java | 204 ---- .../vid/controllers/ViewEditSubControllerTest.java | 46 - .../org/onap/vid/job/command/CommandUtilsTest.java | 88 ++ .../job/command/InProgressStatusCommandTest.java | 143 --- .../job/command/InProgressStatusServiceTest.java | 83 ++ .../vid/job/command/InstanceGroupCommandTest.java | 85 ++ .../vid/job/command/JobCommandFactoryTest.java | 36 +- .../onap/vid/job/command/ResourceCommandTest.java | 303 +++++ .../ResourceInProgressStatusCommandTest.java | 40 + .../ServiceInProgressStatusCommandTest.java | 208 ++++ .../command/ServiceInstantiationCommandTest.java | 157 --- .../vid/job/command/WatchChildrenJobsBLTest.java | 98 ++ .../onap/vid/job/command/WatchingCommandTest.java | 77 ++ .../impl/AsyncInstantiationIntegrationTest.java | 925 ++++++++++++++ .../org/onap/vid/job/impl/JobAdapterImplTest.java | 110 -- .../java/org/onap/vid/job/impl/JobAdapterTest.java | 100 ++ .../vid/job/impl/JobSchedulerInitializerTest.java | 121 -- .../java/org/onap/vid/job/impl/JobWorkerTest.java | 9 +- .../org/onap/vid/model/JobAuditStatusTest.java | 40 + .../vid/model/RequestReferencesContainerTest.java | 6 +- .../org/onap/vid/mso/MsoBusinessLogicImplTest.java | 22 +- .../vid/mso/MsoOperationalEnvironmentTest.java | 14 +- .../java/org/onap/vid/mso/RequestDetailsTest.java | 63 + .../onap/vid/mso/RestMsoImplementationTest.java | 108 -- .../OperationalEnvironmentActivateInfoTest.java | 6 +- .../onap/vid/mso/rest/AsyncRequestStatusTest.java | 2 - .../onap/vid/mso/rest/MsoRestClientNewTest.java | 14 +- .../org/onap/vid/mso/rest/MsoRestClientTest.java | 14 +- .../vid/mso/rest/OutgoingRequestHeadersTest.java | 210 ++++ .../onap/vid/mso/rest/OutgoingRequestIdTest.java | 182 --- .../org/onap/vid/mso/rest/RelatedInstanceTest.java | 6 +- .../org/onap/vid/mso/rest/RelatedModelTest.java | 93 -- .../org/onap/vid/mso/rest/RequestDetailsTest.java | 8 +- .../java/org/onap/vid/mso/rest/RequestTest.java | 2 - .../onap/vid/policy/PolicyResponseWrapperTest.java | 70 -- .../org/onap/vid/policy/PolicyRestIntTest.java | 22 - .../vid/policy/PolicyRestInterfaceFactoryTest.java | 18 - .../onap/vid/policy/PolicyRestInterfaceTest.java | 32 - .../java/org/onap/vid/policy/PolicyUtilTest.java | 51 - .../java/org/onap/vid/policy/RestObjectTest.java | 48 - .../onap/vid/policy/rest/RequestDetailsTest.java | 33 - .../java/org/onap/vid/roles/RoleProviderTest.java | 14 - .../org/onap/vid/scheduler/RestObjectTest.java | 20 +- .../vid/scheduler/RestObjects/RestObjectTest.java | 1 + .../vid/scheduler/SchedulerRestInterfaceTest.java | 9 +- .../java/org/onap/vid/selenium/FirstClass.java | 605 --------- .../java/org/onap/vid/selenium/LogOutLeftPane.java | 242 ---- .../org/onap/vid/services/AAIServiceTreeTest.java | 160 +++ .../onap/vid/services/AAITreeConverterTest.java | 222 ++++ .../onap/vid/services/AAITreeNodeBuilderTest.java | 131 ++ .../vid/services/AaiResponseTranslatorTest.java | 5 +- .../vid/services/AsyncInstantiationBaseTest.java | 220 ++-- .../AsyncInstantiationBusinessLogicTest.java | 877 ++++++++++--- .../onap/vid/services/AuditServiceImplTest.java | 36 +- .../services/BulkInstantiationServiceImplTest.java | 36 +- .../services/ChangeManagementServiceImplTest.java | 20 +- .../vid/services/ChangeManagementServiceTest.java | 29 - .../services/ChangeManagementServiceUnitTest.java | 9 +- .../onap/vid/services/CloudOwnerServiceTest.java | 125 ++ .../java/org/onap/vid/services/CsvServiceTest.java | 162 +-- .../onap/vid/services/JobsBrokerServiceTest.java | 1287 ++++++++++---------- .../vid/services/PortDetailsTranslatorTest.java | 261 ++-- .../vid/services/SchedulerServiceImplTest.java | 179 +++ .../java/org/onap/vid/testUtils/TestUtils.java | 58 +- .../test/java/org/onap/vid/utils/LoggingTest.java | 10 +- .../java/org/onap/vid/utils/LoggingUtilsTest.java | 10 +- .../java/org/onap/vid/utils/TimeUtilsTest.java | 67 + .../src/test/java/org/onap/vid/utils/TreeTest.java | 63 + .../WEB-INF/fusion/conf/fusion.properties | 39 +- .../resources/WEB-INF/fusion/defs/definitions.xml | 25 +- .../fusion/orm/RNoteBookIntegration.hbm.xml | 34 +- vid-app-common/src/test/resources/cacheConfig.json | 13 + vid-app-common/src/test/resources/cr-csar.JSON | 6 +- .../src/test/resources/csv_files/csv_to_json.csv | 2 +- .../src/test/resources/fabric-configuration.json | 52 + .../resources/fabric-real-sriov-configuration.json | 51 + .../org.mockito.plugins.MockMaker | 1 + .../orchestrationRequestsByServiceInstanceId.json | 200 +++ .../bulk_alacarte_service_deletion_request.json | 19 + .../bulk_alacarte_service_request.json | 34 + ...bulk_alacarte_service_request_naming_false.json | 32 + .../payload_jsons/bulk_macro_service_request.json | 97 ++ .../payload_jsons/bulk_service_request.json | 95 -- .../bulk_service_request_ecomp_naming.json | 9 +- ...k_service_request_no_vfmodule_ecomp_naming.json | 1 + .../bulk_service_request_unique_names.json | 21 +- .../resources/payload_jsons/bulk_vnf_request.json | 48 + .../bulk_vnf_request_without_cloud_owner.json | 47 + .../bulk_vnf_request_without_instance_name.json | 47 + .../instance_group_instantiation_request.json | 36 + .../network_instantiation_request.json | 48 + ...nstantiation_request_without_instance_name.json | 47 + .../payload_jsons/scaleOutVfModulePayload.json | 17 +- .../scaleOutVfModulePayloadToMso.json | 16 +- .../vfModuleDeactivateAndCloudDelete.json | 17 + .../vfmodule_instantiation_request.json | 69 ++ ...nstantiation_request_without_instance_name.json | 59 + ...instantiation_request_without_volume_group.json | 60 + .../volumegroup_instantiation_request.json | 56 + .../policy-configuration-by-policy-false.JSON | 9 +- .../test/resources/policy-configuration-csar.JSON | 33 +- .../aai/getCloudRegionAndTenantByVnfId.json | 119 ++ ...orchestrationRequestsMockedMinimalResponse.json | 11 + .../mso/orchestrationRequestsServiceInstance.json | 19 + .../responses/mso/orchestrationRequestsVnf.json | 68 ++ vid-app-common/src/test/resources/vf-csar.JSON | 12 +- .../test/resources/vf-with-annotation-csar.json | 102 +- .../test/resources/vf-with-vfcInstanceGroups.json | 9 +- vid-app-common/src/test/resources/vl-csar.JSON | 9 +- .../src/test/resources/vlan-tagging.json | 222 ++++ .../src/test/resources/vnf-grouping-csar.json | 145 +++ .../src/test/resources/vnfConfigUpdatePayload.json | 2 +- vid-automation/TestNg-ApiTest.xml | 2 +- vid-automation/TestNg-UI-half.xml | 15 +- vid-automation/TestNg-dev.xml | 41 + vid-automation/TestNg.xml | 35 - vid-automation/conf/services | 2 +- vid-automation/conf/users | 4 +- vid-automation/pom.xml | 11 +- .../mso/PresetMSOServiceInstanceGen2WithNames.java | 2 +- .../vid/automation/test/services/UsersService.java | 2 - .../vid/automation/test/test/VidBaseTestCase.java | 19 +- .../test/test/ViewEditServiceInstanceTest.java | 3 +- .../java/vid/automation/test/utils/DB_CONFIG.java | 2 +- .../src/main/resources/META-INF/aop-ajc.xml | 16 - .../onap/vid/api/AsyncInstantiationApiTest.java | 11 +- .../test/java/org/onap/vid/api/BaseApiAaiTest.java | 2 +- .../test/java/org/onap/vid/api/BaseApiTest.java | 9 +- .../test/java/org/onap/vid/api/BaseMsoApiTest.java | 4 +- .../org/onap/vid/api/ChangeManagementApiTest.java | 4 +- .../OperationalEnvironmentControllerApiTest.java | 2 +- .../test/java/org/onap/vid/api/ProbeApiTest.java | 7 +- .../test/java/org/onap/vid/api/SampleApiTest.java | 2 +- .../vid/model/probe/ExternalComponentStatus.java | 2 +- .../java/org/onap/vid/more/LoggerFormatTest.java | 2 +- .../onap/vid/more/RequestIdFilterInstalled.java | 4 +- .../src/test/resources/test_config.properties | 4 +- vid-ext-services-simulator/pom.xml | 6 +- 591 files changed, 26972 insertions(+), 16086 deletions(-) create mode 100644 vid-app-common/TestNg-BE-UnitTest.xml delete mode 100644 vid-app-common/src/main/java/org/onap/vid/RelatedTo.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/CloudRegion.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vlan.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vnf.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/model/CustomQuerySimpleResult.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/model/Permissions.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/model/interfaces/AaiModelWithRelationships.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/util/CacheConfig.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProvider.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProviderWithLoadingCache.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/aai/util/ServiceInstanceStandardQuery.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/asdc/parser/ServiceModelInflator.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaNamingPolicy.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/AaiController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/AaiController2.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/AsyncControllerForTests.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/ChangeManagementController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/ControllersUtils.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/FeatureTogglingController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/HealthCheckController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/HealthStatus.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/MaintenanceController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/ProbeController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/PropertyController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/RoleGeneratorController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/VersionController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/VidController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/VidRestrictedBaseController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/ViewLogController.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/LoggerController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/ViewLogController.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/JobException.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceCommand.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/BaseInProgressStatusCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/BaseInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/BaseRootCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/BaseWatchingCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/CommandBase.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/CommandParentData.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/CommandUtils.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ExpiryChecker.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusService.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupCommand.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/MsoResult.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/NetworkInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInProgressStatusCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ResourceWithChildrenInProgressCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInProgressStatusCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/VnfInProgressStatusCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/VnfInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInProgressStatusCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInstantiationCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/WatchChildrenJobsBL.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommand.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommandBaseModule.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/impl/JobData.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/job/impl/JobSharedData.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/Action.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/MinimalNode.kt delete mode 100644 vid-app-common/src/main/java/org/onap/vid/model/Resource.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/ResourceGroup.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/SoftDeleteRequest.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AAITreeNode.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AbstractNode.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/FailureAAITreeNode.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Network.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Node.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VfModule.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Vnf.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VnfGroup.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/BaseResource.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/InstanceGroup.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Network.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/RestObjectWithRequestInfo.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/BaseResourceInstantiationRequestDetails.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/CloudConfiguration.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/InstanceGroupInstantiationRequestDetails.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/ModelInfo.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/NetworkInstantiationRequestDetails.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/RequestInfo.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/RequestParameters.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/RequestReferences.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceDeletionRequestDetails.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/UserParam.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/UserParamTypes.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleInstantiationRequestDetails.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleMacro.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/VnfInstantiationRequestDetails.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatusList.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/rest/InstanceIds.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedModel.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestStatus.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/mso/rest/SubscriberInfo.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyProperties.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyResponseWrapper.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInt.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceFactory.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/PolicyUtil.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/RestObject.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/policy/rest/RequestDetails.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/scheduler/RestObject.java delete mode 100644 vid-app-common/src/main/java/org/onap/vid/scheduler/RestObjects/RestObject.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerService.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerServiceImpl.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerService.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerServiceImpl.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/utils/KotlinUtils.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/utils/Multival.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/utils/TimeUtils.java create mode 100644 vid-app-common/src/main/java/org/onap/vid/utils/Tree.kt create mode 100644 vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java create mode 100644 vid-app-common/src/main/resources/cacheConfig.json delete mode 100755 vid-app-common/src/main/resources/json/mso/cloudConfiguration delete mode 100755 vid-app-common/src/main/resources/json/mso/instanceIds delete mode 100755 vid-app-common/src/main/resources/json/mso/modelInfo delete mode 100755 vid-app-common/src/main/resources/json/mso/relatedInstance delete mode 100755 vid-app-common/src/main/resources/json/mso/relatedModel delete mode 100755 vid-app-common/src/main/resources/json/mso/request delete mode 100755 vid-app-common/src/main/resources/json/mso/requestDetails delete mode 100755 vid-app-common/src/main/resources/json/mso/requestError delete mode 100755 vid-app-common/src/main/resources/json/mso/requestInfo delete mode 100755 vid-app-common/src/main/resources/json/mso/requestParameters delete mode 100755 vid-app-common/src/main/resources/json/mso/requestReferences delete mode 100755 vid-app-common/src/main/resources/json/mso/requestStatus delete mode 100755 vid-app-common/src/main/resources/json/mso/response delete mode 100755 vid-app-common/src/main/resources/json/mso/subscriberInfo create mode 100644 vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.controller.js create mode 100644 vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.css create mode 100644 vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.html delete mode 100755 vid-app-common/src/main/webapp/test.jsp delete mode 100644 vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java delete mode 100644 vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java delete mode 100644 vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java delete mode 100644 vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java create mode 100644 vid-app-common/src/test/resources/cacheConfig.json create mode 100644 vid-app-common/src/test/resources/fabric-configuration.json create mode 100644 vid-app-common/src/test/resources/fabric-real-sriov-configuration.json create mode 100644 vid-app-common/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker create mode 100644 vid-app-common/src/test/resources/orchestrationRequestsByServiceInstanceId.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_deletion_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_request_naming_false.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_macro_service_request.json delete mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_service_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_vnf_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_vnf_request_without_cloud_owner.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/bulk_vnf_request_without_instance_name.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/instance_group_instantiation_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/network_instantiation_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/network_instantiation_request_without_instance_name.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/vfModuleDeactivateAndCloudDelete.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/vfmodule_instantiation_request.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/vfmodule_instantiation_request_without_instance_name.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/vfmodule_instantiation_request_without_volume_group.json create mode 100644 vid-app-common/src/test/resources/payload_jsons/volumegroup_instantiation_request.json create mode 100644 vid-app-common/src/test/resources/responses/aai/getCloudRegionAndTenantByVnfId.json create mode 100644 vid-app-common/src/test/resources/responses/mso/orchestrationRequestsMockedMinimalResponse.json create mode 100644 vid-app-common/src/test/resources/responses/mso/orchestrationRequestsServiceInstance.json create mode 100644 vid-app-common/src/test/resources/responses/mso/orchestrationRequestsVnf.json create mode 100644 vid-app-common/src/test/resources/vlan-tagging.json create mode 100644 vid-app-common/src/test/resources/vnf-grouping-csar.json create mode 100644 vid-automation/TestNg-dev.xml delete mode 100644 vid-automation/TestNg.xml diff --git a/epsdk-app-onap/pom.xml b/epsdk-app-onap/pom.xml index fec6d0cc..235716bd 100755 --- a/epsdk-app-onap/pom.xml +++ b/epsdk-app-onap/pom.xml @@ -129,7 +129,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + 2.22.1 ${skiptests} @@ -208,7 +208,7 @@ - org.sonarsource.scanner.maven + org.sonarsource.scanner.maven sonar-maven-plugin 3.3.0.603 diff --git a/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java b/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java index 0c6fba9a..3fa08396 100644 --- a/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java +++ b/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java @@ -37,11 +37,6 @@ */ package org.onap.portalapp.conf; -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; - import org.onap.portalapp.login.LoginStrategyImpl; import org.onap.portalapp.scheduler.RegistryAdapter; import org.onap.portalsdk.core.auth.LoginStrategy; @@ -54,13 +49,11 @@ import org.onap.portalsdk.core.util.CacheManager; import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; +import org.springframework.context.annotation.*; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.DataSourceInitializer; +import org.springframework.jdbc.datasource.init.DatabasePopulator; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @@ -70,10 +63,10 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.core.io.Resource; -import org.springframework.jdbc.datasource.init.DataSourceInitializer; -import org.springframework.jdbc.datasource.init.DatabasePopulator; -import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; /** * ONAP Portal SDK sample application. Extends core AppConfig class to @@ -86,6 +79,7 @@ import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; @Profile("src") @EnableAsync @EnableScheduling +@EnableAspectJAutoProxy(proxyTargetClass=true) public class ExternalAppConfig extends AppConfig implements Configurable { private RegistryAdapter schedulerRegistryAdapter; @@ -177,18 +171,12 @@ public class ExternalAppConfig extends AppConfig implements Configurable { * populates it with triggers. * * @return New instance of {@link SchedulerFactoryBean} - * @throws Exception */ - @Bean // ANNOTATION COMMENTED OUT - // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION - @DependsOn("dataSourceInitializer") - public SchedulerFactoryBean schedulerFactoryBean() throws Exception { - SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); - scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); - scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); - scheduler.setDataSource(dataSource()); - scheduler.setJobFactory(new SpringBeanJobFactory()); - return scheduler; + @Bean + public SchedulerFactoryBean schedulerFactoryBean() { + SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean(); + schedulerFactory.setJobFactory(new SpringBeanJobFactory()); + return schedulerFactory; } diff --git a/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java b/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java index 93e867d6..dc6973fe 100644 --- a/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java +++ b/epsdk-app-onap/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java @@ -37,12 +37,8 @@ */ package org.onap.portalapp.conf; -import org.onap.vid.controllers.ChangeManagementController; -import org.onap.vid.controllers.MaintenanceController; -import org.onap.vid.controllers.RoleGeneratorController; import org.onap.portalsdk.core.conf.AppInitializer; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; + import java.util.TimeZone; public class ExternalAppInitializer extends AppInitializer { diff --git a/pom.xml b/pom.xml index 70a7ac74..eff36494 100644 --- a/pom.xml +++ b/pom.xml @@ -1,249 +1,249 @@ - - 4.0.0 - org.onap.vid - vid-parent - 4.0.0-SNAPSHOT - pom - vid - - - - - - onap - - true - - - vid-app-common - vid-webpack-master - epsdk-app-onap - - - - - ecomp-releases - VID Release Repository - ${nexusproxy}/${releaseNexusPath} - - - ecomp-snapshots - VID Snapshot Repository - ${nexusproxy}/${snapshotNexusPath} - - - ecomp-staging - VID Staging Repository - ${nexusproxy}/${stagingNexusPath} - - - - oss-snapshots - oss Central - Snapshots - https://oss.sonatype.org/service/local/repositories/releases/content/ - - - - - - ecomp-releases - VID Release Repository - ${nexusproxy}/${releaseNexusPath} - - - ecomp-snapshots - VID Snapshot Repository - ${nexusproxy}/${snapshotNexusPath} - - - - ecomp-site - dav:${nexusproxy}${sitePath} - - - - - - - docker - - vid-app-common - vid-webpack-master - epsdk-app-onap - deliveries - - - - - - UTF-8 - UTF-8 - 4.0.0-SNAPSHOT - https://nexus.onap.org - /content/repositories/snapshots/ - /content/repositories/releases/ - /content/repositories/staging/ - /content/sites/site/org/onap/vid/${project.version} - - - - - - org.codehaus.mojo - versions-maven-plugin - 1.3.1 - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ${nexusproxy} - 176c31dfe190a - ecomp-staging - - - - - org.apache.maven.plugins - maven-site-plugin - 3.6 - - - org.apache.maven.wagon - wagon-webdav-jackrabbit - 2.10 - - - - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.17 - - false - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - - true - -Xlint - true - true - true - 1.8 - 1.8 - - - - org.sonarsource.scanner.maven - sonar-maven-plugin - 3.3.0.603 - - - com.blackducksoftware.integration - hub-maven-plugin - 1.4.0 - false - - ${project.name} - ${project.basedir} - - - - create-bdio-file - package - - createHubOutput - - - - - - - - - - - - JCenter - JCenter Repository - http://jcenter.bintray.com - - - - Restlet - Restlet Repository - http://maven.restlet.com - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.4 - - false - org.umlgraph.doclet.UmlGraphDoc - - org.umlgraph - umlgraph - 5.6 - - -views - true - - - - - - - junit - junit - 4.11 - test - - - - - ch.qos.logback - logback-core - 1.2.3 - - - ch.qos.logback - logback-classic - 1.2.3 - - - commons-collections - commons-collections - 3.2.2 - - - org.apache.poi - poi - 3.17 - - - org.apache.httpcomponents - httpclient - 4.5.3 - - - + + 4.0.0 + org.onap.vid + vid-parent + 4.0.0-SNAPSHOT + pom + vid + + + + + + onap + + true + + + vid-app-common + vid-webpack-master + epsdk-app-onap + + + + + ecomp-releases + VID Release Repository + ${nexusproxy}/${releaseNexusPath} + + + ecomp-snapshots + VID Snapshot Repository + ${nexusproxy}/${snapshotNexusPath} + + + ecomp-staging + VID Staging Repository + ${nexusproxy}/${stagingNexusPath} + + + + oss-snapshots + oss Central - Snapshots + https://oss.sonatype.org/service/local/repositories/releases/content/ + + + + + + ecomp-releases + VID Release Repository + ${nexusproxy}/${releaseNexusPath} + + + ecomp-snapshots + VID Snapshot Repository + ${nexusproxy}/${snapshotNexusPath} + + + + ecomp-site + dav:${nexusproxy}${sitePath} + + + + + + + docker + + vid-app-common + vid-webpack-master + epsdk-app-onap + deliveries + + + + + + UTF-8 + UTF-8 + 4.0.0-SNAPSHOT + https://nexus.onap.org + /content/repositories/snapshots/ + /content/repositories/releases/ + /content/repositories/staging/ + /content/sites/site/org/onap/vid/${project.version} + + + + + + org.codehaus.mojo + versions-maven-plugin + 1.3.1 + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ${nexusproxy} + 176c31dfe190a + ecomp-staging + + + + + org.apache.maven.plugins + maven-site-plugin + 3.6 + + + org.apache.maven.wagon + wagon-webdav-jackrabbit + 2.10 + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + false + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + true + -Xlint + true + true + true + 1.8 + 1.8 + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + 3.3.0.603 + + + com.blackducksoftware.integration + hub-maven-plugin + 1.4.0 + false + + ${project.name} + ${project.basedir} + + + + create-bdio-file + package + + createHubOutput + + + + + + + + + + + + JCenter + JCenter Repository + http://jcenter.bintray.com + + + + Restlet + Restlet Repository + http://maven.restlet.com + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + false + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + umlgraph + 5.6 + + -views + true + + + + + + + junit + junit + 4.11 + test + + + + + ch.qos.logback + logback-core + 1.2.3 + + + ch.qos.logback + logback-classic + 1.2.3 + + + commons-collections + commons-collections + 3.2.2 + + + org.apache.poi + poi + 3.17 + + + org.apache.httpcomponents + httpclient + 4.5.3 + + + diff --git a/vid-app-common/TestNg-BE-UnitTest.xml b/vid-app-common/TestNg-BE-UnitTest.xml new file mode 100644 index 00000000..b4b05bd7 --- /dev/null +++ b/vid-app-common/TestNg-BE-UnitTest.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/vid-app-common/pom.xml b/vid-app-common/pom.xml index 175c0771..79d8cdd4 100755 --- a/vid-app-common/pom.xml +++ b/vid-app-common/pom.xml @@ -21,6 +21,10 @@ 2.4.0 4.2.9.RELEASE 4.3.11.Final + 2.9.7 + 2.27 + 2.22.1 + true @@ -30,6 +34,11 @@ /content/repositories/releases/ /content/repositories/staging/ /content/sites/site/org/onap/vid/${project.version} + + 1.8.9 + 1.3.11 + 1.8 + @@ -82,6 +91,33 @@ vid-common + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + compile + compile + + + ${project.basedir}/src/main/java + + + + + test-compile + test-compile + + + ${project.basedir}/src/test/java + + + + + + org.sonatype.plugins nexus-staging-maven-plugin @@ -123,39 +159,44 @@ 2.2 - - org.jsonschema2pojo - jsonschema2pojo-maven-plugin - 0.4.23 + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 - ${basedir}/src/main/resources/json/mso - org.onap.vid.domain.mso - ${project.build.directory}/generated-sources + 1.8 + 1.8 + + - - generate - + default-compile + none + + + + default-testCompile + none + + + java-compile + compile + compile + + + java-test-compile + test-compile + testCompile - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + ${surefire.version} ${skiptests} @@ -174,7 +215,29 @@ classpath: false + + + + junit + false + + + 1 + + + + + org.apache.maven.surefire + surefire-junit47 + ${surefire.version} + + + org.apache.maven.surefire + surefire-testng + ${surefire.version} + + @@ -237,8 +300,7 @@ yyyy-MM-dd'T'HH:mm:ssZ ${user.timezone} true - ${project.build.outputDirectory}/git.properties - + ${project.build.outputDirectory}/git.properties ^git.commit.id$ ^git.commit.message.short$ @@ -288,7 +350,7 @@ org.apache.httpcomponents httpclient - 4.3.6 + 4.5.6 org.apache.httpcomponents @@ -371,26 +433,32 @@ 1.2.3 + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + com.fasterxml.jackson.core jackson-annotations - 2.6.3 + ${jackson.version} com.fasterxml.jackson.core jackson-core - 2.8.6 + ${jackson.version} com.fasterxml.jackson.core jackson-databind - 2.6.7.1 + ${jackson.version} - org.codehaus.jackson - jackson-mapper-asl - 1.9.13 + com.fasterxml.jackson.module + jackson-module-kotlin + ${jackson.version} com.mchange @@ -418,6 +486,7 @@ junit junit 4.12 + test commons-io @@ -493,17 +562,23 @@ org.glassfish.jersey.core jersey-client - 2.23.1 + ${jersey.version} org.glassfish.jersey.connectors jersey-jetty-connector - 2.23.1 + ${jersey.version} + + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey.version} com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider - 2.6.3 + ${jackson.version} commons-beanutils @@ -530,7 +605,7 @@ org.testng testng - 6.8 + 6.14.3 test @@ -558,11 +633,12 @@ org.skyscreamer jsonassert 1.5.0 + test org.onap.sdc.sdc-tosca sdc-tosca - 1.4.1 + 1.4.7 compile @@ -571,11 +647,27 @@ 1.23.0 test + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey.version} + test + + + org.apache.commons + commons-lang3 + 3.6 + org.apache.commons commons-text 1.1 + + org.apache.commons + commons-proxy + 1.0 + org.hamcrest java-hamcrest @@ -587,11 +679,28 @@ togglz-spring-core 2.5.0.Final + + com.h2database + h2 + 1.4.196 + test + + + javax.xml.bind + jaxb-api + 2.2.11 + + org.assertj assertj-core 3.10.0 compile + + com.google.guava + guava + 23.0 + diff --git a/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java b/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java deleted file mode 100644 index 08e02816..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/RelatedTo.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.onap.vid; - -import com.fasterxml.jackson.annotation.*; -import org.codehaus.jackson.annotate.JsonProperty; - -import java.util.HashMap; -import java.util.Map; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "id", - "node-type", - "relationship-label", - "url" -}) -public class RelatedTo { - - @JsonProperty("id") - public String id; - @JsonProperty("node-type") - public String nodeType; - @JsonProperty("relationship-label") - public String relationshipLabel; - @JsonProperty("url") - public String url; - @JsonIgnore - private Map additionalProperties = new HashMap<>(); - - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java index baf92b88..e1a1e706 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java @@ -1,25 +1,25 @@ package org.onap.vid.aai; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.client.utils.URIBuilder; -import org.codehaus.jackson.JsonNode; -import org.codehaus.jackson.map.ObjectMapper; +import org.jetbrains.annotations.NotNull; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.aai.exceptions.InvalidAAIResponseException; import org.onap.vid.aai.model.AaiGetAicZone.AicZones; import org.onap.vid.aai.model.*; import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.*; import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone; -import org.onap.vid.aai.model.Relationship; -import org.onap.vid.aai.model.RelationshipData; -import org.onap.vid.aai.model.RelationshipList; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.CacheProvider; import org.onap.vid.aai.util.VidObjectMapperType; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.SubscriberList; @@ -27,6 +27,8 @@ import org.onap.vid.model.probes.ErrorMetadata; import org.onap.vid.model.probes.ExternalComponentStatus; import org.onap.vid.model.probes.HttpRequestMetadata; import org.onap.vid.utils.Logging; +import org.onap.vid.utils.Unchecked; +import org.springframework.http.HttpMethod; import org.springframework.web.util.UriUtils; import javax.inject.Inject; @@ -34,15 +36,16 @@ import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.net.URI; import java.net.URLEncoder; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.UUID; +import java.util.function.Function; import static java.util.Collections.emptyList; +import static java.util.stream.Collectors.toMap; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; /** @@ -52,13 +55,13 @@ import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; public class AaiClient implements AaiClientInterface { - public static final String QUERY_FORMAT_RESOURCE = "query?format=resource"; - public static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/"; - public static final String MODEL_INVARIANT_ID = "&model-invariant-id="; - public static final String QUERY_FORMAT_SIMPLE = "query?format=simple"; - public static final String BUSINESS_CUSTOMER = "/business/customers/customer/"; - public static final String SERVICE_INSTANCE = "/service-instances/service-instance/"; - public static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/"; + private static final String QUERY_FORMAT_RESOURCE = "query?format=resource"; + private static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/"; + private static final String MODEL_INVARIANT_ID = "&model-invariant-id="; + private static final String QUERY_FORMAT_SIMPLE = "query?format=simple"; + private static final String BUSINESS_CUSTOMER = "/business/customers/customer/"; + private static final String SERVICE_INSTANCE = "/service-instances/service-instance/"; + private static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/"; protected String fromAppId = "VidAaiController"; @@ -66,22 +69,22 @@ public class AaiClient implements AaiClientInterface { private final AAIRestInterface restController; + private final CacheProvider cacheProvider; + + ObjectMapper objectMapper = new ObjectMapper(); + /** * The logger */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class); - /** - * The Constant dateFormat. - */ - static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}"; + private static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}"; @Inject - public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator) { + public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) { this.restController = restController; this.portDetailsTranslator = portDetailsTranslator; + this.cacheProvider = cacheProvider; } @@ -107,8 +110,14 @@ public class AaiClient implements AaiClientInterface { @Override public AaiResponse getServiceModelsByDistributionStatus() { - Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, GET_SERVICE_MODELS_RESPONSE_BODY, false); - return processAaiResponse(resp, GetServiceModelsByDistributionStatusResponse.class, null); + return getFromCache("getServiceModelsByDistributionStatus", this::getServiceModelsByDistributionStatusNonCached, + true, "Failed to get service models by distribution status"); + } + + private AaiResponse getServiceModelsByDistributionStatusNonCached(boolean propagateExceptions) { + GetServiceModelsByDistributionStatusResponse response = typedAaiRest(QUERY_FORMAT_RESOURCE, GetServiceModelsByDistributionStatusResponse.class, + GET_SERVICE_MODELS_RESPONSE_BODY, HttpMethod.PUT, propagateExceptions); + return new AaiResponse(response, "", HttpStatus.SC_OK); } @Override @@ -121,14 +130,14 @@ public class AaiClient implements AaiClientInterface { @Override public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) { Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, - "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId + "\"]," + - "\"query\": \"query/instance-group-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + networkFunction + "\"}\n", false); + "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + encodePathSegment(cloudOwner) + "/" + encodePathSegment(cloudRegionId) + "\"]," + + "\"query\": \"query/instance-groups-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + encodePathSegment(networkFunction) + "\"}\n", false); return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML); } private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse aaiResponse){ if(aaiResponse.getHttpCode() == 200) { - com.fasterxml.jackson.databind.ObjectMapper om = new com.fasterxml.jackson.databind.ObjectMapper(); + ObjectMapper om = objectMapper; AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails(); try { for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) { @@ -145,7 +154,8 @@ public class AaiClient implements AaiClientInterface { return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK); } catch (com.fasterxml.jackson.databind.JsonMappingException e) { - return new AaiResponse(e.getCause(), "AAI response parsing Error" , aaiResponse.getHttpCode()); + logger.error(EELFLoggerDelegate.errorLogger, "AAI response parsing Error", e); + return new AaiResponse(e.getCause(), "AAI response parsing Error" , HttpStatus.SC_INTERNAL_SERVER_ERROR); } catch (Exception e) { return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode()); @@ -183,7 +193,7 @@ public class AaiClient implements AaiClientInterface { Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems String rawPayload = resp.readEntity(String.class); - AaiResponse aaiResponse = processAaiResponse(resp, AaiGetPortMirroringSourcePorts.class, rawPayload); + AaiResponse aaiResponse = processAaiResponse(resp, CustomQuerySimpleResult.class, rawPayload); return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload); } @@ -202,21 +212,80 @@ public class AaiClient implements AaiClientInterface { } @Override - public AaiResponse searchNodeTypeByName(String name, ResourceType type) { - String path = String.format( - "search/nodes-query?search-node-type=%s&filter=%s:EQUALS:%s", + public boolean isNodeTypeExistsByName(String name, ResourceType type) { + if (StringUtils.isEmpty(name)) { + throw new GenericUncheckedException("Empty resource-name provided to searchNodeTypeByName; request is rejected as this will cause full resources listing"); + } + + URI path = Unchecked.toURI(String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name} + "nodes/%s?%s=%s", type.getAaiFormat(), type.getNameFilter(), - name - ); - return typedAaiGet(path, AaiNodeQueryResponse.class); + encodePathSegment(name) + )); + final ResponseWithRequestInfo responseWithRequestInfo = restController.RestGet(fromAppId, UUID.randomUUID().toString(), path, false, true); + + return isResourceExistByStatusCode(responseWithRequestInfo); + } + + public Map getCloudRegionAndTenantByVnfId(String vnfId) { + String start = "/network/generic-vnfs/generic-vnf/" + vnfId; + String query = "/query/cloud-region-fromVnf"; + + String payload = "{\"start\":[\"" + start + "\"],\"query\":\"" + query + "\"}"; + CustomQuerySimpleResult result = typedAaiRest(QUERY_FORMAT_SIMPLE, CustomQuerySimpleResult.class, payload, HttpMethod.PUT, false); + + return result.getResults().stream() + .filter(res -> StringUtils.equals(res.getNodeType(), "tenant") || + StringUtils.equals(res.getNodeType(), "cloud-region")) + .collect(toMap(SimpleResult::getNodeType, SimpleResult::getProperties)); + } + + private boolean isResourceExistByStatusCode(ResponseWithRequestInfo responseWithRequestInfo) { + // 200 - is found + // 404 - resource not found + Response.Status statusInfo = responseWithRequestInfo.getResponse().getStatusInfo().toEnum(); + switch (statusInfo) { + case OK: + return true; + case NOT_FOUND: + return false; + default: + throw new GenericUncheckedException("Unexpected response-code (only OK and NOT_FOUND are expected): " + + responseWithRequestInfo.getResponse().getStatusInfo()); + } } - private AaiResponse typedAaiGet(String path, Class clz) { - Response resp = doAaiGet(path , false); - return processAaiResponse(resp, clz, null, VidObjectMapperType.FASTERXML); + @Override + public T typedAaiGet(URI uri, Class clz) { + return typedAaiRest(uri, clz, null, HttpMethod.GET, false); } + public T typedAaiRest(String path, Class clz, String payload, HttpMethod method, boolean propagateExceptions) { + return typedAaiRest(Unchecked.toURI(path), clz, payload, method, propagateExceptions); + } + + + public T typedAaiRest(URI path, Class clz, String payload, HttpMethod method, boolean propagateExceptions) { + ResponseWithRequestInfo responseWithRequestInfo; + try { + responseWithRequestInfo = restController.doRest(fromAppId, UUID.randomUUID().toString(), path, payload, method, false, propagateExceptions); + } catch (Exception e) { + responseWithRequestInfo = handleExceptionFromRestCall(propagateExceptions, "doAai"+method.name(), e); + } + + final AaiResponseWithRequestInfo aaiResponse = processAaiResponse(responseWithRequestInfo, clz, VidObjectMapperType.FASTERXML, true); + + if (aaiResponse.getAaiResponse().getHttpCode() > 399 || aaiResponse.getAaiResponse().getT() == null) { + throw new ExceptionWithRequestInfo(aaiResponse.getHttpMethod(), + aaiResponse.getRequestedUrl(), + aaiResponse.getRawData(), + responseWithRequestInfo.getResponse().getStatus(), + new InvalidAAIResponseException(aaiResponse.getAaiResponse())); + } + + return aaiResponse.getAaiResponse().getT(); + } private String getUrlFromLIst(String url, String paramKey, List params){ @@ -229,8 +298,8 @@ public class AaiClient implements AaiClientInterface { encodedParam= URLEncoder.encode(param, "UTF-8"); } catch (UnsupportedEncodingException e) { String methodName = "getUrlFromList"; - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString()); } url = url.concat(encodedParam); if(i != params.size()){ @@ -241,9 +310,34 @@ public class AaiClient implements AaiClientInterface { } + @Override public AaiResponse getAllSubscribers() { - return getAllSubscribers(false).getAaiResponse(); + return getFromCache("getAllSubscribers", this::getAllSubscribersNonCached, true, "Failed to get all subscribers"); + } + + private AaiResponse getFromCache(String cacheName, Function function, K argument, String errorMessage) { + try { + return cacheProvider + .aaiClientCacheFor(cacheName, function) + .get(argument); + } catch (ExceptionWithRequestInfo exception) { + logger.error(errorMessage, exception); + return new AaiResponse(null, exception.getRawData(), exception.getHttpCode()); + } + catch (Exception exception) { + logger.error(errorMessage, exception); + return new AaiResponse(null, exception.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + } + + private AaiResponse getAllSubscribersNonCached(boolean propagateExceptions) { + AaiResponse aaiResponse = getAllSubscribers(propagateExceptions).getAaiResponse(); + if (propagateExceptions && (aaiResponse.getT() == null || aaiResponse.getT().customer == null || aaiResponse.getT().customer.isEmpty())) { + throw new GenericUncheckedException("Failed to get Subscribers data. The data is null or empty."); + } else { + return aaiResponse; + } } AaiResponseWithRequestInfo getAllSubscribers(boolean propagateExceptions){ @@ -262,33 +356,12 @@ public class AaiClient implements AaiClientInterface { return processAaiResponse(resp, AicZones.class, null); } - - @Override - public AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) { - String aicZonePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType + SERVICE_INSTANCE + serviceId; - Response resp = doAaiGet(aicZonePath , false); - AaiResponse aaiResponse = processAaiResponse(resp , ServiceRelationships.class , null); - ServiceRelationships serviceRelationships = aaiResponse.getT(); - RelationshipList relationshipList = serviceRelationships.getRelationshipList(); - Relationship relationship = relationshipList.getRelationship().get(0); - RelationshipData relationshipData= relationship.getRelationDataList().get(0); - String aicZone = relationshipData.getRelationshipValue(); - return new AaiResponse(aicZone , null ,HttpStatus.SC_OK); - } - - @Override - public AaiResponse getVNFData() { - String payload = "{\"start\": [\"/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/3f93c7cb-2fd0-4557-9514-e189b7b04f9d\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}"; - Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); - return processAaiResponse(resp, AaiGetVnfResponse.class, null); - } - - @Override - public Response getVNFData(String globalSubscriberId, String serviceType) { + public AaiResponse getVNFData(String globalSubscriberId, String serviceType) { String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," + "\"query\": \"query/vnf-topology-fromServiceInstance\"}"; - return doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); + Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false); + return processAaiResponse(resp, AaiGetVnfResponse.class, null); } @Override @@ -343,22 +416,17 @@ public class AaiClient implements AaiClientInterface { @Override public AaiResponse getTenants(String globalCustomerId, String serviceType) { - AaiResponse aaiResponse; - if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty())) ){ - aaiResponse = new AaiResponse<>(null, "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}", HttpStatus.SC_INTERNAL_SERVER_ERROR); - return aaiResponse; + return buildAaiResponseForGetTenantsFailure(" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing."); } - - String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType; - - Response resp = doAaiGet(url, false); - String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class)); - if (responseAsString.equals("")){ - return new AaiResponse<>(null, String.format("{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'\"}", globalCustomerId, serviceType), HttpStatus.SC_INTERNAL_SERVER_ERROR); + try { + return cacheProvider + .aaiClientCacheFor("getTenants", this::getTenantsByKey) + .get(CacheProvider.compileKey(globalCustomerId, serviceType)); } - else { - return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString); + catch (ParsingGetTenantsResponseFailure exception) { + logger.error("Failed to get tenants ", exception); + return buildAaiResponseForGetTenantsFailure(exception.getMessage()); } } @@ -389,13 +457,17 @@ public class AaiClient implements AaiClientInterface { } private AaiResponseWithRequestInfo processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class classType, boolean propagateExceptions) { + return processAaiResponse(responseWithRequestInfo, classType, VidObjectMapperType.CODEHAUS, propagateExceptions); + } + + private AaiResponseWithRequestInfo processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class classType, VidObjectMapperType omType, boolean propagateExceptions) { String responseBody = null; Integer responseHttpCode = null; try { Response response = responseWithRequestInfo.getResponse(); responseHttpCode = (response != null) ? response.getStatus() : null; responseBody = (response != null) ? response.readEntity(String.class) : null; - AaiResponse processedAaiResponse = processAaiResponse(response, classType, responseBody, VidObjectMapperType.CODEHAUS, propagateExceptions); + AaiResponse processedAaiResponse = processAaiResponse(response, classType, responseBody, omType, propagateExceptions); return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse, responseBody); } catch (Exception e) { @@ -408,17 +480,17 @@ public class AaiClient implements AaiClientInterface { return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS); } - private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType) { + private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType) { return processAaiResponse(resp, classType, responseBody, omType, false); } - private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) { - AaiResponse subscriberDataResponse; + private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) { + AaiResponse subscriberDataResponse; if (resp == null) { subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); + logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI"); } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "getSubscribers() resp=" + resp.getStatusInfo().toString()); if (resp.getStatus() != HttpStatus.SC_OK) { subscriberDataResponse = processFailureResponse(resp,responseBody); } else { @@ -429,7 +501,7 @@ public class AaiClient implements AaiClientInterface { } private AaiResponse processFailureResponse(Response resp, String responseBody) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI"); + logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI"); String rawData; if (responseBody != null) { rawData = responseBody; @@ -439,8 +511,8 @@ public class AaiClient implements AaiClientInterface { return new AaiResponse<>(null, rawData, resp.getStatus()); } - private AaiResponse processOkResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) { - AaiResponse subscriberDataResponse; + private AaiResponse processOkResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) { + AaiResponse subscriberDataResponse; String finalResponse = null; try { if (responseBody != null) { @@ -465,50 +537,59 @@ public class AaiClient implements AaiClientInterface { return subscriberDataResponse; } - private AaiResponse parseFasterXmlObject(Class classType, String finalResponse) throws IOException { - com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + private AaiResponse parseFasterXmlObject(Class classType, String finalResponse) throws IOException { return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK); } - private AaiResponse parseCodeHausObject(Class classType, String finalResponse) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); + private AaiResponse parseCodeHausObject(Class classType, String finalResponse) throws IOException { return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK); } + @Override public Response doAaiGet(String uri, boolean xml) { return doAaiGet(uri, xml, false).getResponse(); } public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) { + return doAaiGet(Unchecked.toURI(uri), xml, propagateExceptions); + } + + public ResponseWithRequestInfo doAaiGet(URI uri, boolean xml, boolean propagateExceptions) { String methodName = "doAaiGet"; - String transId = UUID.randomUUID().toString(); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); ResponseWithRequestInfo resp; try { - resp = restController.RestGet(fromAppId, transId, uri, xml, propagateExceptions); + resp = restController.RestGet(fromAppId, UUID.randomUUID().toString(), uri, xml, propagateExceptions); } catch (Exception e) { - if (propagateExceptions) { - throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e); - } else { - final Exception actual = - e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e; + resp = handleExceptionFromRestCall(propagateExceptions, methodName, e); + } + return resp; + } - final String message = - actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString(); + @NotNull + protected ResponseWithRequestInfo handleExceptionFromRestCall(boolean propagateExceptions, String methodName, Exception e) { + ResponseWithRequestInfo resp; + if (propagateExceptions) { + throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e); + } else { + final Exception actual = + e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e; - //ToDo: change parameter of requestUrl to real url from RestGet function - resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET); - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - } + final String message = + actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString(); + + //ToDo: change parameter of requestUrl to real url from doRest function + resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET); + logger.info(EELFLoggerDelegate.errorLogger, methodName + message); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + message); } return resp; } - private String parseForTenantsByServiceSubscription(String resp) { + private String parseForTenantsByServiceSubscription(String relatedToKey, String resp) { String tenantList = ""; try { @@ -516,7 +597,7 @@ public class AaiClient implements AaiClientInterface { JSONObject jsonObject = (JSONObject) jsonParser.parse(resp); - return parseServiceSubscriptionObjectForTenants(jsonObject); + return parseServiceSubscriptionObjectForTenants(relatedToKey, jsonObject); } catch (Exception ex) { logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex); } @@ -524,24 +605,26 @@ public class AaiClient implements AaiClientInterface { } protected Response doAaiPut(String uri, String payload, boolean xml) { + return doAaiPut(uri, payload, xml, false).getResponse(); + } + + protected ResponseWithRequestInfo doAaiPut(String uri, String payload, boolean xml, boolean propagateExceptions) { String methodName = "doAaiPut"; - String transId = UUID.randomUUID().toString(); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); - Response resp = null; + ResponseWithRequestInfo resp; try { - resp = restController.RestPut(fromAppId, uri, payload, xml); + resp = restController.RestPut(fromAppId, uri, payload, xml, propagateExceptions); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + resp = handleExceptionFromRestCall(propagateExceptions, methodName, e); } return resp; } - private String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) { + private String parseServiceSubscriptionObjectForTenants(String relatedToKey, JSONObject jsonObject) { JSONArray tenantArray = new JSONArray(); boolean bconvert = false; try { @@ -550,7 +633,7 @@ public class AaiClient implements AaiClientInterface { JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship"); for (Object innerObj : defaultIfNull(rShipArray, emptyList())) { if (innerObj != null) { - bconvert = parseTenant(tenantArray, bconvert, (JSONObject) innerObj); + bconvert = parseTenant(relatedToKey, tenantArray, bconvert, (JSONObject) innerObj); } } } @@ -565,9 +648,9 @@ public class AaiClient implements AaiClientInterface { } - private static boolean parseTenant(JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) { + private static boolean parseTenant(String relatedToKey, JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) { String relatedTo = checkForNull((String) inner1Obj.get("related-to")); - if (relatedTo.equalsIgnoreCase("tenant")) { + if (relatedTo.equalsIgnoreCase(relatedToKey)) { JSONObject tenantNewObj = new JSONObject(); String relatedLink = checkForNull((String) inner1Obj.get("related-link")); @@ -609,9 +692,7 @@ public class AaiClient implements AaiClientInterface { tenantNewObj.put("cloudOwner", rShipVal); } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) { tenantNewObj.put("cloudRegionID", rShipVal); - } - - if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) { + } else if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) { tenantNewObj.put("tenantID", rShipVal); } } @@ -639,7 +720,7 @@ public class AaiClient implements AaiClientInterface { responseWithRequestInfo.getHttpMethod(), (aaiResponse != null) ? aaiResponse.getHttpCode() : 0, responseWithRequestInfo.getRequestedUrl(), - StringUtils.substring(responseWithRequestInfo.getRawData(), 0, 500), + responseWithRequestInfo.getRawData(), isAvailable ? "OK" : "No subscriber received", duration ); @@ -648,16 +729,104 @@ public class AaiClient implements AaiClientInterface { } catch (ExceptionWithRequestInfo e) { long duration = System.currentTimeMillis() - startTime; return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false, - new HttpRequestMetadata( - e.getHttpMethod(), - defaultIfNull(e.getHttpCode(), 0), - e.getRequestedUrl(), - e.getRawData(), - Logging.exceptionToDescription(e.getCause()), duration)); + new HttpRequestMetadata(e, duration)); } catch (Exception e) { long duration = System.currentTimeMillis() - startTime; return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false, new ErrorMetadata(Logging.exceptionToDescription(e), duration)); } } + + @Override + public String getCloudOwnerByCloudRegionId(String cloudRegionId) { + return cacheProvider + .aaiClientCacheFor("getCloudOwnerByCloudRegionId", this::getCloudOwnerByCloudRegionIdNonCached) + .get(cloudRegionId); + } + + + @Override + public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) { + + if (StringUtils.isEmpty(vnfInstanceId)||StringUtils.isEmpty(vfModuleId)){ + throw new GenericUncheckedException("Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing."); + } + Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId +"/vf-modules/vf-module/"+ vfModuleId, false); + String responseAsString = parseForTenantsByServiceSubscription("vserver",resp.readEntity(String.class)); + if (responseAsString.equals("")){ + throw new GenericUncheckedException( String.format("A&AI has no homing data associated to vfModule '%s' of vnf '%s'", vfModuleId, vnfInstanceId)); + } + else { + AaiResponse aaiResponse = processAaiResponse(resp, GetTenantsResponse[].class, responseAsString); + return ((GetTenantsResponse[])aaiResponse.getT())[0]; + } + } + + @Override + public void resetCache(String cacheName) { + cacheProvider.resetCache(cacheName); + } + + String getCloudOwnerByCloudRegionIdNonCached(String cloudRegionId) { + String uri = "cloud-infrastructure/cloud-regions?cloud-region-id=" + encodePathSegment(cloudRegionId); + + final CloudRegion.Collection cloudRegionCollection = + typedAaiGet(Unchecked.toURI(uri), CloudRegion.Collection.class); + + return cloudRegionCollection + .getCloudRegions().stream() + .map(CloudRegion::getCloudOwner) + // from here we assure that the cloud owner is given, and not null + // and non-empty, and that if more than one cloud-owner is given - + // it is only a single value. + // exception is thrown if none or more than a single values are + // given. + .filter(StringUtils::isNotEmpty) + .distinct() + .reduce((a, b) -> { + // will be invoked only if distinct() leaves more than a single element + throw new GenericUncheckedException("Conflicting cloud-owner found for " + cloudRegionId + ": '" + a + "' / '" + b + "'"); + }) + .orElseThrow(() -> new GenericUncheckedException("No cloud-owner found for " + cloudRegionId)); + } + + private AaiResponse getTenantsByKey(String key) { + String[] args = CacheProvider.decompileKey(key); + String globalCustomerId = safeGetFromArray(args, 0); + String serviceType = safeGetFromArray(args, 1); + return getTenantsNonCached(globalCustomerId, serviceType); + } + + AaiResponse getTenantsNonCached(String globalCustomerId, String serviceType) { + String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType; + + Response resp = doAaiGet(url, false); + String responseAsString = parseForTenantsByServiceSubscription("tenant",resp.readEntity(String.class)); + if (StringUtils.isEmpty(responseAsString)){ + throw new ParsingGetTenantsResponseFailure(String.format("A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'", globalCustomerId, serviceType)); + } + else { + return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString); + } + } + + public static class ParsingGetTenantsResponseFailure extends GenericUncheckedException { + + public ParsingGetTenantsResponseFailure(String message) { + super(message); + } + } + + @NotNull + private AaiResponse buildAaiResponseForGetTenantsFailure(String errorText) { + return new AaiResponse<>(null, String.format("{\"statusText\":\"%s\"}", errorText), HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + private static String safeGetFromArray(String[] array, int i) { + if (i < 0 || i >= array.length) { + return null; + } else { + return array[i]; + } + } } \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java index 901591a8..bf97e599 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClientInterface.java @@ -1,24 +1,29 @@ package org.onap.vid.aai; -import org.codehaus.jackson.JsonNode; +import com.fasterxml.jackson.databind.JsonNode; import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; -import org.onap.vid.aai.model.AaiNodeQueryResponse; +import org.onap.vid.aai.model.CustomQuerySimpleResult; import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.model.Properties; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.model.SubscriberList; import org.onap.vid.model.probes.ExternalComponentStatus; import javax.ws.rs.core.Response; +import java.net.URI; import java.util.List; +import java.util.Map; /** * Created by Oren on 7/4/17. */ public interface AaiClientInterface { - AaiResponse searchNodeTypeByName(String name, ResourceType type); + boolean isNodeTypeExistsByName(String name, ResourceType type); + + T typedAaiGet(URI path, Class clz); AaiResponse getAllSubscribers(); @@ -34,15 +39,11 @@ public interface AaiClientInterface { AaiResponse getAllAicZones(); - AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId); - - AaiResponse getVNFData(); - AaiResponse getNetworkCollectionDetails(String serviceInstanceId); AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction); - Response getVNFData(String globalSubscriberId, String serviceType); + AaiResponse getVNFData(String globalSubscriberId, String serviceType); AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId); @@ -69,4 +70,14 @@ public interface AaiClientInterface { AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId); ExternalComponentStatus probeAaiGetAllSubscribers(); + + Response doAaiGet(String uri, boolean xml); + + String getCloudOwnerByCloudRegionId(String cloudRegionId); + + GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId); + + void resetCache(String cacheName); + + Map getCloudRegionAndTenantByVnfId(String vnfId); } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java index 08585206..479bd138 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiGetVnfResponse.java @@ -1,8 +1,7 @@ package org.onap.vid.aai; -import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.*; import com.google.common.base.MoreObjects; -import org.codehaus.jackson.annotate.*; import org.onap.vid.aai.model.VnfResult; import java.util.HashMap; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java index 6e25e271..fe62f029 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java @@ -20,26 +20,25 @@ package org.onap.vid.aai; -import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.ACCEPT; -import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.CONTENT_TYPE; -import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.FROM_APP_ID_HEADER; -import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.REQUEST_ID; -import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.TRANSACTION_ID_HEADER; - import io.joshworks.restclient.http.HttpResponse; +import io.joshworks.restclient.http.JsonNode; import io.vavr.collection.HashMap; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Collections; -import java.util.Map; -import javax.ws.rs.core.MediaType; +import org.apache.commons.lang3.StringUtils; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.aai.model.AaiNodeQueryResponse; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.aai.util.AAIProperties; import org.onap.vid.client.SyncRestClientInterface; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.SubscriberList; +import javax.ws.rs.core.MediaType; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collections; +import java.util.Map; + +import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.*; + public class AaiOverTLSClient implements AaiOverTLSClientInterface { private final AaiOverTLSPropertySupplier propertySupplier; @@ -64,9 +63,23 @@ public class AaiOverTLSClient implements AaiOverTLSClientInterface { } @Override - public HttpResponse searchNodeTypeByName(String name, ResourceType type) { - String uri = urlBase + String.format(URIS.NODE_TYPE_BY_NAME, type.getAaiFormat(), type.getNameFilter(), name); - return syncRestClient.get(uri, getRequestHeaders(), Collections.emptyMap(), AaiNodeQueryResponse.class); + public boolean isNodeTypeExistsByName(String name, ResourceType type) { + + if (StringUtils.isEmpty(name)) { + throw new GenericUncheckedException("Empty resource-name provided to isNodeTypeExistsByName; request is rejected as this will cause full resources listing"); + } + + String path = String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name} + "nodes/%s?%s=%s", + type.getAaiFormat(), + type.getNameFilter(), + name + ); + + String uri = urlBase + path; + final HttpResponse response = syncRestClient.get(uri, getRequestHeaders(), Collections.emptyMap()); + + return response.isSuccessful(); } @Override diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java index ad43746c..57ec519c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java @@ -22,7 +22,6 @@ package org.onap.vid.aai; import io.joshworks.restclient.http.HttpResponse; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.aai.model.AaiNodeQueryResponse; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.model.SubscriberList; @@ -44,7 +43,7 @@ public interface AaiOverTLSClientInterface { void setUseClientCert(boolean useClientCert); - HttpResponse searchNodeTypeByName(String name, ResourceType type); + boolean isNodeTypeExistsByName(String name, ResourceType type); HttpResponse getAllSubscribers(); diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java index c7a98a8c..a0a8a30d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseTranslator.java @@ -1,7 +1,7 @@ package org.onap.vid.aai; +import com.fasterxml.jackson.databind.JsonNode; import org.apache.commons.lang3.StringUtils; -import org.codehaus.jackson.JsonNode; import org.springframework.stereotype.Component; import java.util.Optional; @@ -26,7 +26,7 @@ public class AaiResponseTranslator { for (JsonNode resultNode : results) { final JsonNode nodeType = resultNode.path("node-type"); - if (nodeType.isTextual() && "cloud-region".equals(nodeType.getTextValue())) { + if (nodeType.isTextual() && "cloud-region".equals(nodeType.textValue())) { return getPortMirroringConfigData(payload, resultNode); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java index cd1f9044..a1806f0c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiResponseWithRequestInfo.java @@ -3,9 +3,8 @@ package org.onap.vid.aai; import org.springframework.http.HttpMethod; -import java.io.Serializable; -public class AaiResponseWithRequestInfo implements Serializable { +public class AaiResponseWithRequestInfo { private AaiResponse aaiResponse; private String requestedUrl; private String rawData; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java index dcca3ec4..388c3819 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ExceptionWithRequestInfo.java @@ -42,13 +42,13 @@ public class ExceptionWithRequestInfo extends RuntimeException { private static String toMessage(HttpMethod httpMethod, String requestedUrl, Throwable cause) { if (StringUtils.isEmpty(requestedUrl)) { - return cause.toString(); + return String.valueOf(cause); } else { return "" + "Exception while handling " + defaultIfNull(httpMethod, "request").toString() + " " + requestedUrl + - ": " + cause.toString(); + ": " + (cause == null ? "null" : cause.toString()); } } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java b/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java index 10ad4e96..4b4a496c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/OperationalEnvironment.java @@ -1,12 +1,9 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; -import org.onap.vid.aai.model.Relationship; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import org.onap.vid.aai.model.RelationshipList; -import java.util.List; - @JsonIgnoreProperties(ignoreUnknown = true) public class OperationalEnvironment { @@ -33,75 +30,75 @@ public class OperationalEnvironment { this.relationshipList = relationshipList; } - @JsonProperty("operational-environment-id") public String getOperationalEnvironmentId() { return operationalEnvironmentId; } - public void setOperationalEnvironmentId(String operationalEnvironmentId) { + @JsonProperty("operational-environment-id") + public void setJsonOperationalEnvironmentId(String operationalEnvironmentId) { this.operationalEnvironmentId = operationalEnvironmentId; } - @JsonProperty("operational-environment-name") public String getOperationalEnvironmentName() { return operationalEnvironmentName; } - public void setOperationalEnvironmentName(String operationalEnvironmentName) { + @JsonProperty("operational-environment-name") + public void setJsonOperationalEnvironmentName(String operationalEnvironmentName) { this.operationalEnvironmentName = operationalEnvironmentName; } - @JsonProperty("operational-environment-type") public String getOperationalEnvironmentType() { return operationalEnvironmentType; } - public void setOperationalEnvironmentType(String operationalEnvironmentType) { + @JsonProperty("operational-environment-type") + public void setJsonOperationalEnvironmentType(String operationalEnvironmentType) { this.operationalEnvironmentType = operationalEnvironmentType; } - @JsonProperty("operational-environment-status") public String getOperationalEnvironmentStatus() { return operationalEnvironmentStatus; } - public void setOperationalEnvironmentStatus(String operationalEnvironmentStatus) { + @JsonProperty("operational-environment-status") + public void setJsonOperationalEnvironmentStatus(String operationalEnvironmentStatus) { this.operationalEnvironmentStatus = operationalEnvironmentStatus; } - @JsonProperty("tenant-context") public String getTenantContext() { return tenantContext; } - public void setTenantContext(String tenantContext) { + @JsonProperty("tenant-context") + public void setJsonTenantContext(String tenantContext) { this.tenantContext = tenantContext; } - @JsonProperty("workload-context") public String getWorkloadContext() { return workloadContext; } - public void setWorkloadContext(String workloadContext) { + @JsonProperty("workload-context") + public void setJsonWorkloadContext(String workloadContext) { this.workloadContext = workloadContext; } - @JsonProperty("resource-version") public String getResourceVersion() { return resourceVersion; } - public void setResourceVersion(String resourceVersion) { + @JsonProperty("resource-version") + public void setJsonResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } - @JsonProperty("relationship-list") public RelationshipList getRelationshipList() { return relationshipList; } - public void setRelationshipList(RelationshipList relationshipList) { + @JsonProperty("relationship-list") + public void setJsonRelationshipList(RelationshipList relationshipList) { this.relationshipList = relationshipList; } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java b/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java index 28b6f542..000628d8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/PombaClientImpl.java @@ -1,21 +1,15 @@ package org.onap.vid.aai; import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.vid.model.PombaInstance.PombaRequest; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.model.PombaInstance.PombaRequest; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.ServletContext; -import javax.ws.rs.core.Response; -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; public class PombaClientImpl implements PombaClientInterface { - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); protected String fromAppId = "VidAaiController"; EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class); @@ -29,22 +23,15 @@ public class PombaClientImpl implements PombaClientInterface { @Override public void verify(PombaRequest request) { String methodName = "doAaiPost"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); String uri = SystemProperties.getProperty("pomba.server.url"); try { - Response response = pombaRestInterface.RestPost(fromAppId, uri, new ObjectMapper().writeValueAsString(request)); + pombaRestInterface.RestPost(fromAppId, uri, new ObjectMapper().writeValueAsString(request)); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString()); } } - - - private File getCertificatesFile() { - if (servletContext != null) - return new File(servletContext.getRealPath("/WEB-INF/cert/")); - return null; - } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java index c4bc852f..63762373 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/PombaRestInterface.java @@ -42,11 +42,12 @@ public class PombaRestInterface extends AAIRestInterface { private Client client = null; - private void initRestClient() + @Override + protected void initRestClient() { if (client == null) { try { - client = httpsAuthClientFactory.getClient(HttpClientMode.UNSECURE); + client = httpsAuthClientFactory.getClient(HttpClientMode.WITH_KEYSTORE); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, "Exception in REST call to DB in initRestClient" + e.toString()); @@ -78,6 +79,7 @@ public class PombaRestInterface extends AAIRestInterface { } else { logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, cres)); } + return cres; } catch (Exception e) { logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstance.java index 26f4a21e..59f36733 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstance.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstance.java @@ -1,7 +1,7 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceInstance { @@ -11,16 +11,16 @@ public class ServiceInstance { @JsonProperty("service-instance-name") public String serviceInstanceName; - + @JsonProperty("persona-model-id") public String personaModelId; - + @JsonProperty("persona-model-version") public String personaModelVersion; - + @JsonProperty("resource-version") public String resourceVersion; - + @JsonProperty("orchestration-status") public String orchestrationStatus; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstances.java b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstances.java index c92a47a3..fb5f18b6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstances.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstances.java @@ -1,7 +1,7 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstancesSearchResults.java b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstancesSearchResults.java index b32a83a1..79d90986 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstancesSearchResults.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceInstancesSearchResults.java @@ -1,10 +1,9 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import org.onap.vid.model.ServiceInstanceSearchResult; -import java.util.ArrayList; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscription.java b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscription.java index 5dc9d526..80578014 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscription.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscription.java @@ -1,7 +1,7 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class ServiceSubscription { diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscriptions.java b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscriptions.java index 686dc7d6..8938f2cd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscriptions.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/ServiceSubscriptions.java @@ -1,7 +1,7 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/Services.java b/vid-app-common/src/main/java/org/onap/vid/aai/Services.java index fe70de5a..2a7fc407 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/Services.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/Services.java @@ -1,7 +1,7 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Services { @@ -16,7 +16,7 @@ public class Services { @JsonProperty("resource-version") public String resourceVersion; - + @JsonProperty("service-subscriptions") public ServiceSubscriptions serviceSubscriptions; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/SubscriberWithFilter.java b/vid-app-common/src/main/java/org/onap/vid/aai/SubscriberWithFilter.java index aaaa1445..a91e33e5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/SubscriberWithFilter.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/SubscriberWithFilter.java @@ -1,6 +1,6 @@ package org.onap.vid.aai; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonProperty; import org.onap.vid.model.Subscriber; /** diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/AicZones.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/AicZones.java index c30aaeb8..f91797a7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/AicZones.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/AicZones.java @@ -1,8 +1,8 @@ package org.onap.vid.aai.model.AaiGetAicZone; -import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; -import org.codehaus.jackson.annotate.JsonProperty; +import java.util.List; public class AicZones { @JsonProperty("zone") diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/Zone.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/Zone.java index 89400f20..13e26844 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/Zone.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetAicZone/Zone.java @@ -1,13 +1,13 @@ package org.onap.vid.aai.model.AaiGetAicZone; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Zone { @JsonProperty("zone-id") public String zoneId; - + @JsonProperty("zone-name") public String zoneName; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/CloudRegion.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/CloudRegion.java new file mode 100644 index 00000000..38dd2b12 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/CloudRegion.java @@ -0,0 +1,55 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.apache.commons.lang3.ObjectUtils; + +import java.util.List; + +import static java.util.Collections.emptyList; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class CloudRegion { + + private final String cloudOwner; + private final String cloudRegionId; + + public CloudRegion( + @JsonProperty("cloud-owner") String cloudOwner, + @JsonProperty("cloud-region-id") String cloudRegionId + ) { + this.cloudOwner = cloudOwner; + this.cloudRegionId = cloudRegionId; + } + + public String getCloudOwner() { + return cloudOwner; + } + + public String getCloudRegionId() { + return cloudRegionId; + } + + /* + This will handle container like: + { + "cloud-region": [{ + "cloud-owner": "alfi", + "cloud-region-id": "foo", + . . . + }, { + "cloud-owner": "alba", + "cloud-region-id": "bar", + */ + public static class Collection { + private final List cloudRegions; + + public Collection(@JsonProperty("cloud-region") List cloudRegions) { + this.cloudRegions = ObjectUtils.defaultIfNull(cloudRegions, emptyList()); + } + + public List getCloudRegions() { + return cloudRegions; + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java index 29450a8f..41b720a4 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Network.java @@ -2,9 +2,10 @@ package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.aai.model.interfaces.AaiModelWithRelationships; @JsonIgnoreProperties(ignoreUnknown = true) -public class Network { +public class Network implements AaiModelWithRelationships { @JsonProperty("network-id") private String networkId; @JsonProperty("network-name") @@ -19,6 +20,8 @@ public class Network { private Boolean isBoundToVpn; @JsonProperty("resource-version") private String resourceVersion; + @JsonProperty("orchestration-status") + private String orchestrationStatus; @JsonProperty("is-provider-network") private Boolean isProviderNetwork; @JsonProperty("is-shared-network") @@ -99,6 +102,16 @@ public class Network { this.resourceVersion = resourceVersion; } + @JsonProperty("orchestration-status") + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + @JsonProperty("orchestration-status") + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + @JsonProperty("is-provider-network") public Boolean getIsProviderNetwork() { return isProviderNetwork; @@ -129,6 +142,7 @@ public class Network { this.isExternalNetwork = isExternalNetwork; } + @Override @JsonProperty("relationship-list") public RelationshipList getRelationshipList() { return relationshipList; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java index c366402e..49b8536c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/ServiceInstance.java @@ -1,17 +1,51 @@ package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.aai.model.interfaces.AaiModelWithRelationships; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; @JsonIgnoreProperties(ignoreUnknown = true) -public class ServiceInstance { +public class ServiceInstance implements AaiModelWithRelationships { + + private final String serviceInstanceId; + private final String serviceInstanceName; + private final String resourceVersion; + private final RelationshipList relationshipList; + + public ServiceInstance( + @JsonProperty("service-instance-id") String serviceInstanceId, + @JsonProperty("service-instance-name") String serviceInstanceName, + @JsonProperty("resource-version") String resourceVersion, + @JsonProperty("relationship-list") RelationshipList relationshipList + ) { + this.serviceInstanceId = serviceInstanceId; + this.serviceInstanceName = serviceInstanceName; + this.resourceVersion = resourceVersion; + this.relationshipList = relationshipList; + } @JsonProperty("service-instance-id") - public String serviceInstanceId; + public String getServiceInstanceId() { + return serviceInstanceId; + } + + @JsonProperty("service-instance-name") + @JsonInclude(NON_NULL) + public String getServiceInstanceName() { + return serviceInstanceName; + } @JsonProperty("resource-version") - public String resourceVersion; + public String getResourceVersion() { + return resourceVersion; + } + @Override @JsonProperty("relationship-list") - public RelationshipList relationshipList; + public RelationshipList getRelationshipList() { + return relationshipList; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vlan.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vlan.java new file mode 100644 index 00000000..a1846485 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vlan.java @@ -0,0 +1,41 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.aai.model.interfaces.AaiModelWithRelationships; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Vlan implements AaiModelWithRelationships { + + public Vlan( + @JsonProperty("vlan-interface") String vlanInterface, + @JsonProperty("vlan-id-inner") String vlanIdInner, + @JsonProperty("relationship-list") RelationshipList relationshipList) { + this.vlanInterface = vlanInterface; + this.vlanIdInner = vlanIdInner; + this.relationshipList = relationshipList; + } + + @JsonProperty("vlan-interface") + private final String vlanInterface; + + @JsonProperty("vlan-id-inner") + private final String vlanIdInner; + + @JsonProperty("relationship-list") + public final RelationshipList relationshipList; + + public String getVlanInterface() { + return vlanInterface; + } + + public String getVlanIdInner() { + return vlanIdInner; + } + + @Override + public RelationshipList getRelationshipList() { + return relationshipList; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vnf.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vnf.java new file mode 100644 index 00000000..5dc6e4d3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/Vnf.java @@ -0,0 +1,84 @@ +package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.aai.model.interfaces.AaiModelWithRelationships; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Vnf implements AaiModelWithRelationships { + @JsonProperty("vnf-id") + private String vnfId; + @JsonProperty("vnf-name") + private String vnfName; + @JsonProperty("vnf-type") + private String vnfType; + @JsonProperty("resource-version") + private String resourceVersion; + @JsonProperty("orchestration-status") + private String orchestrationStatus; + @JsonProperty("relationship-list") + private RelationshipList relationshipList; + + + @JsonProperty("vnf-id") + public String getVnfId() { + return vnfId; + } + + @JsonProperty("vnf-id") + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + @JsonProperty("vnf-name") + public String getVnfName() { + return vnfName; + } + + @JsonProperty("vnf-name") + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + @JsonProperty("vnf-type") + public String getVnfType() { + return vnfType; + } + + @JsonProperty("vnf-type") + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + @JsonProperty("resource-version") + public String getResourceVersion() { + return resourceVersion; + } + + @JsonProperty("resource-version") + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + @JsonProperty("orchestration-status") + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + @JsonProperty("orchestration-status") + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + @Override + @JsonProperty("relationship-list") + public RelationshipList getRelationshipList() { + return relationshipList; + } + + @JsonProperty("relationship-list") + public void setRelationshipList(RelationshipList relationshipList) { + this.relationshipList = relationshipList; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java index 1f31cfaa..254d5edc 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetOperationalEnvironments/OperationalEnvironmentList.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model.AaiGetOperationalEnvironments; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.onap.vid.aai.OperationalEnvironment; import java.util.List; @@ -9,12 +9,11 @@ import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class OperationalEnvironmentList { - @JsonProperty("operational-environment") public List getOperationalEnvironment() { return operationalEnvironment; } - @JsonProperty("operational-environment") + @JsonAlias("operational-environment") public void setOperationalEnvironment(List operationalEnvironment) { this.operationalEnvironment = operationalEnvironment; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfResponse.java index fa9fe935..93c12c8e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfResponse.java @@ -1,12 +1,7 @@ package org.onap.vid.aai.model; -import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.*; import com.google.common.base.MoreObjects; -import org.codehaus.jackson.annotate.JsonAnyGetter; -import org.codehaus.jackson.annotate.JsonAnySetter; -import org.codehaus.jackson.annotate.JsonIgnore; -import org.codehaus.jackson.annotate.JsonProperty; -import org.codehaus.jackson.annotate.JsonPropertyOrder; import java.util.HashMap; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfs/Pnf.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfs/Pnf.java index 00a731a7..d359474d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfs/Pnf.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPnfs/Pnf.java @@ -1,31 +1,25 @@ package org.onap.vid.aai.model.AaiGetPnfs; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.onap.vid.aai.model.AaiRelationResponse; @JsonIgnoreProperties(ignoreUnknown = true) public class Pnf extends AaiRelationResponse { - @JsonProperty("pnf-name") - public String pnfName; - @JsonProperty("pnf-name2") - public String pnfName2; - @JsonProperty("pnf-name2-source") - public String pnfName2Source; - @JsonProperty("pnf-id") - public String pnfId; - @JsonProperty("equip-type") - public String equipType; - @JsonProperty("equip-vendor") - public String equipVendor; - @JsonProperty("equip-model") - public String equipModel; + private String pnfName; + private String pnfName2; + private String pnfName2Source; + private String pnfId; + private String equipType; + private String equipVendor; + private String equipModel; public String getPnfName() { return pnfName; } + @JsonAlias("pnf-name") public void setPnfName(String pnfName) { this.pnfName = pnfName; } @@ -34,6 +28,7 @@ public class Pnf extends AaiRelationResponse { return equipType; } + @JsonAlias("equip-type") public void setEquipType(String equipType) { this.equipType = equipType; } @@ -42,6 +37,7 @@ public class Pnf extends AaiRelationResponse { return equipVendor; } + @JsonAlias("equip-vendor") public void setEquipVendor(String equipVendor) { this.equipVendor = equipVendor; } @@ -50,6 +46,7 @@ public class Pnf extends AaiRelationResponse { return pnfName2; } + @JsonAlias("pnf-name2") public void setPnfName2(String pnfName2) { this.pnfName2 = pnfName2; } @@ -58,6 +55,7 @@ public class Pnf extends AaiRelationResponse { return pnfId; } + @JsonAlias("pnf-id") public void setPnfId(String pnfId) { this.pnfId = pnfId; } @@ -66,12 +64,14 @@ public class Pnf extends AaiRelationResponse { return equipModel; } + @JsonAlias("equip-model") public void setEquipModel(String equipModel) { this.equipModel = equipModel; } public String getPnfName2Source() { return pnfName2Source; } + @JsonAlias("pnf-name2-source") public void setPnfName2Source(String pnfName2Source) { this.pnfName2Source = pnfName2Source; } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java index 47a57daf..b629d904 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetPortMirroringSourcePorts.java @@ -1,6 +1,6 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/GetServicesAAIRespone.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/GetServicesAAIRespone.java index d3dd7d26..d5858de2 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/GetServicesAAIRespone.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/GetServicesAAIRespone.java @@ -1,7 +1,6 @@ package org.onap.vid.aai.model.AaiGetServicesRequestModel; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/Service.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/Service.java index 367287e1..36b5a514 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/Service.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetServicesRequestModel/Service.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model.AaiGetServicesRequestModel; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Oren on 7/17/17. diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetTenatns/GetTenantsResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetTenatns/GetTenantsResponse.java index 1d0e8495..c799c8fa 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetTenatns/GetTenantsResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetTenatns/GetTenantsResponse.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model.AaiGetTenatns; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Oren on 7/18/17. @@ -9,26 +9,29 @@ import org.codehaus.jackson.annotate.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class GetTenantsResponse { - @JsonProperty("cloudRegionID") - public String cloudRegionId; + public String cloudRegionID; - @JsonProperty("cloudOwner") public String cloudOwner; - - @JsonProperty("tenantName") + public String tenantName; - @JsonProperty("tenantID") public String tenantID; - @JsonProperty("is-permitted") public boolean isPermitted; + @JsonProperty("is-permitted") + public boolean getJsonIsPermitted() { + // this is a special case to *duplicate* the permission field + // as it might be that both -- camelCase and hyphen faces -- + // are in use + return isPermitted; + } + public GetTenantsResponse() { } public GetTenantsResponse(String cloudRegionId, String cloudOwner, String tenantName, String tenantID, boolean isPermitted) { - this.cloudRegionId = cloudRegionId; + this.cloudRegionID = cloudRegionId; this.cloudOwner = cloudOwner; this.tenantName = tenantName; this.tenantID = tenantID; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiRelationResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiRelationResponse.java index 7bc2e7a2..981f8565 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiRelationResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiRelationResponse.java @@ -1,9 +1,8 @@ package org.onap.vid.aai.model; - -import org.codehaus.jackson.annotate.JsonIgnore; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.HashMap; import java.util.Map; @@ -13,30 +12,27 @@ import java.util.Map; */ public class AaiRelationResponse { - @JsonProperty("resource-version") private String resourceVersion; - @JsonProperty("relationship-list") private RelationshipList relationshipList; + @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); - @JsonProperty("resource-version") public String getResourceVersion() { return resourceVersion; } - @JsonProperty("resource-version") + @JsonAlias("resource-version") public void setResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } - @JsonProperty("relationship-list") public RelationshipList getRelationshipList() { return relationshipList; } - @JsonProperty("relationship-list") + @JsonAlias("relationship-list") public void setRelationshipList(RelationshipList relationshipList) { this.relationshipList = relationshipList; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/CustomQuerySimpleResult.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/CustomQuerySimpleResult.java new file mode 100644 index 00000000..4f91b756 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/CustomQuerySimpleResult.java @@ -0,0 +1,18 @@ +package org.onap.vid.aai.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class CustomQuerySimpleResult { + + private final List results; + + public CustomQuerySimpleResult(@JsonProperty("results") List results) { + this.results = results; + } + + public List getResults() { + return results; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/GetServiceModelsByDistributionStatusResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/GetServiceModelsByDistributionStatusResponse.java index 5a6924dc..c17f930c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/GetServiceModelsByDistributionStatusResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/GetServiceModelsByDistributionStatusResponse.java @@ -1,8 +1,8 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/LogicalLinkResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/LogicalLinkResponse.java index 6625957e..4d815bc3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/LogicalLinkResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/LogicalLinkResponse.java @@ -1,31 +1,26 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; public class LogicalLinkResponse { - @JsonProperty("link-name") public String linkName; - @JsonProperty("in-maint") public Boolean inMaint; - @JsonProperty("link-type") public String linkType; - @JsonProperty("resource-version") public String resourceVersion; - @JsonProperty("purpose") public String purpose; - @JsonProperty("relationship-list") public RelationshipList relationshipList; public String getLinkName() { return linkName; } + @JsonAlias("link-name") public void setLinkName(String linkName) { this.linkName = linkName; } @@ -34,6 +29,7 @@ public class LogicalLinkResponse { return inMaint; } + @JsonAlias("in-maint") public void setInMaint(Boolean inMaint) { this.inMaint = inMaint; } @@ -42,6 +38,7 @@ public class LogicalLinkResponse { return linkType; } + @JsonAlias("link-type") public void setLinkType(String linkType) { this.linkType = linkType; } @@ -50,6 +47,7 @@ public class LogicalLinkResponse { return resourceVersion; } + @JsonAlias("resource-version") public void setResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } @@ -58,6 +56,7 @@ public class LogicalLinkResponse { return purpose; } + @JsonAlias("purpose") public void setPurpose(String purpose) { this.purpose = purpose; } @@ -66,6 +65,7 @@ public class LogicalLinkResponse { return relationshipList; } + @JsonAlias("relationship-list") public void setRelationshipList(RelationshipList relationshipList) { this.relationshipList = relationshipList; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Model.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Model.java index 5f422f68..7a771e4e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Model.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Model.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by moriya1 on 15/10/2017. @@ -9,51 +9,43 @@ import org.codehaus.jackson.annotate.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Model { - @JsonProperty("model-invariant-id") private String modelInvariantId; - @JsonProperty("model-type") private String modelType; - @JsonProperty("resource-version") private String resourceVersion; - @JsonProperty("model-vers") private ModelVers modelVers; - @JsonProperty("model-invariant-id") public String getModelInvariantId() { return modelInvariantId; } - @JsonProperty("model-invariant-id") + @JsonAlias("model-invariant-id") public void setModelInvariantId(String modelInvariantId) { this.modelInvariantId = modelInvariantId; } - @JsonProperty("model-type") public String getModelType() { return modelType; } - @JsonProperty("model-type") + @JsonAlias("model-type") public void setModelType(String modelType) { this.modelType = modelType; } - @JsonProperty("resource-version") public String getResourceVersion() { return resourceVersion; } - @JsonProperty("resource-version") + @JsonAlias("resource-version") public void setResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } - @JsonProperty("model-vers") public ModelVers getModelVers() { return modelVers; } - @JsonProperty("model-vers") + @JsonAlias("model-vers") public void setModelVers(ModelVers modelVers) { this.modelVers = modelVers; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVer.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVer.java index f02bbacf..6908feb7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVer.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVer.java @@ -1,82 +1,70 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class ModelVer { - @JsonProperty("model-version-id") private String modelVersionId; - @JsonProperty("model-name") private String modelName; - @JsonProperty("model-version") private String modelVersion; - @JsonProperty("distribution-status") private String distributionStatus; - @JsonProperty("resource-version") private String resourceVersion; - @JsonProperty("model-description") private String modelDescription; - @JsonProperty("model-version-id") public String getModelVersionId() { return modelVersionId; } - @JsonProperty("model-version-id") + @JsonAlias("model-version-id") public void setModelVersionId(String modelVersionId) { this.modelVersionId = modelVersionId; } - @JsonProperty("model-name") public String getModelName() { return modelName; } - @JsonProperty("model-name") + @JsonAlias("model-name") public void setModelName(String modelName) { this.modelName = modelName; } - @JsonProperty("model-version") public String getModelVersion() { return modelVersion; } - @JsonProperty("model-version") + @JsonAlias("model-version") public void setModelVersion(String modelVersion) { this.modelVersion = modelVersion; } - @JsonProperty("distribution-status") public String getDistributionStatus() { return distributionStatus; } - @JsonProperty("distribution-status") + @JsonAlias("distribution-status") public void setDistributionStatus(String distributionStatus) { this.distributionStatus = distributionStatus; } - @JsonProperty("resource-version") public String getResourceVersion() { return resourceVersion; } - @JsonProperty("resource-version") + @JsonAlias("resource-version") public void setResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } - @JsonProperty("model-description") public String getModelDescription() { return modelDescription; } - @JsonProperty("model-description") + @JsonAlias("model-description") public void setModelDescription(String modelDescription) { this.modelDescription = modelDescription; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVers.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVers.java index f352158f..eed40fc0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVers.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ModelVers.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; @@ -11,15 +11,13 @@ import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class ModelVers { - @JsonProperty("model-ver") private List modelVer; - @JsonProperty("model-ver") public List getModelVer() { return modelVer; } - @JsonProperty("model-ver") + @JsonAlias("model-ver") public void setModelVer(List modelVer) { this.modelVer = modelVer; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntity.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntity.java index edf5242d..366a1088 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntity.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntity.java @@ -1,33 +1,29 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; /** * Created by moriya1 on 08/10/2017. */ public class OwningEntity extends AaiRelationResponse { - @JsonProperty("owning-entity-id") private String owningEntityId; - @JsonProperty("owning-entity-name") private String owningEntityName; - @JsonProperty("owning-entity-id") public String getOwningEntityId() { return owningEntityId; } - @JsonProperty("owning-entity-id") + @JsonAlias("owning-entity-id") public void setOwningEntityId(String owningEntityId) { this.owningEntityId = owningEntityId; } - @JsonProperty("owning-entity-name") public String getOwningEntityName() { return owningEntityName; } - @JsonProperty("owning-entity-name") + @JsonAlias("owning-entity-name") public void setOwningEntityName(String owningEntityName) { this.owningEntityName = owningEntityName; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntityResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntityResponse.java index 3a571ea1..1d9bd839 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntityResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/OwningEntityResponse.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; @@ -10,17 +10,15 @@ import java.util.List; */ public class OwningEntityResponse { - @JsonProperty("owning-entity") private List owningEntity; - @JsonProperty("owning-entity") public List getOwningEntity() { return owningEntity; } @JsonProperty("owning-entity") - public void setOwningEntity(List owningEntity) { + public void setJsonOwningEntity(List owningEntity) { this.owningEntity = owningEntity; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Permissions.kt b/vid-app-common/src/main/java/org/onap/vid/aai/model/Permissions.kt new file mode 100644 index 00000000..472da8db --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Permissions.kt @@ -0,0 +1,6 @@ +package org.onap.vid.aai.model + +import com.fasterxml.jackson.annotation.JsonProperty + + +data class Permissions(@get:JsonProperty("isEditPermitted") val isEditPermitted: Boolean) \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfProperties.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfProperties.java index 3481d263..032714b9 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfProperties.java @@ -1,12 +1,6 @@ package org.onap.vid.aai.model; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.*; import java.util.HashMap; import java.util.Map; @@ -23,20 +17,15 @@ import java.util.Map; }) public class PnfProperties { - @JsonProperty("pnf-name") public String pnfName; - @JsonProperty("equip-type") public String equipType; - @JsonProperty("equip-vendor") public String equipVendor; - @JsonProperty("equip-model") public String equipModel; - @JsonProperty("in-maint") public Boolean inMaint; - @JsonProperty("resource-version") public String resourceVersion; + @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonAnyGetter public Map getAdditionalProperties() { @@ -48,4 +37,34 @@ public class PnfProperties { this.additionalProperties.put(name, value); } + @JsonProperty("pnf-name") + public void setJsonPnfName(String pnfName) { + this.pnfName = pnfName; + } + + @JsonProperty("equip-type") + public void setJsonEquipType(String equipType) { + this.equipType = equipType; + } + + @JsonProperty("equip-vendor") + public void setJsonEquipVendor(String equipVendor) { + this.equipVendor = equipVendor; + } + + @JsonProperty("equip-model") + public void setJsonEquipModel(String equipModel) { + this.equipModel = equipModel; + } + + @JsonProperty("in-maint") + public void setJsonInMaint(Boolean inMaint) { + this.inMaint = inMaint; + } + + @JsonProperty("resource-version") + public void setJsonResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfResult.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfResult.java index a727d8f3..a2c3d3be 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfResult.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/PnfResult.java @@ -1,12 +1,6 @@ package org.onap.vid.aai.model; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.codehaus.jackson.annotate.JsonProperty; -import org.onap.vid.RelatedTo; +import com.fasterxml.jackson.annotation.*; import java.util.HashMap; import java.util.List; @@ -23,19 +17,39 @@ import java.util.Map; }) public class PnfResult { - @JsonProperty("id") public String id; - @JsonProperty("node-type") public String nodeType; - @JsonProperty("url") public String url; - @JsonProperty("properties") public PnfProperties properties; - @JsonProperty("related-to") public List relatedTo; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); + + @JsonProperty("id") + public void setJsonId(String id) { + this.id = id; + } + + @JsonProperty("node-type") + public void setJsonNodeType(String nodeType) { + this.nodeType = nodeType; + } + + @JsonProperty("url") + public void setJsonUrl(String url) { + this.url = url; + } + + @JsonProperty("properties") + public void setJsonProperties(PnfProperties properties) { + this.properties = properties; + } + + @JsonProperty("related-to") + public void setJsonRelatedTo(List relatedTo) { + this.relatedTo = relatedTo; + } @JsonAnyGetter public Map getAdditionalProperties() { diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java index f8980457..ae74af6f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/PortDetailsTranslator.java @@ -3,10 +3,7 @@ package org.onap.vid.aai.model; import com.google.common.collect.ImmutableList; import org.onap.vid.aai.AaiResponse; -import org.onap.vid.properties.Features; -import org.togglz.core.manager.FeatureManager; -import javax.inject.Inject; import java.util.LinkedList; import java.util.List; import java.util.Optional; @@ -15,10 +12,7 @@ import java.util.stream.Collectors; public class PortDetailsTranslator { - @Inject - FeatureManager featureManager; - - public static class PortDetailsOk extends PortDetails { + public static class PortDetailsOk implements PortDetails { private final String interfaceId; private final String interfaceName; @@ -43,16 +37,16 @@ public class PortDetailsTranslator { } } - public abstract static class PortDetails { + public interface PortDetails { } - public static class PortDetailsError extends PortDetails { + public static class PortDetailsError implements PortDetails { private final String errorDescription; private final String rawAaiResponse; - public PortDetailsError(String errorDescription, String rawAaiResponse){ - this.errorDescription = errorDescription; - this.rawAaiResponse = rawAaiResponse; + public PortDetailsError(String errorDescription, String rawAaiResponse) { + this.errorDescription = errorDescription; + this.rawAaiResponse = rawAaiResponse; } public String getErrorDescription() { @@ -64,13 +58,13 @@ public class PortDetailsTranslator { } } - public static PortDetails extractPortDetailsFromProperties(Properties properties, String rawPayload){ + public static PortDetails extractPortDetailsFromProperties(Properties properties, String rawPayload) { List errorDescriptions = new LinkedList<>(); describeIfNullOrEmpty("interface-id", properties.getInterfaceId(), errorDescriptions); describeIfNullOrEmpty("interface-name", properties.getInterfaceName(), errorDescriptions); describeIfNullOrEmpty("is-port-mirrored", properties.getIsPortMirrored(), errorDescriptions); - if(errorDescriptions.isEmpty()){ + if (errorDescriptions.isEmpty()) { return new PortDetailsOk(properties.getInterfaceId(), properties.getInterfaceName(), properties.getIsPortMirrored()); } else { return new PortDetailsError(String.join(" ", errorDescriptions), rawPayload); @@ -90,14 +84,14 @@ public class PortDetailsTranslator { final String errorMessage = aaiResponse.getErrorMessage(); return Optional.of(ImmutableList.of(new PortDetailsError( "Got " + aaiResponse.getHttpCode() + " from aai", - errorMessage != null ? errorMessage.toString() : rawPayload) + errorMessage != null ? errorMessage : rawPayload) )); } else { return Optional.empty(); } } - public List extractPortDetailsInternal(AaiGetPortMirroringSourcePorts aaiGetPortsResponse, String rawPayload){ + public List extractPortDetailsInternal(CustomQuerySimpleResult aaiGetPortsResponse, String rawPayload) { List filteredResult = getFilteredPortList(aaiGetPortsResponse.getResults()); return filteredResult.stream() @@ -107,7 +101,7 @@ public class PortDetailsTranslator { } public List getFilteredPortList(List results) { - String LINTERFACE = "l-interface"; + final String LINTERFACE = "l-interface"; final Predicate ifIsPort = (SimpleResult r) -> LINTERFACE.equals(r.getNodeType()); Predicate ifIsSource = getIsSourcePredicate(); @@ -119,18 +113,12 @@ public class PortDetailsTranslator { } private Predicate getIsSourcePredicate() { - boolean FLAG_ADVANCED_PORTS_FILTER = featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER); - - if (FLAG_ADVANCED_PORTS_FILTER) { - String PORT_LABEL = "org.onap.relationships.inventory.Source"; - return (SimpleResult r) -> r.getRelatedTo().stream() - .anyMatch(relatedTo -> PORT_LABEL.equalsIgnoreCase(relatedTo.getRelationshipLabel())); - } else { - return (SimpleResult r) -> true; - } + final String PORT_LABEL = "org.onap.relationships.inventory.Source"; + return (SimpleResult r) -> r.getRelatedTo().stream() + .anyMatch(relatedTo -> PORT_LABEL.equalsIgnoreCase(relatedTo.getRelationshipLabel())); } - public List extractPortDetails(AaiResponse aaiGetPortsResponse, String rawPayload){ + public List extractPortDetails(AaiResponse aaiGetPortsResponse, String rawPayload) { return extractErrorResponseIfHttpError(aaiGetPortsResponse, rawPayload).orElseGet(() -> extractPortDetailsInternal(aaiGetPortsResponse.getT(), rawPayload)); } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Project.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Project.java index 5931bb97..4e9f945c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Project.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Project.java @@ -1,20 +1,18 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; /** * Created by moriya1 on 08/10/2017. */ public class Project extends AaiRelationResponse { - @JsonProperty("project-name") private String projectName; - @JsonProperty("project-name") public String getProjectName() { return projectName; } - @JsonProperty("project-name") + @JsonAlias("project-name") public void setProjectName(String projectName) { this.projectName = projectName; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ProjectResponse.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ProjectResponse.java index 0ca35b0a..125e1061 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ProjectResponse.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ProjectResponse.java @@ -1,8 +1,6 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; - import java.util.List; /** @@ -10,16 +8,13 @@ import java.util.List; */ public class ProjectResponse { - @JsonProperty("project") private List project; - @JsonProperty("project") public List getProject() { return project; } - @JsonProperty("project") public void setProject(List project) { this.project = project; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java index 6fecbed5..dec632ea 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Properties.java @@ -1,23 +1,38 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.HashMap; +import java.util.Map; -@JsonIgnoreProperties(ignoreUnknown = true) public class Properties { - private final String interfaceName; - private final String interfaceId; - private final Boolean isPortMirrored; + //properties for l-interface node-type + @JsonProperty("interface-name") + private String interfaceName; - public Properties( - @JsonProperty("interface-name") String interfaceName, - @JsonProperty("interface-id") String interfaceId, - @JsonProperty("is-port-mirrored") Boolean isPortMirrored) { - this.interfaceName = interfaceName; - this.interfaceId = interfaceId; - this.isPortMirrored = isPortMirrored; - } + @JsonProperty("interface-id") + private String interfaceId; + + @JsonProperty("is-port-mirrored") + private Boolean isPortMirrored; + + //properties for tenant node-type + @JsonProperty("tenant-id") + private String tenantId; + + @JsonProperty("tenant-name") + private String tenantName; + + //properties for cloud-region node-type + @JsonProperty("cloud-region-id") + private String cloudRegionId; + + private Map additionalProperties = new HashMap<>(); + + public Properties(){} public String getInterfaceName() { return interfaceName; @@ -30,4 +45,38 @@ public class Properties { public Boolean getIsPortMirrored() { return isPortMirrored; } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public String getCloudRegionId() { + return cloudRegionId; + } + + public void setCloudRegionId(String cloudRegionId) { + this.cloudRegionId = cloudRegionId; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperties(String name, String value) { + additionalProperties.put(name, value); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java index f14a445f..fa0351e8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedTo.java @@ -1,9 +1,11 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) public class RelatedTo { private final String id; private final String relationshipLabel; @@ -20,19 +22,19 @@ public class RelatedTo { this.nodeType = nodeType; this.url = url; } - + @JsonProperty("id") public String getId() { return id; } - + @JsonProperty("relationship-label") public String getRelationshipLabel() { return relationshipLabel; } - + @JsonProperty("node-type") public String getNodeType() { return nodeType; } - + @JsonProperty("url") public String getUrl() { return url; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java index a2a98fc2..9227e87c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelatedToProperty.java @@ -1,8 +1,8 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class RelatedToProperty { @@ -12,6 +12,7 @@ public class RelatedToProperty { } + @JsonAlias("property-key") public void setPropertyKey(String propertyKey) { this.propertyKey = propertyKey; } @@ -22,16 +23,15 @@ public class RelatedToProperty { } + @JsonAlias("property-value") public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } - @JsonProperty("property-key") public String propertyKey; - @JsonProperty("property-value") public String propertyValue; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java index 6bf63c43..d6ba8d84 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Relationship.java @@ -1,7 +1,8 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + import java.util.List; @@ -9,19 +10,14 @@ import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class Relationship { - @JsonProperty("related-to") public String relatedTo; - @JsonProperty("related-link") public String relatedLink; - @JsonProperty("relationship-label") public String relationshipLabel; - @JsonProperty("relationship-data") public List relationshipData; - @JsonProperty("related-to-property") public List relatedToProperty; @@ -29,6 +25,7 @@ public class Relationship { return relatedTo; } + @JsonAlias("related-to") public void setRelatedTo(String relatedTo) { this.relatedTo = relatedTo; } @@ -37,6 +34,7 @@ public class Relationship { return relatedLink; } + @JsonAlias("related-link") public void setRelatedLink(String relatedLink) { this.relatedLink = relatedLink; } @@ -45,6 +43,7 @@ public class Relationship { return relationshipData; } + @JsonAlias("relationship-data") public void setRelationDataList(List relationDataList) { this.relationshipData = relationDataList; } @@ -53,6 +52,7 @@ public class Relationship { return relatedToProperty; } + @JsonAlias("related-to-property") public void setRelatedToPropertyList(List relatedToPropertyList) { this.relatedToProperty = relatedToPropertyList; } @@ -61,6 +61,7 @@ public class Relationship { return relationshipLabel; } + @JsonAlias("relationship-label") public void setRelationshipLabel(String relationshipLabel) { this.relationshipLabel = relationshipLabel; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java index 41536651..55a0b77d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipData.java @@ -1,29 +1,29 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class RelationshipData { - @JsonProperty("relationship-key") - public String getRelationshipKey() { - return relationshipKey; - } - @JsonProperty("relationship-key") - public void setRelationshipKey(String relationshipKey) { - this.relationshipKey = relationshipKey; - } - @JsonProperty("relationship-value") - public String getRelationshipValue() { - return relationshipValue; - } - @JsonProperty("relationship-value") - public void setRelationshipValue(String relationshipValue) { - this.relationshipValue = relationshipValue; - } + public String relationshipKey; + public String relationshipValue; - public String relationshipKey; - - public String relationshipValue; + public String getRelationshipKey() { + return relationshipKey; + } + + @JsonAlias("relationship-key") + public void setRelationshipKey(String relationshipKey) { + this.relationshipKey = relationshipKey; + } + + public String getRelationshipValue() { + return relationshipValue; + } + + @JsonAlias("relationship-value") + public void setRelationshipValue(String relationshipValue) { + this.relationshipValue = relationshipValue; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java index b16ddd01..f51fb9df 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/RelationshipList.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java index 736a1aa9..79f5272c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ResourceType.java @@ -10,10 +10,12 @@ import java.util.stream.Stream; public enum ResourceType { - SERVICE_INSTANCE("service-instance", "service-instance-name"), - GENERIC_VNF("generic-vnf", "vnf-name"), - VF_MODULE("vf-module", "vf-module-name"), - VOLUME_GROUP("volume-group", "volume-group-name"); + SERVICE_INSTANCE("service-instances", "service-instance-name"), + GENERIC_VNF("generic-vnfs", "vnf-name"), + L3_NETWORK("l3-networks", "network-name"), + VF_MODULE("vf-modules", "vf-module-name"), + INSTANCE_GROUP("instance-groups", "instance-group-name"), + VOLUME_GROUP("volume-groups", "volume-group-name"); private static Map AAI_FORMAT_MAP = Stream .of(ResourceType.values()) diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Result.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Result.java index 1eb46be7..cb4dc869 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Result.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/Result.java @@ -1,7 +1,7 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by moriya1 on 15/10/2017. diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceProperties.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceProperties.java index a76bcf8a..a1962cc5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceProperties.java @@ -1,8 +1,6 @@ package org.onap.vid.aai.model; import com.fasterxml.jackson.annotation.*; -import org.codehaus.jackson.annotate.JsonIgnoreProperties; -import org.codehaus.jackson.annotate.JsonProperty; import java.util.HashMap; import java.util.Map; @@ -35,70 +33,49 @@ import java.util.Map; public class ServiceProperties { @JsonProperty("service-instance-id") - @com.fasterxml.jackson.annotation.JsonProperty("service-instance-id") public String serviceInstanceId; @JsonProperty("service-instance-name") - @com.fasterxml.jackson.annotation.JsonProperty("service-instance-name") public String serviceInstanceName; @JsonProperty("model-invariant-id") - @com.fasterxml.jackson.annotation.JsonProperty("model-invariant-id") public String modelInvariantId; @JsonProperty("model-version-id") - @com.fasterxml.jackson.annotation.JsonProperty("model-version-id") public String modelVersionId; @JsonProperty("resource-version") - @com.fasterxml.jackson.annotation.JsonProperty("resource-version") public String resourceVersion; @JsonProperty("orchestration-status") - @com.fasterxml.jackson.annotation.JsonProperty("orchestration-status") public String orchestrationStatus; @JsonProperty("global-customer-id") - @com.fasterxml.jackson.annotation.JsonProperty("global-customer-id") public String globalCustomerId; @JsonProperty("subscriber-name") - @com.fasterxml.jackson.annotation.JsonProperty("subscriber-name") public String subscriberName; @JsonProperty("subscriber-type") - @com.fasterxml.jackson.annotation.JsonProperty("subscriber-type") public String subscriberType; @JsonProperty("vnf-id") - @com.fasterxml.jackson.annotation.JsonProperty("vnf-id") public String vnfId; @JsonProperty("vnf-name") - @com.fasterxml.jackson.annotation.JsonProperty("vnf-name") public String vnfName; @JsonProperty("vnf-type") - @com.fasterxml.jackson.annotation.JsonProperty("vnf-type") public String vnfType; @JsonProperty("service-id") - @com.fasterxml.jackson.annotation.JsonProperty("service-id") public String serviceId; @JsonProperty("prov-status") - @com.fasterxml.jackson.annotation.JsonProperty("prov-status") public String provStatus; @JsonProperty("in-maint") - @com.fasterxml.jackson.annotation.JsonProperty("in-maint") public Boolean inMaint; @JsonProperty("is-closed-loop-disabled") - @com.fasterxml.jackson.annotation.JsonProperty("is-closed-loop-disabled") public Boolean isClosedLoopDisabled; @JsonProperty("model-customization-id") - @com.fasterxml.jackson.annotation.JsonProperty("model-customization-id") public String modelCustomizationId; @JsonProperty("nf-type") - @com.fasterxml.jackson.annotation.JsonProperty("nf-type") public String nfType; @JsonProperty("nf-function") - @com.fasterxml.jackson.annotation.JsonProperty("nf-function") public String nfFunction; @JsonProperty("nf-role") - @com.fasterxml.jackson.annotation.JsonProperty("nf-role") public String nfRole; @JsonProperty("nf-naming-code") - @com.fasterxml.jackson.annotation.JsonProperty("nf-naming-code") public String nfNamingCode; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonAnyGetter public Map getAdditionalProperties() { diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceRelationships.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceRelationships.java index b8abc849..eba00356 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceRelationships.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceRelationships.java @@ -1,40 +1,31 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +@JsonIgnoreProperties(ignoreUnknown = true) public class ServiceRelationships { - @JsonProperty("service-instance-id") public String serviceInstanceId; - @JsonProperty("service-instance-name") public String serviceInstanceName; - @JsonProperty("service-type") public String serviceType; - @JsonProperty("service-role") public String serviceRole; - @JsonProperty("environment-context") public String environmentContext; - @JsonProperty("workload-context") public String workloadContext; - @JsonProperty("model-invariant-id") public String modelInvariantId; - - @JsonProperty("model-version-id") + public String modelVersionId; - @JsonProperty("resource-version") public String resourceVersion; - - @JsonProperty("orchestration-status") + public String orchestrationStatus; - @JsonProperty("relationship-list") public RelationshipList relationshipList; @@ -42,6 +33,7 @@ public class ServiceRelationships { return serviceInstanceId; } + @JsonAlias("service-instance-id") public void setServiceInstanceId(String serviceInstanceId) { this.serviceInstanceId = serviceInstanceId; } @@ -50,6 +42,7 @@ public class ServiceRelationships { return serviceInstanceName; } + @JsonAlias("service-instance-name") public void setServiceInstanceName(String serviceInstanceName) { this.serviceInstanceName = serviceInstanceName; } @@ -58,6 +51,43 @@ public class ServiceRelationships { return modelInvariantId; } + public String getServiceType() { + return serviceType; + } + + @JsonAlias("service-type") + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + @JsonAlias("service-role") + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public String getEnvironmentContext() { + return environmentContext; + } + + @JsonAlias("environment-context") + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + @JsonAlias("workload-context") + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + @JsonAlias("model-invariant-id") public void setModelInvariantId(String modelInvariantId) { this.modelInvariantId = modelInvariantId; } @@ -66,6 +96,7 @@ public class ServiceRelationships { return modelVersionId; } + @JsonAlias("model-version-id") public void setModelVersionId(String modelVersionId) { this.modelVersionId = modelVersionId; } @@ -74,6 +105,7 @@ public class ServiceRelationships { return resourceVersion; } + @JsonAlias("resource-version") public void setResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } @@ -82,6 +114,7 @@ public class ServiceRelationships { return orchestrationStatus; } + @JsonAlias("orchestration-status") public void setOrchestrationStatus(String orchestrationStatus) { this.orchestrationStatus = orchestrationStatus; } @@ -90,6 +123,7 @@ public class ServiceRelationships { return relationshipList; } + @JsonAlias("relationship-list") public void setRelationshipList(RelationshipList relationshipList) { this.relationshipList = relationshipList; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java index b2edfc17..554449b9 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/SimpleResult.java @@ -1,85 +1,73 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.annotate.JsonAnyGetter; -import org.codehaus.jackson.annotate.JsonAnySetter; -import org.codehaus.jackson.annotate.JsonIgnore; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; import java.util.HashMap; import java.util.List; import java.util.Map; public class SimpleResult { - @JsonProperty("id") private String id; - @JsonProperty("node-type") private String nodeType; - @JsonProperty("url") private String url; - @JsonProperty("properties") private Properties properties; - @JsonProperty("related-to") private List relatedTo = null; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); - @JsonProperty("id") public String getId() { return id; } @JsonProperty("id") - public void setId(String id) { + public void setJsonId(String id) { this.id = id; } - @JsonProperty("node-type") public String getNodeType() { return nodeType; } @JsonProperty("node-type") - public void setNodeType(String nodeType) { + public void setJsonNodeType(String nodeType) { this.nodeType = nodeType; } - @JsonProperty("url") public String getUrl() { return url; } @JsonProperty("url") - public void setUrl(String url) { + public void setJsonUrl(String url) { this.url = url; } - @JsonProperty("properties") public Properties getProperties() { return properties; } @JsonProperty("properties") - public void setProperties(Properties properties) { + public void setJsonProperties(Properties properties) { this.properties = properties; } - @JsonProperty("related-to") public List getRelatedTo() { return relatedTo; } @JsonProperty("related-to") - public void setRelatedTo(List relatedTo) { + public void setJsonRelatedTo(List relatedTo) { this.relatedTo = relatedTo; } - @JsonAnyGetter public Map getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { + public void setJsonAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/VnfResult.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/VnfResult.java index e4f22849..b404a025 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/model/VnfResult.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/VnfResult.java @@ -1,8 +1,6 @@ package org.onap.vid.aai.model; import com.fasterxml.jackson.annotation.*; -import org.codehaus.jackson.annotate.JsonProperty; -import org.onap.vid.RelatedTo; import java.util.HashMap; import java.util.List; @@ -18,10 +16,8 @@ import java.util.Map; "related-to" }) public class VnfResult { - @JsonProperty("id") public String id; - @com.fasterxml.jackson.annotation.JsonProperty("node-type") @JsonProperty("node-type") public String nodeType; @JsonProperty("url") @@ -29,10 +25,34 @@ public class VnfResult { @JsonProperty("properties") public ServiceProperties properties; @JsonProperty("related-to") - @com.fasterxml.jackson.annotation.JsonProperty("related-to") public List relatedTo = null; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); + + @JsonProperty("id") + public void setJsonId(String id) { + this.id = id; + } + + @JsonProperty("node-type") + public void setJsonNodeType(String nodeType) { + this.nodeType = nodeType; + } + + @JsonProperty("url") + public void setJsonUrl(String url) { + this.url = url; + } + + @JsonProperty("properties") + public void setJsonProperties(ServiceProperties properties) { + this.properties = properties; + } + + @JsonProperty("related-to") + public void setJsonRelatedTo(List relatedTo) { + this.relatedTo = relatedTo; + } @JsonAnyGetter public Map getAdditionalProperties() { @@ -40,7 +60,7 @@ public class VnfResult { } @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { + public void setJsonAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/interfaces/AaiModelWithRelationships.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/interfaces/AaiModelWithRelationships.java new file mode 100644 index 00000000..77fe4cea --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/model/interfaces/AaiModelWithRelationships.java @@ -0,0 +1,7 @@ +package org.onap.vid.aai.model.interfaces; + +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList; + +public interface AaiModelWithRelationships { + RelationshipList getRelationshipList(); +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java index f5625ce2..f4401ab3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java @@ -22,12 +22,14 @@ package org.onap.vid.aai.util; import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.ResponseWithRequestInfo; import org.onap.vid.aai.exceptions.InvalidPropertyException; import org.onap.vid.utils.Logging; +import org.onap.vid.utils.Unchecked; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; @@ -37,6 +39,7 @@ import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; +import java.net.URI; import java.net.URLEncoder; import java.util.Optional; import java.util.UUID; @@ -55,7 +58,6 @@ public class AAIRestInterface { protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); - /** The client. */ private Client client = null; @@ -105,9 +107,9 @@ public class AAIRestInterface { return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20"); } - private void initRestClient() { - initRestClient(false); - } + protected void initRestClient() { + initRestClient(false); + } private void initRestClient(boolean propagateExceptions) { @@ -160,47 +162,61 @@ public class AAIRestInterface { * @param xml the xml * @return the string */ - public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) { + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, URI requestUri, boolean xml) { return RestGet(fromAppId, transId, requestUri, xml, false); } - public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) { - String methodName = "RestGet"; - String url = systemPropertyHelper.getFullServicePath(requestUri); + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, URI requestUri, boolean xml, boolean propagateExceptions) { + return doRest(fromAppId, transId, requestUri, null, HttpMethod.GET, xml, propagateExceptions); + } + + public ResponseWithRequestInfo doRest(String fromAppId, String transId, URI requestUri, String payload, HttpMethod method, boolean xml, boolean propagateExceptions) { + String url = null; + String methodName = "Rest"+method.name(); try { + + url = systemPropertyHelper.getFullServicePath(requestUri); + initRestClient(propagateExceptions); logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); logger.debug(EELFLoggerDelegate.debugLogger, url + " for the get REST API"); - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + Logging.logRequest(outgoingRequestsLogger, method, url, payload); final Response response; - Invocation.Builder requestBuilder = client.target(url) - .request() - .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()); - response = systemPropertyHelper.isClientCertEnabled() ? - requestBuilder.get() : authenticateRequest(requestBuilder).get(); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); - - if (response.getStatusInfo().equals(Response.Status.OK)) { + Invocation.Builder requestBuilder = client.target(url) + .request() + .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header("Content-Type", MediaType.APPLICATION_JSON) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()); + + requestBuilder = systemPropertyHelper.isClientCertEnabled() ? + requestBuilder : authenticateRequest(requestBuilder); + + Invocation restInvocation = StringUtils.isEmpty(payload) ? + requestBuilder.build(method.name()) : + requestBuilder.build(method.name(), Entity.entity(payload, MediaType.APPLICATION_JSON)); + + response = restInvocation.invoke(); + Logging.logResponse(outgoingRequestsLogger, method, url, response); + + if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { logger.debug(EELFLoggerDelegate.debugLogger, methodName + SUCCESSFUL_API_MESSAGE); logger.info(EELFLoggerDelegate.errorLogger, methodName + SUCCESSFUL_API_MESSAGE); } else { logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response)); } - return new ResponseWithRequestInfo(response, url, HttpMethod.GET); + return new ResponseWithRequestInfo(response, url, method); } catch (Exception e) { logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); if (propagateExceptions) { - throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e); - } else { - return new ResponseWithRequestInfo(null, url, HttpMethod.GET); - } + throw new ExceptionWithRequestInfo(method, defaultIfNull(url, requestUri.toASCIIString()), e); + } else { + return new ResponseWithRequestInfo(null, url, method); + } } } @@ -222,7 +238,7 @@ public class AAIRestInterface { transId += ":" + UUID.randomUUID().toString(); logger.debug(methodName + START_STRING); Boolean response = false; - String url = systemPropertyHelper.getFullServicePath(path);; + String url = systemPropertyHelper.getFullServicePath(path); try { initRestClient(); @@ -263,37 +279,11 @@ public class AAIRestInterface { * @param path the path * @param payload the payload * @param xml the xml + * @param propagateExceptions * @return the string */ - public Response RestPut(String fromAppId, String path, String payload, boolean xml) { - String methodName = "RestPut"; - String url=systemPropertyHelper.getFullServicePath(path); - String transId = UUID.randomUUID().toString(); - logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); - - Response response = null; - try { - initRestClient(); - Logging.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, payload); - response = authenticateRequest(client.target(url) - .request() - .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId)) - .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) - .put(Entity.entity(payload, MediaType.APPLICATION_JSON)); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, response); - - if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) { - logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName)); - logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName)); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response)); - } - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); - } - return response; + public ResponseWithRequestInfo RestPut(String fromAppId, String path, String payload, boolean xml, boolean propagateExceptions) { + return doRest(fromAppId, UUID.randomUUID().toString(), Unchecked.toURI(path), payload, HttpMethod.PUT, xml, propagateExceptions); } @@ -313,13 +303,13 @@ public class AAIRestInterface { String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); - Response response = null; + Response response = null; try { initRestClient(); Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload); - response = authenticateRequest(client.target(systemPropertyHelper.getServiceBasePath(path)) + response = authenticateRequest(client.target(url) .request() - .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) + .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, fromAppId)) .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java new file mode 100644 index 00000000..8fa6f6c6 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAITreeConverter.java @@ -0,0 +1,89 @@ +package org.onap.vid.aai.util; + +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.model.aaiTree.*; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.services.AAITreeNodeBuilder; +import org.springframework.stereotype.Component; + +import java.util.Objects; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.counting; +import static java.util.stream.Collectors.groupingBy; +import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE; + +@Component +public class AAITreeConverter { + + public static final String VNF_TYPE = "vnf-type"; + public static final String NETWORK_TYPE = "network-type"; + + public static final String IS_BASE_VF_MODULE = "is-base-vf-module"; + + public enum ModelType { + service, + vnf, + network, + instanceGroup, + vfModule + } + + public ServiceInstance convertTreeToUIModel(AAITreeNode rootNode, String globalCustomerId, String serviceType, String instantiationType) { + ServiceInstance serviceInstance = new ServiceInstance(); + serviceInstance.setInstanceId(rootNode.getId()); + serviceInstance.setInstanceName(rootNode.getName()); + serviceInstance.setOrchStatus(rootNode.getOrchestrationStatus()); + serviceInstance.setGlobalSubscriberId(globalCustomerId); + serviceInstance.setSubscriptionServiceType(serviceType); + serviceInstance.setIsALaCarte(StringUtils.equals(instantiationType, A_LA_CARTE)); + + serviceInstance.setModelInfo(createModelInfo(rootNode, ModelType.service)); + + //set children: vnf, network,group + rootNode.getChildren().forEach(child -> { + if (child.getType().equals(AAITreeNodeBuilder.GENERIC_VNF)) { + serviceInstance.getVnfs().put(child.getUniqueNodeKey(), Vnf.from(child)); + } else if (child.getType().equals(AAITreeNodeBuilder.NETWORK)) { + serviceInstance.getNetworks().put(child.getUniqueNodeKey(), Network.from(child)); + } else if (child.getType().equals(AAITreeNodeBuilder.INSTANCE_GROUP)) { + serviceInstance.getVnfGroups().put(child.getUniqueNodeKey(), VnfGroup.from(child)); + } + }); + + serviceInstance.setExistingVNFCounterMap( + serviceInstance.getVnfs().entrySet().stream() + .map(k -> k.getValue().getModelInfo().getModelVersionId()) + .collect(groupingBy(identity(), counting())) + ); + + serviceInstance.setExistingNetworksCounterMap( + serviceInstance.getNetworks().entrySet().stream() + .map(k -> k.getValue().getModelInfo().getModelVersionId()) + .filter(Objects::nonNull) + .collect(groupingBy(identity(), counting())) + ); + + + serviceInstance.setExistingVnfGroupCounterMap( + serviceInstance.getVnfGroups().entrySet().stream() + .map(k -> k.getValue().getModelInfo().getModelVersionId()) + .filter(Objects::nonNull) + .collect(groupingBy(identity(), counting())) + ); + + return serviceInstance; + } + + private static ModelInfo createModelInfo(AAITreeNode aaiNode, ModelType modelType) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType(modelType.name()); + modelInfo.setModelName(aaiNode.getModelName()); + modelInfo.setModelVersion(aaiNode.getModelVersion()); + modelInfo.setModelVersionId(aaiNode.getModelVersionId()); + modelInfo.setModelInvariantId(aaiNode.getModelInvariantId()); + modelInfo.setModelCustomizationId(aaiNode.getModelCustomizationId()); + + return modelInfo; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheConfig.kt b/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheConfig.kt new file mode 100644 index 00000000..0ff60414 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheConfig.kt @@ -0,0 +1,52 @@ +package org.onap.vid.aai.util + +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.module.kotlin.KotlinModule +import com.google.common.collect.ImmutableMap +import org.springframework.stereotype.Component + +//I use a regular kotlin class because I want that when jackson read +//a json with null values (or missing fields) they would get default values. +//for other cases it's better to use data class for POJO class +//for more information you can read here : +//https://github.com/FasterXML/jackson-module-kotlin/issues/130 +class CacheConfig constructor( + isActive: Boolean?, + expireAfterWriteHours: Long?, + refreshAfterWriteSeconds: Long?) { + val isActive: Boolean = isActive ?: true + val expireAfterWriteHours: Long = expireAfterWriteHours ?: 24L + val refreshAfterWriteSeconds: Long = refreshAfterWriteSeconds ?: 10L + + companion object { + val defaultCacheConfig = CacheConfig(null, null, null) + } + +} + + +interface CacheConfigProvider { + fun getCacheConfig(cacheName:String): CacheConfig +} + +@Component +class CacheConfigProviderImpl() : CacheConfigProvider { + private val mapper = ObjectMapper().apply { registerModule(KotlinModule()) } + + private fun readMapOfCacheConfig(): Map { + val configInputStream = CacheConfigProviderImpl::class.java.classLoader.getResourceAsStream("cacheConfig.json") + + return if (configInputStream == null) { + ImmutableMap.of() + } else { + mapper.readValue(configInputStream, object : TypeReference>() {}) + } + } + + override fun getCacheConfig(cacheName: String): CacheConfig { + return readMapOfCacheConfig()[cacheName] ?: CacheConfig.defaultCacheConfig + } +} + + diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProvider.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProvider.java new file mode 100644 index 00000000..63615f49 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProvider.java @@ -0,0 +1,37 @@ +package org.onap.vid.aai.util; + +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; + +public interface CacheProvider { + String KEY_DELIMITER = "!@#'"; + /* + Returns the cache associated with given name; creates one if wasn't any + */ + Cache aaiClientCacheFor(String name, Function loader); + + /* + reset cache if exist. Otherwise do nothing + */ + void resetCache(String name); + + interface Cache { + V get(K key); + } + + static String compileKey(List args) { + return compileKey(args.toArray(new String[0])); + } + + static String compileKey(String... args) { + return Stream.of(args).map(arg->defaultIfNull(arg, "")).collect( Collectors.joining( KEY_DELIMITER ) ); + } + + static String[] decompileKey(String key) { + return key.split(KEY_DELIMITER); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProviderWithLoadingCache.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProviderWithLoadingCache.java new file mode 100644 index 00000000..26a3ebf2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/CacheProviderWithLoadingCache.java @@ -0,0 +1,100 @@ +package org.onap.vid.aai.util; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.util.concurrent.UncheckedExecutionException; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.jetbrains.annotations.NotNull; +import org.onap.vid.properties.Features; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.togglz.core.manager.FeatureManager; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; + +@Component +public class CacheProviderWithLoadingCache implements CacheProvider { + + private final ExecutorService cacheReloadPool; + private final FeatureManager featureManager; + private final CacheConfigProvider cacheConfigProvider; + private final ConcurrentHashMap caches; + + + @Autowired + public CacheProviderWithLoadingCache(FeatureManager featureManager, CacheConfigProvider cacheConfigProvider) { + this.featureManager = featureManager; + this.cacheConfigProvider = cacheConfigProvider; + this.cacheReloadPool = Executors.newFixedThreadPool(3); + this.caches = new ConcurrentHashMap<>(); + } + + /* + Returns the cache associated with given name; creates one if wasn't any + */ + @Override + public Cache aaiClientCacheFor(String name, Function loader) { + return (Cache) caches.computeIfAbsent(name, s -> buildAaiClientCacheFrom(loader, name)); + } + + @Override + public void resetCache(String name) { + caches.remove(name); + } + + /* + Creates and returns a Cache that use provided `loader` to fetch values for + search keys, and stores the result for reuse over a certain time. + The cache will not use any stored key if FLAG_1810_AAI_LOCAL_CACHE is turned off. + In that case, `loader` will be invoked for any `get()` request from the cache. The + cache adheres the flag in real-time; so no restart is required. + */ + protected Cache buildAaiClientCacheFrom(Function loader, String name) { + final LoadingCache activeCache = buildAaiClientActiveCacheFrom(loader, name); + + // this works because Cache interface has only a single method: "get()" + // can be replaced with new anonimous class; e.g.: + // return new Cache() { ... } + return key -> { + if (featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE) && + defaultIfNull(cacheConfigProvider.getCacheConfig(name).isActive(), true)) { + try { + return activeCache.getUnchecked(key); + } + catch (UncheckedExecutionException exception) { + return ExceptionUtils.rethrow(exception.getCause()); + } + } else { + activeCache.invalidateAll(); + activeCache.cleanUp(); + return loader.apply(key); + } + }; + } + + private LoadingCache buildAaiClientActiveCacheFrom(Function loader, String name) { + return createCacheBuilder(name).build(createAsyncReloadingCacheLoaderFrom(loader)); + + } + + @NotNull + protected CacheBuilder createCacheBuilder(String name) { + CacheConfig cacheConfig = cacheConfigProvider.getCacheConfig(name); + return CacheBuilder.newBuilder() + .maximumSize(1000) + .expireAfterWrite(cacheConfig.getExpireAfterWriteHours(), TimeUnit.HOURS) + .refreshAfterWrite(cacheConfig.getRefreshAfterWriteSeconds(), TimeUnit.SECONDS); + } + + private CacheLoader createAsyncReloadingCacheLoaderFrom(Function loader) { + return CacheLoader.asyncReloading(CacheLoader.from(loader::apply), cacheReloadPool); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java index 15f81439..489d2f1b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java @@ -22,11 +22,16 @@ package org.onap.vid.aai.util; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; +import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.HttpUrlConnectorProvider; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.aai.exceptions.HttpClientBuilderException; +import org.onap.vid.properties.Features; +import org.togglz.core.manager.FeatureManager; +import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; @@ -47,16 +52,19 @@ public class HttpsAuthClient { private final SystemPropertyHelper systemPropertyHelper; private final SSLContextProvider sslContextProvider; - public HttpsAuthClient(String certFilePath, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider) { + public HttpsAuthClient(String certFilePath, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider, FeatureManager featureManager) { this.certFilePath = certFilePath; this.systemPropertyHelper = systemPropertyHelper; this.sslContextProvider = sslContextProvider; + this.featureManager = featureManager; } private final String certFilePath; + FeatureManager featureManager; + /** The logger. */ - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsAuthClient.class); + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(org.onap.vid.aai.util.HttpsAuthClient.class); /** @@ -70,7 +78,7 @@ public class HttpsAuthClient { try { setSystemProperties(); - ignoreHostname(); + optionallyVerifyHostname(); return systemPropertyHelper.isClientCertEnabled() ? getTrustedClient(config, getKeystorePath(), systemPropertyHelper.getDecryptedKeystorePassword(), mode) @@ -83,8 +91,8 @@ public class HttpsAuthClient { } - private void ignoreHostname() { - HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); + private void optionallyVerifyHostname() { + HttpsURLConnection.setDefaultHostnameVerifier(getHostnameVerifier()); } private Client getUntrustedClient(ClientConfig config) { @@ -94,12 +102,20 @@ public class HttpsAuthClient { private Client getTrustedClient(ClientConfig config, String keystorePath, String keystorePassword, HttpClientMode httpClientMode) throws HttpClientBuilderException { return ClientBuilder.newBuilder() .sslContext(sslContextProvider.getSslContext(keystorePath, keystorePassword, httpClientMode)) - .hostnameVerifier((s, sslSession) -> true) + .hostnameVerifier(getHostnameVerifier()) .withConfig(config) .build() .register(CustomJacksonJaxBJsonProvider.class); } + protected HostnameVerifier getHostnameVerifier() { + if(featureManager.isActive(Features.FLAG_EXP_USE_DEFAULT_HOST_NAME_VERIFIER)){ + return new DefaultHostnameVerifier(); + } + + return new NoopHostnameVerifier(); + } + private String getKeystorePath() { return getCertificatesPath() + FileSystems.getDefault().getSeparator() + systemPropertyHelper.getAAIKeystoreFilename(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java deleted file mode 100644 index d1f1cfc8..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.aai.util; - -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLContextBuilder; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.eclipse.jetty.util.security.Password; -import org.onap.vid.exceptions.GenericUncheckedException; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; - -import javax.net.ssl.SSLContext; -import java.io.FileInputStream; -import java.security.GeneralSecurityException; -import java.security.KeyManagementException; -import java.security.KeyStore; - - -/** - * The Class HttpsComponentsClient. - */ -public class HttpsComponentsClient{ - - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsComponentsClient.class); - - /** - * Gets the client. - * - * @param certFilePath the cert file path - * @return the client - * @throws KeyManagementException the key management exception - */ - public static CloseableHttpClient getClient(String certFilePath) { - CloseableHttpClient httpclient = null; - try { - - String truststore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_TRUSTSTORE_FILENAME); - String truststore_password = SystemProperties.getProperty(AAIProperties.AAI_TRUSTSTORE_PASSWD_X); - String decrypted_truststore_password = Password.deobfuscate(truststore_password); - String keystore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_FILENAME); - String keystore_password = SystemProperties.getProperty(AAIProperties.AAI_KEYSTORE_PASSWD_X); - String decrypted_keystore_password = Password.deobfuscate(keystore_password); - - SSLContextBuilder sslContextB = new SSLContextBuilder(); - - KeyStore ks = KeyStore.getInstance("PKCS12"); - char[] pwd = decrypted_keystore_password.toCharArray(); - - try(FileInputStream fin = new FileInputStream(keystore_path)) { - ks.load(fin, pwd); - } - catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up keystore"); - logger.error(EELFLoggerDelegate.errorLogger, "Error loading keystore materials: (keystore path: {}, obfuascated keystore password: {})", keystore_path, keystore_password); - throw new GenericUncheckedException(e); - } - - sslContextB.loadKeyMaterial(ks, pwd); - - KeyStore ts = KeyStore.getInstance("JKS"); - char[] pwd1 = decrypted_truststore_password.toCharArray(); - - try(FileInputStream fin1 = new FileInputStream(truststore_path)) { - ts.load(fin1, pwd1); - } - catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up truststore"); - logger.error(EELFLoggerDelegate.errorLogger, "Error loading truststore materials: (truststore path: {}, obfuascated truststore password: {})", truststore_path, truststore_password); - throw new GenericUncheckedException(e); - } - - sslContextB.loadTrustMaterial(ts); - sslContextB.loadKeyMaterial(ks, pwd); - sslContextB.useTLS(); - - SSLContext sslcontext = sslContextB.build(); - - SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory( - sslcontext, - new String[] { "TLSv1.1", "TLSv1.2" }, - null, - SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER ); - - httpclient = HttpClients.custom() - .setSSLSocketFactory(sslFactory) - .build(); - - - } catch (GeneralSecurityException e) { - throw new GenericUncheckedException(e); - } - return httpclient; - } - - - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java index cfc56d18..b39c2031 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java @@ -48,8 +48,8 @@ public class JettyObfuscationConversionCommandLineUtil { System.out.println(encoded); } else if (cmd.hasOption("d")) { toProcess = cmd.getOptionValue("d"); - String decoded_str = Password.deobfuscate(toProcess); - System.out.println(decoded_str); + String decodedStr = Password.deobfuscate(toProcess); + System.out.println(decodedStr); } else { usage(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/ServiceInstanceStandardQuery.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/ServiceInstanceStandardQuery.java new file mode 100644 index 00000000..22743bbf --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/ServiceInstanceStandardQuery.java @@ -0,0 +1,93 @@ +package org.onap.vid.aai.util; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.text.StrSubstitutor; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.*; +import org.onap.vid.aai.model.interfaces.AaiModelWithRelationships; +import org.onap.vid.utils.Multival; +import org.onap.vid.utils.Unchecked; + +import javax.inject.Inject; +import java.net.URI; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toSet; + +public class ServiceInstanceStandardQuery { + + private static final String SERVICE_INSTANCE_URI_TEMPLATE = "" + + "business/customers/customer/${global-customer-id}" + + "/service-subscriptions/service-subscription/${service-type}" + + "/service-instances/service-instance/${service-instance-id}"; + + private final AaiClientInterface aaiClient; + + @Inject + public ServiceInstanceStandardQuery(AaiClientInterface aaiClient) { + this.aaiClient = aaiClient; + } + + public ServiceInstance fetchServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) { + final String serviceInstanceUri = getServiceInstanceUri(globalCustomerId, serviceType, serviceInstanceId); + + return fetchServiceInstance(Unchecked.toURI(serviceInstanceUri)); + } + + ServiceInstance fetchServiceInstance(URI serviceInstanceUri) { + return objectByUri(ServiceInstance.class, serviceInstanceUri); + } + + protected T objectByUri(Class clazz, URI aaiResourceUri) { + return aaiClient.typedAaiGet(aaiResourceUri, clazz); + } + + public Multival fetchRelatedVnfs(ServiceInstance serviceInstance) { + return fetchRelated("service", serviceInstance, "generic-vnf", Vnf.class); + } + + public Multival fetchRelatedL3Networks(String sourceType, K source) { + return fetchRelated(sourceType, source, "l3-network", Network.class); + } + + public Multival fetchRelatedVlanTags(Network network) { + return fetchRelated("network", network, "vlan-tag", Vlan.class); + } + + private String getServiceInstanceUri(String globalCustomerId, String serviceType, String serviceInstanceId) { + return new StrSubstitutor(ImmutableMap.of( + "global-customer-id", globalCustomerId, + "service-type", serviceType, + "service-instance-id", serviceInstanceId + )).replace(SERVICE_INSTANCE_URI_TEMPLATE); + } + + private Multival fetchRelated(String sourceType, K source, String destType, Class destClass) { + return Multival.of( + sourceType, + source, + destType, + fetchRelatedInner(source, destType, destClass) + ); + } + + private Set fetchRelatedInner(K source, String destType, Class destClass) { + return getURIsOf(source, relationship -> relatedTo(relationship, destType)) + .map(destUri -> objectByUri(destClass, destUri)) + .collect(toSet()); + } + + protected Stream getURIsOf(AaiModelWithRelationships aaiModel, Predicate predicate) { + return aaiModel.getRelationshipList().getRelationship().stream() + .filter(predicate) + .map(r -> r.relatedLink) + .map(Unchecked::toURI); + } + + protected static boolean relatedTo(Relationship r, String relationshipName) { + return relationshipName.equals(r.getRelatedTo()); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/SystemPropertyHelper.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/SystemPropertyHelper.java index 4d43d3ba..939bfe5b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/SystemPropertyHelper.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/SystemPropertyHelper.java @@ -23,8 +23,10 @@ package org.onap.vid.aai.util; import org.eclipse.jetty.util.security.Password; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.aai.exceptions.InvalidPropertyException; +import org.onap.vid.utils.Unchecked; import java.io.UnsupportedEncodingException; +import java.net.URI; import java.util.Base64; import java.util.Optional; @@ -74,6 +76,15 @@ public class SystemPropertyHelper { return getAAIServerUrl().orElse("") + path; } + public String getFullServicePath(URI requestUri) { + // resolve() will merge two paths, handling the restiveness: + // Especially if requestUri starts with a '/' -- result will be + // AAI_SERVER_URL host, post, etc., and the path will be just + // requestUri. + return Unchecked.toURI(getAAIServerUrl().orElse("")) + .resolve(requestUri).toASCIIString(); + } + public String getServiceBasePath(String path) { return getAAIServerBaseUrl().orElse("") + path; } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java index fdbf2c28..d26a1b27 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java @@ -50,4 +50,5 @@ public interface AsdcClient { * @throws AsdcCatalogException the asdc catalog exception */ Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException; + } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureServices.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureServices.java index a6aa3de6..6eaf37b9 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureServices.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/SecureServices.java @@ -1,7 +1,6 @@ package org.onap.vid.asdc.beans; import java.util.Collection; -import java.util.List; /** * Created by Oren on 6/27/17. diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java index 59028492..d66591c3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Input.java @@ -20,10 +20,11 @@ package org.onap.vid.asdc.beans.tosca; +import com.fasterxml.jackson.annotation.JsonInclude; import org.onap.sdc.toscaparser.api.Property; -import java.util.List; import java.util.ArrayList; +import java.util.List; // TODO: Auto-generated Javadoc /** @@ -36,6 +37,7 @@ public class Input { this.description = input.getDescription(); this._default = input.getDefault(); this.inputProperties = new InputProperties(properties); + this.fromInputName = input.getName(); } /** The type. */ @@ -51,7 +53,9 @@ public class Input { private Input entry_schema; private InputProperties inputProperties; - + + private String fromInputName; + /** The constraints */ private List constraints; @@ -63,12 +67,12 @@ public class Input { private String templateUUID; private String templateInvariantUUID; private String templateCustomizationUUID; - + /** * Instantiates a new input. */ public Input() { - constraints = new ArrayList(); + constraints = new ArrayList<>(); } /** @@ -160,6 +164,11 @@ public class Input { return inputProperties; } + @JsonInclude(JsonInclude.Include.NON_NULL) + public String getFromInputName() { + return fromInputName; + } + public void setInputProperties(InputProperties inputProperties) { this.inputProperties = inputProperties; } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java index bc2513ea..c5fe8b90 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/InputProperties.java @@ -17,13 +17,10 @@ public class InputProperties { for(Property property: properties) { if (property.getName().equals("source_type")) { this.sourceType = (String)property.getValue(); - continue; } else if (property.getName().equals("param_name")) { this.paramName = (String)property.getValue(); - continue; } else if (property.getName().equals("vf_module_label")) { this.vfModuleLabel = getPropertyValueAsString(property); - continue; } } } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/NodeTemplate.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/NodeTemplate.java index 28210b2e..23c0a109 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/NodeTemplate.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/NodeTemplate.java @@ -20,8 +20,8 @@ package org.onap.vid.asdc.beans.tosca; -import java.util.Map; import java.util.HashMap; +import java.util.Map; /** * The Class NodeTemplate. @@ -41,7 +41,7 @@ public class NodeTemplate { private Object requirements; public NodeTemplate () { - properties = new HashMap(); + properties = new HashMap<>(); } /** * Gets the type. diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java index 74b00bdf..a15c55ff 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/Property.java @@ -43,7 +43,7 @@ public class Property { /** * Instantiates a new property. */ - Property() {} + private Property() {} /** * Gets the type. diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/SubstitutionMappings.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/SubstitutionMappings.java index 70779c5f..4ce30239 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/SubstitutionMappings.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/SubstitutionMappings.java @@ -41,8 +41,8 @@ public class SubstitutionMappings { * Instantiates a new substitution mappings. */ public SubstitutionMappings() { - capabilities = new HashMap (); - requirements = new HashMap (); + capabilities = new HashMap<> (); + requirements = new HashMap<> (); } /** diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/TopologyTemplate.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/TopologyTemplate.java index 70830715..b24627d1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/TopologyTemplate.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/TopologyTemplate.java @@ -45,9 +45,9 @@ public class TopologyTemplate { */ public TopologyTemplate() { substitution_mappings = new SubstitutionMappings(); - inputs = new HashMap (); - node_templates = new HashMap (); - groups = new HashMap (); + inputs = new HashMap<> (); + node_templates = new HashMap<> (); + groups = new HashMap<> (); } /** diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaCsar.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaCsar.java index 67858357..4cf2f797 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaCsar.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaCsar.java @@ -43,7 +43,7 @@ public class ToscaCsar { private final ToscaModel parent; /** The children. */ - private Collection children = new LinkedList (); + private Collection children = new LinkedList<> (); /** * Instantiates a new builder. diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaMeta.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaMeta.java index a7a6c629..ad883401 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaMeta.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/tosca/ToscaMeta.java @@ -20,6 +20,8 @@ package org.onap.vid.asdc.beans.tosca; +import org.onap.vid.asdc.AsdcCatalogException; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -27,8 +29,6 @@ import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; -import org.onap.vid.asdc.AsdcCatalogException; - /** * The Class ToscaMeta. */ @@ -45,7 +45,7 @@ public class ToscaMeta { * @throws AsdcCatalogException the asdc catalog exception */ private ToscaMeta(Builder builder) throws IOException, AsdcCatalogException { - metadata = new HashMap (); + metadata = new HashMap<> (); read(builder.inputStream); } @@ -113,10 +113,7 @@ public class ToscaMeta { metadata.put(entry[0], entry[1].substring(1)); } } - } catch (IOException e) { - metadata.clear(); - throw e; - } catch (AsdcCatalogException e) { + } catch (IOException | AsdcCatalogException e) { metadata.clear(); throw e; } diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java index 108d9c06..bcb201d2 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/local/LocalAsdcClient.java @@ -1,31 +1,22 @@ package org.onap.vid.asdc.local; -import org.codehaus.jackson.JsonParseException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONArray; import org.json.JSONObject; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.beans.Service; -import org.onap.vid.asdc.beans.tosca.ToscaCsar; -import org.onap.vid.asdc.beans.tosca.ToscaMeta; -import org.onap.vid.asdc.beans.tosca.ToscaModel; import org.onap.vid.exceptions.GenericUncheckedException; -import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.Map; import java.util.UUID; -import java.util.zip.ZipFile; /** * The Class LocalAsdcClient. @@ -117,7 +108,7 @@ public class LocalAsdcClient implements AsdcClient { /* (non-Javadoc) * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID) */ - public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException { + public Path getServiceToscaModel(UUID serviceUuid) { String toscaModelURL = null; @@ -145,49 +136,6 @@ public class LocalAsdcClient implements AsdcClient { } } - /** - * Gets the tosca model. - * - * @param csarInputStream the csar input stream - * @return the tosca model - * @throws AsdcCatalogException the asdc catalog exception - */ - private ToscaCsar getToscaModel(InputStream csarInputStream) throws AsdcCatalogException { - final Path csarFile; - - try { - csarFile = Files.createTempFile("csar", ".zip"); - Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - throw new AsdcCatalogException("Caught IOException while creating CSAR", e); - } - - try (final ZipFile csar = new ZipFile(csarFile.toFile())) { - - final InputStream toscaMetaStream = csar.getInputStream(csar.getEntry("TOSCA-Metadata/TOSCA.meta")); - final ToscaMeta toscaMeta = new ToscaMeta.Builder(toscaMetaStream).build(); - final String entryDefinitions = toscaMeta.get("Entry-Definitions"); - final InputStream toscaParentEntryYamlStream = csar.getInputStream(csar.getEntry(entryDefinitions)); - - final Yaml yaml = new Yaml(); - final ToscaModel parentModel = yaml.loadAs(toscaParentEntryYamlStream, ToscaModel.class); - - final ToscaCsar.Builder csarBuilder = new ToscaCsar.Builder(parentModel); - - for (Map> imports : parentModel.getImports()) { - for (Map.Entry> entry : imports.entrySet()) { - final InputStream toscaChildEntryYamlStream = csar.getInputStream(csar.getEntry("Definitions/" + entry.getValue().get("file"))); - final ToscaModel childModel = yaml.loadAs(toscaChildEntryYamlStream, ToscaModel.class); - csarBuilder.addVnf(childModel); - } - } - - return csarBuilder.build(); - } catch (IOException e) { - throw new AsdcCatalogException("Caught IOException while processing CSAR", e); - } - } - /** * The Class Builder. */ diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ServiceModelInflator.kt b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ServiceModelInflator.kt new file mode 100644 index 00000000..79ab0459 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ServiceModelInflator.kt @@ -0,0 +1,43 @@ +package org.onap.vid.asdc.parser + +import org.onap.vid.model.* +import org.springframework.stereotype.Component + +@Component +class ServiceModelInflator { + + data class Names (val modelCustomizationName: String?, val modelKey: String?) + + fun toNamesByVersionId(model: ServiceModel): Map { + return emptyMap() + .plus(inflate(model.networks)) + .plus(inflate(model.vnfs)) + .plus(inflate(model.vnfGroups)) + } + + private fun inflate(instances: Map): Map { + return instances.entries.map { inflate(it.key, it.value) }.fold(emptyMap()) { acc, it -> acc.plus(it) } + } + + private fun inflate(modelKey: String, vnf: VNF): Map { + return mapOf(vnf.uuid to Names(vnf.modelCustomizationName, modelKey)) + .plus(inflate(vnf.vfModules)) + .plus(inflate(vnf.volumeGroups)) + } + + private fun inflate(modelKey: String, instance: Any?): Map { + return when (instance) { + is Network -> mapOf(instance.uuid to Names(instance.modelCustomizationName, modelKey)) + is VfModule -> mapOf(instance.uuid to Names(instance.modelCustomizationName, modelKey)) + is VolumeGroup -> mapOf(instance.uuid to Names(instance.modelCustomizationName, modelKey)) + is ResourceGroup -> mapOf(instance.uuid to Names(instance.modelCustomizationName, modelKey)) + is VNF -> inflate(modelKey, instance) + + else -> { + // sink + emptyMap() + } + } + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaNamingPolicy.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaNamingPolicy.java new file mode 100644 index 00000000..ca260103 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaNamingPolicy.java @@ -0,0 +1,28 @@ +package org.onap.vid.asdc.parser; + +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Property; + +import java.util.Map; + +public class ToscaNamingPolicy { + + public static String isUserProvidingServiceNameOptional(ISdcCsarHelper csarHelper){ + return csarHelper.getServiceMetadata().getValue(ToscaParserImpl2.Constants.ECOMP_GENERATED_NAMING); + } + + private static Object isPropertyContainsEcompGeneratedNaming(Property property) { + return ((Map) (property.getValue())).get(ToscaParserImpl2.Constants.ECOMP_GENERATED_NAMING_PROPERTY); + } + + public static String getEcompNamingValueForNode(NodeTemplate node, String parentProperty) { + return node.getPropertiesObjects().stream() + .filter(property -> StringUtils.equals(property.getName(), parentProperty)) + .findFirst() + .map(ToscaNamingPolicy::isPropertyContainsEcompGeneratedNaming) + .map(Object::toString) + .orElse("false"); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java index 27445c0f..ef57ccb6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl.java @@ -16,6 +16,7 @@ import org.yaml.snakeyaml.error.YAMLException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -92,7 +93,7 @@ public class ToscaParserImpl implements ToscaParser { final ToscaModel asdcServiceToscaModel = toscaCsar.getParent(); serviceModel.setService(ServiceModel.extractService(asdcServiceToscaModel, service)); - + serviceModel.setFabricConfigurations(Collections.emptyMap()); populateVnfsAndNetwork(methodName, isNewFlow, vnfs, networks, asdcServiceToscaModel, serviceModel); @@ -180,8 +181,6 @@ public class ToscaParserImpl implements ToscaParser { } private ServiceModel getCustomizedServices(ToscaModel asdcServiceToscaModel, ServiceModel serviceModel) { - String methodName = "asdcServiceToscaModel"; - // asdcServiceToscaModel should have vf modules and vol groups populated // at this point but // they are not associated with the VNFs diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java index 57d80ce9..53ec4036 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java @@ -1,11 +1,12 @@ package org.onap.vid.asdc.parser; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.enums.FilterType; +import org.onap.sdc.tosca.parser.enums.SdcTypes; import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; -import org.onap.sdc.tosca.parser.impl.FilterType; import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; -import org.onap.sdc.tosca.parser.impl.SdcTypes; import org.onap.sdc.toscaparser.api.Group; import org.onap.sdc.toscaparser.api.*; import org.onap.sdc.toscaparser.api.elements.Metadata; @@ -15,87 +16,112 @@ import org.onap.vid.model.*; import java.nio.file.Path; import java.util.*; -import java.util.stream.Collectors; +import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.VF_MODULE_LABEL; public class ToscaParserImpl2 { - - public class Constants { - public final static String UUID = "UUID"; - public final static String DESCRIPTION = "description"; - public final static String SERVICE_TYPE = "serviceType"; - public final static String SERVICE_ROLE = "serviceRole"; - public final static String ECOMP_GENERATED_NAMING = "ecompGeneratedNaming"; - - public final static String CUSTOMIZATION_UUID = "customizationUUID"; - public final static String VF_MODULE_MODEL_VERSION = "vfModuleModelVersion"; - public final static String VF_MODULE_MODEL_CUSTOMIZATION_UUID = "vfModuleModelCustomizationUUID"; - public final static String VOLUME_GROUP = "volume_group"; - public final static String VF_MODULE_MODEL_INVARIANT_UUID = "vfModuleModelInvariantUUID"; - public final static String VF_MODULE_MODEL_UUID = "vfModuleModelUUID"; - public final static String INVARIANT_UUID = "invariantUUID"; - public final static String VERSION = "version"; - public final static String NAME = "name"; - public final static String CATEGORY = "category"; - public final static String VF_MODULE_MODEL_NAME = "vfModuleModelName"; - public final static String GET_INPUT = "get_input"; - public final static String TYPE = "type"; - - public final static String INSTANTIATION_TYPE = "instantiationType"; + + private final VidNotionsBuilder vidNotionsBuilder; + + public class Constants { + public static final String UUID = "UUID"; + public static final String DESCRIPTION = "description"; + public static final String SERVICE_TYPE = "serviceType"; + public static final String SERVICE_ROLE = "serviceRole"; + public static final String ECOMP_GENERATED_NAMING = "ecompGeneratedNaming"; + + public static final String CUSTOMIZATION_UUID = "customizationUUID"; + public static final String VF_MODULE_MODEL_VERSION = "vfModuleModelVersion"; + public static final String VF_MODULE_MODEL_CUSTOMIZATION_UUID = "vfModuleModelCustomizationUUID"; + public static final String VOLUME_GROUP = "volume_group"; + public static final String VF_MODULE_MODEL_INVARIANT_UUID = "vfModuleModelInvariantUUID"; + public static final String VF_MODULE_MODEL_UUID = "vfModuleModelUUID"; + public static final String INVARIANT_UUID = "invariantUUID"; + public static final String VERSION = "version"; + public static final String NAME = "name"; + public static final String CATEGORY = "category"; + public static final String VF_MODULE_MODEL_NAME = "vfModuleModelName"; + public static final String GET_INPUT = "get_input"; + public static final String TYPE = "type"; + + public static final String INSTANTIATION_TYPE = "instantiationType"; //instantiation type - public final static String BOTH = "Both"; - public final static String MACRO = "Macro"; - public final static String A_LA_CARTE = "A-La-Carte"; - public final static String CLIENT_CONFIG = "ClientConfig"; + public static final String BOTH = "Both"; + public static final String MACRO = "Macro"; + public static final String A_LA_CARTE = "A-La-Carte"; + public static final String CLIENT_CONFIG = "ClientConfig"; + + //service role + public static final String GROUPING = "GROUPING"; //group properties - public final static String MIN_VF_MODULE_INSTANCES = "min_vf_module_instances"; - public final static String MAX_VF_MODULE_INSTANCES = "max_vf_module_instances"; - public final static String INITIAL_COUNT = "initial_count"; - public final static String VF_MODULE_LABEL = "vf_module_label"; + public static final String MIN_VF_MODULE_INSTANCES = "min_vf_module_instances"; + public static final String MAX_VF_MODULE_INSTANCES = "max_vf_module_instances"; + public static final String INITIAL_COUNT = "initial_count"; + public static final String VF_MODULE_LABEL = "vf_module_label"; + public static final String VF_MODULE_TYPE = "vf_module_type"; //collection resource properties - public final static String SUBCATEGORY = "subcategory"; - public final static String RESOURCE_VENDOR = "resourceVendor"; - public final static String RESOURCE_VENDOR_RELEASE = "resourceVendorRelease"; - public final static String RESOURCE_VENDOR_MODEL_NUMBER = "resourceVendorModelNumber"; - public final static String ORG_OPENECOMP_GROUPS_NETWORK_COLLECTION = "org.openecomp.groups.NetworkCollection"; - public final static String NETWORK_COLLECTION_FUNCTION = "network_collection_function"; - public final static String NETWORK_COLLECTION_DESCRIPTION = "network_collection_description"; + public static final String SUBCATEGORY = "subcategory"; + public static final String RESOURCE_VENDOR = "resourceVendor"; + public static final String RESOURCE_VENDOR_RELEASE = "resourceVendorRelease"; + public static final String RESOURCE_VENDOR_MODEL_NUMBER = "resourceVendorModelNumber"; + public static final String ORG_OPENECOMP_GROUPS_NETWORK_COLLECTION = "org.openecomp.groups.NetworkCollection"; + public static final String NETWORK_COLLECTION_FUNCTION = "network_collection_function"; + public static final String NETWORK_COLLECTION_DESCRIPTION = "network_collection_description"; //vfc instance group properties - public final static String VFC_INSTANCE_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup"; - public final static String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; - public final static String SUBINTERFACE_ROLE = "subinterface_role"; - public final static String VFC_INSTANCE_GROUP_FUNCTION = "vfc_instance_group_function"; + public static final String VFC_INSTANCE_GROUP_TYPE = "org.openecomp.groups.VfcInstanceGroup"; + public static final String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; + public static final String SUBINTERFACE_ROLE = "subinterface_role"; + public static final String VFC_INSTANCE_GROUP_FUNCTION = "vfc_instance_group_function"; + + public static final String FABRIC_CONFIGURATION_TYPE = "org.openecomp.nodes.FabricConfiguration"; + + public static final String RESOURCE_GROUP_TYPE = "org.openecomp.groups.ResourceInstanceGroup"; + public static final String RESOURCE_GROUP_CONTAINED_TYPE = "contained_resource_type"; + + public static final String VNF_GROUP = "VnfGroup"; + + public static final String NAMING_POLICY_TYPE = "org.openecomp.policies.External"; + + public static final String ECOMP_GENERATED_NAMING_PROPERTY = "ecomp_generated_naming"; } - - public ToscaParserImpl2() {} - public ServiceModel makeServiceModel(Path path, Service asdcServiceMetadata) throws SdcToscaParserException { + public ToscaParserImpl2(VidNotionsBuilder vidNotionsBuilder) { + this.vidNotionsBuilder = vidNotionsBuilder; + } + + public ServiceModel makeServiceModel(Path path, Service asdcServiceMetadata) throws SdcToscaParserException { ServiceModel serviceModel = new ServiceModel(); - SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); - ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(path.toFile().getAbsolutePath(),false); + ISdcCsarHelper sdcCsarHelper = getSdcCsarHelper(path); + List policiesTargets = extractNamingPoliciesTargets(sdcCsarHelper); serviceModel.setService(extractServiceFromCsar(asdcServiceMetadata, sdcCsarHelper)); serviceModel.setVolumeGroups(extractVolumeGroups(sdcCsarHelper)); serviceModel.setVfModules(extractVfModuleFromCsar(sdcCsarHelper)); - serviceModel.setVnfs(extractVnfsFromCsar(sdcCsarHelper)); - serviceModel.setConfigurations(extractPortMirroringConfigFromCsar(sdcCsarHelper)); - serviceModel.setServiceProxies(extractServiceProxyFromCsar(sdcCsarHelper)); - serviceModel.setNetworks(extractNetworksFromCsar(sdcCsarHelper)); - serviceModel.setPnfs(extractPnfsFromCsar(sdcCsarHelper)); - serviceModel.setCollectionResource(extractCRFromCsar(sdcCsarHelper)); + serviceModel.setVnfs(extractVnfsFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setConfigurations(extractPortMirroringConfigFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setServiceProxies(extractServiceProxyFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setNetworks(extractNetworksFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setPnfs(extractPnfsFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setCollectionResource(extractCRFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setFabricConfigurations(extractFabricConfigFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.setVnfGroups(extractVnfGroupsFromCsar(sdcCsarHelper, policiesTargets)); + serviceModel.getService().setVidNotions(vidNotionsBuilder.buildVidNotions(sdcCsarHelper, serviceModel)); return serviceModel; } + public ISdcCsarHelper getSdcCsarHelper(Path path) throws SdcToscaParserException { + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + return factory.getSdcCsarHelper(path.toFile().getAbsolutePath(), false); + } - - private org.onap.vid.model.Service extractServiceFromCsar(Service asdcServiceMetadata, ISdcCsarHelper csarHelper) throws SdcToscaParserException { - org.onap.vid.model.Service service = new org.onap.vid.model.Service(); + private org.onap.vid.model.Service extractServiceFromCsar(Service asdcServiceMetadata, ISdcCsarHelper csarHelper) { + org.onap.vid.model.Service service = new org.onap.vid.model.Service(); service.setName(csarHelper.getServiceMetadata().getValue(Constants.NAME)); service.setCategory(csarHelper.getServiceMetadata().getValue(Constants.CATEGORY)); @@ -104,21 +130,25 @@ public class ToscaParserImpl2 { service.setVersion(asdcServiceMetadata.getVersion()); service.setDescription(csarHelper.getServiceMetadata().getValue(Constants.DESCRIPTION)); service.setInputs(inputsListToInputsMap(csarHelper.getInputsWithAnnotations())); - service.setServiceEcompNaming(csarHelper.getServiceMetadata().getValue(Constants.ECOMP_GENERATED_NAMING)); + service.setServiceEcompNaming(isUserProvidingServiceNameOptional(csarHelper)); service.setServiceType(csarHelper.getServiceMetadata().getValue(Constants.SERVICE_TYPE)); service.setServiceRole(csarHelper.getServiceMetadata().getValue(Constants.SERVICE_ROLE)); service.setInstantiationType(validateInstantiationType(csarHelper)); return service; } - private Map extractCRFromCsar(ISdcCsarHelper sdcCsarHelper) { - List nodeTemplates = sdcCsarHelper.getServiceNodeTemplates(); - Map collectionResourceMap = new HashMap<>(); + private String isUserProvidingServiceNameOptional(ISdcCsarHelper csarHelper) { + return ToscaNamingPolicy.isUserProvidingServiceNameOptional(csarHelper); + } + + private Map extractCRFromCsar(ISdcCsarHelper sdcCsarHelper, List policiesTargets) { + List nodeTemplates = sdcCsarHelper.getServiceNodeTemplates(); + Map collectionResourceMap = new HashMap<>(); - for(NodeTemplate nodeTemplate: nodeTemplates){ - if(nodeTemplate.getMetaData().getValue(Constants.TYPE).equals(SdcTypes.CR.getValue())) { + for (NodeTemplate nodeTemplate : nodeTemplates) { + if ( nodeTemplate.getMetaData().getValue(Constants.TYPE).equals(SdcTypes.CR.getValue()) ) { CR cr = new CR(); - populateCrFromNodeTemplate(nodeTemplate, sdcCsarHelper, cr); + populateCrFromNodeTemplate(nodeTemplate, sdcCsarHelper, cr, policiesTargets); collectionResourceMap.put(nodeTemplate.getName(), cr); } } @@ -126,21 +156,39 @@ public class ToscaParserImpl2 { return collectionResourceMap; } - private void populateCrFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper sdcCsarHelper, CR cr) { - populateNodeFromNodeTemplate(nodeTemplate, sdcCsarHelper, cr); + private Map extractFabricConfigFromCsar(ISdcCsarHelper sdcCsarHelper, List policiesTargets) { + List nodeTemplates = sdcCsarHelper.getServiceNodeTemplates(); + Map fabricConfiguration = new HashMap<>(); + + for (NodeTemplate nodeTemplate : nodeTemplates) { + List nodeTemplateChildren = sdcCsarHelper.getNodeTemplateChildren(nodeTemplate); + for (NodeTemplate nodeTemplateChild : nodeTemplateChildren) { + if ( nodeTemplateChild.getType().equals(Constants.FABRIC_CONFIGURATION_TYPE) ) { + Node node = new Node(); + fabricConfiguration.put(nodeTemplateChild.getName(), populateNodeFromNodeTemplate(nodeTemplateChild, sdcCsarHelper, node, policiesTargets)); + } + } + + } + return fabricConfiguration; + } + + + private void populateCrFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper sdcCsarHelper, CR cr, List policiesTargets) { + populateNodeFromNodeTemplate(nodeTemplate, sdcCsarHelper, cr, policiesTargets); cr.setCustomizationUUID(nodeTemplate.getMetaData().getValue(Constants.CUSTOMIZATION_UUID)); cr.setCategory(nodeTemplate.getMetaData().getValue(Constants.CATEGORY)); - cr.setSubcategory(nodeTemplate.getMetaData().getValue(Constants.SUBCATEGORY)); - cr.setResourceVendor(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR)); - cr.setResourceVendorRelease(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR_RELEASE)); - cr.setResourceVendorModelNumber(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR_MODEL_NUMBER)); - cr.setNetworksCollection(getNetworksCollectionMapFromGroupsList(sdcCsarHelper, nodeTemplate)); + cr.setSubcategory(nodeTemplate.getMetaData().getValue(Constants.SUBCATEGORY)); + cr.setResourceVendor(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR)); + cr.setResourceVendorRelease(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR_RELEASE)); + cr.setResourceVendorModelNumber(nodeTemplate.getMetaData().getValue(Constants.RESOURCE_VENDOR_MODEL_NUMBER)); + cr.setNetworksCollection(getNetworksCollectionMapFromGroupsList(sdcCsarHelper, nodeTemplate)); } private Map getNetworksCollectionMapFromGroupsList(ISdcCsarHelper sdcCsarHelper, NodeTemplate nodeTemplate) { List groups = sdcCsarHelper.getGroupsOfOriginOfNodeTemplateByToscaGroupType(nodeTemplate, Constants.ORG_OPENECOMP_GROUPS_NETWORK_COLLECTION); - Map networksCollectionMap = new HashMap(); - for(Group group: groups){ + Map networksCollectionMap = new HashMap<>(); + for (Group group : groups) { networksCollectionMap.put(group.getName(), populateCollectionNetworkFromGroup(group, nodeTemplate)); } return networksCollectionMap; @@ -161,44 +209,46 @@ public class ToscaParserImpl2 { LinkedHashMap properties = group.getProperties(); Map nodeTemplateProperties = nodeTemplate.getProperties(); - String networkCollectionFunction = (String)((Map)(properties.get(Constants.NETWORK_COLLECTION_FUNCTION).getValue())).get(Constants.GET_INPUT); - String networkCollectionDescription = (String)((Map)(properties.get(Constants.NETWORK_COLLECTION_DESCRIPTION).getValue())).get(Constants.GET_INPUT); + String networkCollectionFunction = (String) ((Map) (properties.get(Constants.NETWORK_COLLECTION_FUNCTION).getValue())).get(Constants.GET_INPUT); + String networkCollectionDescription = (String) ((Map) (properties.get(Constants.NETWORK_COLLECTION_DESCRIPTION).getValue())).get(Constants.GET_INPUT); - networkCollection.getNetworkCollectionProperties().setNetworkCollectionDescription((String)nodeTemplateProperties.get(networkCollectionDescription).getValue()); - networkCollection.getNetworkCollectionProperties().setNetworkCollectionFunction((String)nodeTemplateProperties.get(networkCollectionFunction).getValue()); + networkCollection.getNetworkCollectionProperties().setNetworkCollectionDescription((String) nodeTemplateProperties.get(networkCollectionDescription).getValue()); + networkCollection.getNetworkCollectionProperties().setNetworkCollectionFunction((String) nodeTemplateProperties.get(networkCollectionFunction).getValue()); } - private Map extractVnfsFromCsar(ISdcCsarHelper csarHelper) { + private Map extractVnfsFromCsar(ISdcCsarHelper csarHelper, List policiesTargets) { List nodeTemplates = csarHelper.getServiceVfList(); - Map vnfsMaps = new HashMap(); + Map vnfsMaps = new HashMap<>(); for (NodeTemplate nodeTemplate : nodeTemplates) { VNF vnf = new VNF(); - populateNodeFromNodeTemplate(nodeTemplate, csarHelper, vnf); + populateNodeFromNodeTemplate(nodeTemplate, csarHelper, vnf, policiesTargets); vnf.setModelCustomizationName(nodeTemplate.getName()); vnf.setVfModules(getVfModulesFromVF(csarHelper, vnf.getCustomizationUuid())); vnf.setVolumeGroups(getVolumeGroupsFromVF(csarHelper, vnf.getCustomizationUuid())); vnf.setVfcInstanceGroups(getVfcInstanceGroup(csarHelper, nodeTemplate)); - + if (ToscaNamingPolicy.getEcompNamingValueForNode(nodeTemplate, "nf_naming").equals("true")) { + setEcompNamingProperty(vnf.getProperties(), "true"); + } vnfsMaps.put(nodeTemplate.getName(), vnf); } return vnfsMaps; } - private Map getVfcInstanceGroup(ISdcCsarHelper csarHelper, NodeTemplate nodeTemplate) { - List vfcList = csarHelper.getGroupsOfOriginOfNodeTemplateByToscaGroupType(nodeTemplate, Constants.VFC_INSTANCE_GROUP_TYPE); + private Map getVfcInstanceGroup(ISdcCsarHelper csarHelper, NodeTemplate nodeTemplate) { + List vfcList = csarHelper.getGroupsOfOriginOfNodeTemplateByToscaGroupType(nodeTemplate, Constants.VFC_INSTANCE_GROUP_TYPE); return vfcList.stream() - .collect(toMap(Group::getName, group -> populateVfcInstanceGroupFromGroup(group, csarHelper, nodeTemplate))); + .collect(toMap(Group::getName, group -> populateVfcInstanceGroupFromGroup(group, nodeTemplate))); } - private VfcInstanceGroup populateVfcInstanceGroupFromGroup(Group group, ISdcCsarHelper csarHelper, NodeTemplate nodeTemplate) { - VfcInstanceGroup vfcInstanceGroup = new VfcInstanceGroup(); - vfcInstanceGroup.setUuid(group.getMetadata().getValue(Constants.UUID)); - vfcInstanceGroup.setInvariantUuid(group.getMetadata().getValue(Constants.INVARIANT_UUID)); - vfcInstanceGroup.setVersion(group.getMetadata().getValue(Constants.VERSION)); - vfcInstanceGroup.setName(group.getMetadata().getValue(Constants.NAME)); - vfcInstanceGroup.setVfcInstanceGroupProperties(getVfcPropertiesFromGroup(nodeTemplate, group)); + private VfcInstanceGroup populateVfcInstanceGroupFromGroup(Group group, NodeTemplate nodeTemplate) { + VfcInstanceGroup vfcInstanceGroup = new VfcInstanceGroup(); + vfcInstanceGroup.setUuid(group.getMetadata().getValue(Constants.UUID)); + vfcInstanceGroup.setInvariantUuid(group.getMetadata().getValue(Constants.INVARIANT_UUID)); + vfcInstanceGroup.setVersion(group.getMetadata().getValue(Constants.VERSION)); + vfcInstanceGroup.setName(group.getMetadata().getValue(Constants.NAME)); + vfcInstanceGroup.setVfcInstanceGroupProperties(getVfcPropertiesFromGroup(nodeTemplate, group)); return vfcInstanceGroup; @@ -209,24 +259,24 @@ public class ToscaParserImpl2 { vfcInstanceGroupProperties.setVfcParentPortRole((String) group.getProperties().get(Constants.VFC_PARENT_PORT_ROLE).getValue()); vfcInstanceGroupProperties.setSubinterfaceRole((String) group.getProperties().get(Constants.SUBINTERFACE_ROLE).getValue()); - String networkCollectionFunction = (String)((Map)(group.getProperties().get(Constants.NETWORK_COLLECTION_FUNCTION).getValue())).get(Constants.GET_INPUT); - String vfcInstanceGroupFunction = (String)((Map)(group.getProperties().get(Constants.VFC_INSTANCE_GROUP_FUNCTION).getValue())).get(Constants.GET_INPUT); + String networkCollectionFunction = (String) ((Map) (group.getProperties().get(Constants.NETWORK_COLLECTION_FUNCTION).getValue())).get(Constants.GET_INPUT); + String vfcInstanceGroupFunction = (String) ((Map) (group.getProperties().get(Constants.VFC_INSTANCE_GROUP_FUNCTION).getValue())).get(Constants.GET_INPUT); - if(nodeTemplate.getProperties().get(networkCollectionFunction) != null) + if ( nodeTemplate.getProperties().get(networkCollectionFunction) != null ) vfcInstanceGroupProperties.setNetworkCollectionFunction((String) nodeTemplate.getProperties().get(networkCollectionFunction).getValue()); - if(nodeTemplate.getProperties().get(vfcInstanceGroupFunction) != null) + if ( nodeTemplate.getProperties().get(vfcInstanceGroupFunction) != null ) vfcInstanceGroupProperties.setVfcInstanceGroupFunction((String) nodeTemplate.getProperties().get(vfcInstanceGroupFunction).getValue()); return vfcInstanceGroupProperties; } - private Map extractPortMirroringConfigFromCsar(ISdcCsarHelper csarHelper) { - List nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); + private Map extractPortMirroringConfigFromCsar(ISdcCsarHelper csarHelper, List policiesTargets) { + List nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION);//TODO change to Map configMaps = new HashMap<>(); for (NodeTemplate nodeTemplate : nodeTemplates) { PortMirroringConfig pmConfig = new PortMirroringConfig(); - populateNodeFromNodeTemplate(nodeTemplate, csarHelper, pmConfig); + populateNodeFromNodeTemplate(nodeTemplate, csarHelper, pmConfig, policiesTargets); pmConfig.setModelCustomizationName(nodeTemplate.getName()); pmConfig.setRequirementAssignments(nodeTemplate.getRequirements()); @@ -236,38 +286,38 @@ public class ToscaParserImpl2 { } return configMaps; - } + } - private Map extractServiceProxyFromCsar(ISdcCsarHelper csarHelper) { + private Map extractServiceProxyFromCsar(ISdcCsarHelper csarHelper, List policiesTargets) { List nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY); - Map serviceProxies = new HashMap<>(); - for (NodeTemplate nodeTemplate: nodeTemplates) { - ServiceProxy serviceProxy = new ServiceProxy(); - populateNodeFromNodeTemplate(nodeTemplate, csarHelper, serviceProxy); + return nodeTemplates.stream() + .collect(toMap(NodeTemplate::getName, node -> getServiceProxyFromNodeTemplate(node, csarHelper, policiesTargets))); + } - Map metadata = nodeTemplate.getMetaData().getAllProperties(); - serviceProxy.setSourceModelUuid(metadata.get("sourceModelUuid")); - serviceProxy.setSourceModelInvariant(metadata.get("sourceModelInvariant")); - serviceProxy.setSourceModelName(metadata.get("sourceModelName")); + private ServiceProxy getServiceProxyFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, List policiesTargets) { + ServiceProxy serviceProxy = new ServiceProxy(); + populateNodeFromNodeTemplate(nodeTemplate, csarHelper, serviceProxy, policiesTargets); - serviceProxies.put(nodeTemplate.getName(), serviceProxy); - } + Map metadata = nodeTemplate.getMetaData().getAllProperties(); + serviceProxy.setSourceModelUuid(metadata.get("sourceModelUuid")); + serviceProxy.setSourceModelInvariant(metadata.get("sourceModelInvariant")); + serviceProxy.setSourceModelName(metadata.get("sourceModelName")); - return serviceProxies; + return serviceProxy; } - private void setSourceAndCollectorProxyNodes(ISdcCsarHelper csarHelper, PortMirroringConfig portMirroringConfig, NodeTemplate nodeTemplate) { - RequirementAssignments requirementAssignments = nodeTemplate.getRequirements(); + private void setSourceAndCollectorProxyNodes(ISdcCsarHelper csarHelper, PortMirroringConfig portMirroringConfig, NodeTemplate nodeTemplate) { + RequirementAssignments requirementAssignments = nodeTemplate.getRequirements(); List sourceNodes = getRequirementsNodesNames(requirementAssignments.getRequirementsByName("source").getAll()); portMirroringConfig.setSourceNodes(sourceNodes); List collectorNodes = getRequirementsNodesNames(requirementAssignments.getRequirementsByName("collector").getAll()); - if (!collectorNodes.isEmpty()) { // vprobe + if ( !collectorNodes.isEmpty() ) { // vprobe portMirroringConfig.setCollectorNodes(collectorNodes); } else { // pprobe - configuration by policy String collectorNodeName = csarHelper.getNodeTemplatePropertyLeafValue(nodeTemplate, "collector_node"); - if (collectorNodeName != null) { + if ( collectorNodeName != null ) { portMirroringConfig.setCollectorNodes(Arrays.asList(collectorNodeName)); portMirroringConfig.setConfigurationByPolicy(true); } @@ -277,8 +327,8 @@ public class ToscaParserImpl2 { private List getRequirementsNodesNames(List requirements) { List requirementsNodes = new ArrayList<>(); - if (requirements != null && requirements.size() > 0) { - requirementsNodes = requirements.stream().map(RequirementAssignment::getNodeTemplateName).collect(Collectors.toList()); + if ( !CollectionUtils.isEmpty(requirements) ) { + requirementsNodes = requirements.stream().map(RequirementAssignment::getNodeTemplateName).collect(toList()); } return requirementsNodes; @@ -301,26 +351,29 @@ public class ToscaParserImpl2 { return Boolean.valueOf(group.getPropertyValue(Constants.VOLUME_GROUP).toString()); } - private Map extractNetworksFromCsar(ISdcCsarHelper csarHelper) { + private Map extractNetworksFromCsar(ISdcCsarHelper csarHelper, List policiesTargets) { List nodeTemplates = csarHelper.getServiceVlList(); - Map networksMap = new HashMap(); + Map networksMap = new HashMap<>(); for (NodeTemplate nodeTemplate : nodeTemplates) { Network newNetwork = new Network(); - populateNodeFromNodeTemplate(nodeTemplate, csarHelper, newNetwork); + populateNodeFromNodeTemplate(nodeTemplate, csarHelper, newNetwork, policiesTargets); newNetwork.setModelCustomizationName(nodeTemplate.getName()); + if (ToscaNamingPolicy.getEcompNamingValueForNode(nodeTemplate, "exVL_naming").equals("true")) { + setEcompNamingProperty(newNetwork.getProperties(), "true"); + } networksMap.put(nodeTemplate.getName(), newNetwork); } return networksMap; - } + } - private Map extractPnfsFromCsar(ISdcCsarHelper csarHelper) { + private Map extractPnfsFromCsar(ISdcCsarHelper csarHelper, List policiesTargets) { List nodeTemplates = csarHelper.getServiceNodeTemplateBySdcType(SdcTypes.PNF); HashMap pnfHashMap = new HashMap<>(); for (NodeTemplate nodeTemplate : nodeTemplates) { Node pnf = new Node(); - populateNodeFromNodeTemplate(nodeTemplate, csarHelper, pnf); + populateNodeFromNodeTemplate(nodeTemplate, csarHelper, pnf, policiesTargets); pnfHashMap.put(nodeTemplate.getName(), pnf); } return pnfHashMap; @@ -352,13 +405,13 @@ public class ToscaParserImpl2 { Map inputs = new HashMap<>(); for (org.onap.sdc.toscaparser.api.parameters.Input input : inputList) { //Set only inputs without annotation to the service level - if(input.getAnnotations() == null) + if ( input.getAnnotations() == null ) inputs.put(input.getName(), convertInput(input, new org.onap.vid.asdc.beans.tosca.Input(), null)); } return inputs; } - private Node populateNodeFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, Node newNode) { + private Node populateNodeFromNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, Node newNode, List policiesTargets) { newNode.setCustomizationUuid(csarHelper.getNodeTemplateCustomizationUuid(nodeTemplate)); newNode.setDescription(nodeTemplate.getMetaData().getValue(Constants.DESCRIPTION)); newNode.setInvariantUuid(nodeTemplate.getMetaData().getValue(Constants.INVARIANT_UUID)); @@ -367,19 +420,21 @@ public class ToscaParserImpl2 { newNode.setVersion(nodeTemplate.getMetaData().getValue(Constants.VERSION)); newNode.setInputs(extractInputsAndCommandsForNodeTemplate(nodeTemplate, csarHelper, newNode)); newNode.setType(nodeTemplate.getMetaData().getValue(Constants.TYPE)); - Map propertiesMap = setPropertiesOfVnf(nodeTemplate.getPropertiesObjects()); + Map propertiesMap = nodeTemplate.getPropertiesObjects().stream() + .collect(toMap(Property::getName, p -> p.getValue().toString())); + setEcompNamingProperty(propertiesMap, String.valueOf(policiesTargets.contains(nodeTemplate.getName()))); newNode.setProperties(propertiesMap); return newNode; } - private VfModule populateVfModuleFromGroup(Group group, ISdcCsarHelper csarHelper){ + private VfModule populateVfModuleFromGroup(Group group, ISdcCsarHelper csarHelper) { VfModule vfModule = new VfModule(); extractBasicPropertiesForGroup(vfModule, group, csarHelper); vfModule.setVolumeGroupAllowed(isVolumeGroup(group)); return vfModule; } - private VolumeGroup populateVolumeGroupFromGroup(Group group, ISdcCsarHelper csarHelper){ + private VolumeGroup populateVolumeGroupFromGroup(Group group, ISdcCsarHelper csarHelper) { VolumeGroup volumeGroup = new VolumeGroup(); extractBasicPropertiesForGroup(volumeGroup, group, csarHelper); return volumeGroup; @@ -398,30 +453,39 @@ public class ToscaParserImpl2 { } - private Map extractVfInputsFromCsarByAnnotation(ISdcCsarHelper csarHelper, org.onap.vid.model.Group group) { + private Map extractVfInputsFromCsarByAnnotation(ISdcCsarHelper csarHelper, org.onap.vid.model.Group group) { Map inputMap = new HashMap<>(); - if(group.getProperties().getVfModuleLabel() != null){ + if ( group.getProperties().getVfModuleLabel() != null ) { List inputsList = csarHelper.getInputsWithAnnotations(); - for(Input input: inputsList){ - if(input.getAnnotations() != null){ - List annotationProperties = input.getAnnotations().get("source").getProperties(); - if(isInputMatchesToGroup(annotationProperties, group)){ - inputMap.put(input.getName(), new org.onap.vid.asdc.beans.tosca.Input(input ,annotationProperties)); - } - } + for (Input input : inputsList) { + extractVfModuleInput(group, inputMap, input); } } return inputMap; } + private void extractVfModuleInput(org.onap.vid.model.Group group, Map inputMap, Input input) { + if ( input.getAnnotations() != null ) { + List annotationProperties = input.getAnnotations().get("source").getProperties(); + if ( isInputMatchesToGroup(annotationProperties, group) ) { + final org.onap.vid.asdc.beans.tosca.Input vfModuleInput = new org.onap.vid.asdc.beans.tosca.Input(input, annotationProperties); + if ( vfModuleInput.getInputProperties() != null && vfModuleInput.getInputProperties().getParamName() != null ) { + inputMap.put(vfModuleInput.getInputProperties().getParamName(), vfModuleInput); + } else { + inputMap.put(input.getName(), vfModuleInput); + } + } + } + } + - private boolean isInputMatchesToGroup(List annotationProperties, org.onap.vid.model.Group group){ - for(Property property: annotationProperties){ - if(property.getName().equals(VF_MODULE_LABEL)){ + private boolean isInputMatchesToGroup(List annotationProperties, org.onap.vid.model.Group group) { + for (Property property : annotationProperties) { + if ( property.getName().equals(VF_MODULE_LABEL) ) { final Object values = property.getValue(); final String vfModuleLabel = group.getProperties().getVfModuleLabel(); - if (values instanceof List) { - if (listContainsAsString((List) values, vfModuleLabel)) return true; + if ( values instanceof List ) { + if ( listContainsAsString((List) values, vfModuleLabel) ) return true; } else { return getPropertyValueAsString(property).equals(vfModuleLabel); } @@ -432,7 +496,7 @@ public class ToscaParserImpl2 { private boolean listContainsAsString(List list, String value) { for (Object v : list) { - if (StringUtils.equals(v.toString(), value)) { + if ( StringUtils.equals(v.toString(), value) ) { return true; } } @@ -443,37 +507,45 @@ public class ToscaParserImpl2 { return removeSquareBrackets(property.getValue().toString()); } - private String removeSquareBrackets(String stringWithSquareBrackets){ + private String removeSquareBrackets(String stringWithSquareBrackets) { return stringWithSquareBrackets.replaceAll("(^\\[|\\]$)", ""); } - private GroupProperties extractVfModuleProperties(Group group, ISdcCsarHelper csarHelper){ + private GroupProperties extractVfModuleProperties(Group group, ISdcCsarHelper csarHelper) { GroupProperties vfModuleProperties = new GroupProperties(); - if(csarHelper.getGroupPropertyAsObject(group, Constants.MIN_VF_MODULE_INSTANCES) != null) - vfModuleProperties.setMinCountInstances((Integer)csarHelper.getGroupPropertyAsObject(group, Constants.MIN_VF_MODULE_INSTANCES)); - if(csarHelper.getGroupPropertyAsObject(group, Constants.MAX_VF_MODULE_INSTANCES) != null) - vfModuleProperties.setMaxCountInstances((Integer)csarHelper.getGroupPropertyAsObject(group, Constants.MAX_VF_MODULE_INSTANCES)); - if(csarHelper.getGroupPropertyAsObject(group, Constants.INITIAL_COUNT) != null) - vfModuleProperties.setInitialCount((Integer)csarHelper.getGroupPropertyAsObject(group, Constants.INITIAL_COUNT)); - if(csarHelper.getGroupPropertyAsObject(group, VF_MODULE_LABEL) != null) + if ( csarHelper.getGroupPropertyAsObject(group, Constants.MIN_VF_MODULE_INSTANCES) != null ) + vfModuleProperties.setMinCountInstances((Integer) csarHelper.getGroupPropertyAsObject(group, Constants.MIN_VF_MODULE_INSTANCES)); + if ( csarHelper.getGroupPropertyAsObject(group, Constants.MAX_VF_MODULE_INSTANCES) != null ) + vfModuleProperties.setMaxCountInstances((Integer) csarHelper.getGroupPropertyAsObject(group, Constants.MAX_VF_MODULE_INSTANCES)); + if ( csarHelper.getGroupPropertyAsObject(group, Constants.INITIAL_COUNT) != null ) + vfModuleProperties.setInitialCount((Integer) csarHelper.getGroupPropertyAsObject(group, Constants.INITIAL_COUNT)); + if ( csarHelper.getGroupPropertyAsObject(group, VF_MODULE_LABEL) != null ) vfModuleProperties.setVfModuleLabel((String) csarHelper.getGroupPropertyAsObject(group, VF_MODULE_LABEL)); + vfModuleProperties.setBaseModule(isModuleTypeIsBaseObjectSafe(csarHelper.getGroupPropertyAsObject(group, Constants.VF_MODULE_TYPE))); return vfModuleProperties; } + public static boolean isModuleTypeIsBaseObjectSafe(Object vfModuleTypeValue) { + return (vfModuleTypeValue instanceof String) && (isModuleTypeIsBase((String) vfModuleTypeValue)); + } + + protected static boolean isModuleTypeIsBase(String vfModuleTypeValue) { + return "Base".equalsIgnoreCase(vfModuleTypeValue); + } - private Map extractInputsAndCommandsForNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, Node newNode){ + private Map extractInputsAndCommandsForNodeTemplate(NodeTemplate nodeTemplate, ISdcCsarHelper csarHelper, Node newNode) { Map inputMap = new HashMap<>(); Map commandPropertyMap = new HashMap<>(); List inputs = csarHelper.getServiceInputs(); - Map properties = csarHelper.filterNodeTemplatePropertiesByValue(nodeTemplate, FilterType.CONTAINS, Constants.GET_INPUT); + Map properties = csarHelper.filterNodeTemplatePropertiesByValue(nodeTemplate, FilterType.CONTAINS, Constants.GET_INPUT); for (Map.Entry property : properties.entrySet()) { String inputKey = property.getValue(); String key = extractInputValue(inputKey); - for (Input input: inputs){ - if(input.getName().equals(key)){ + for (Input input : inputs) { + if ( input.getName().equals(key) ) { org.onap.vid.asdc.beans.tosca.Input localInput = new org.onap.vid.asdc.beans.tosca.Input(); localInput = convertInput(input, localInput, nodeTemplate); String name = property.getKey(); @@ -487,7 +559,7 @@ public class ToscaParserImpl2 { } private String extractInputValue(String inputKey) { - return inputKey.substring(inputKey.indexOf(":") + 1); + return inputKey.substring(inputKey.indexOf(':') + 1); } private org.onap.vid.asdc.beans.tosca.Input convertInput(Input parserInput, org.onap.vid.asdc.beans.tosca.Input localInput, NodeTemplate nodeTemplate){ @@ -497,7 +569,7 @@ public class ToscaParserImpl2 { localInput.setType(parserInput.getType()); localInput.setConstraints(parserInput.getConstraints()); // localInput.setentry_schema() - + //if inputs of inner nodeTemplate - tell its details if(nodeTemplate != null) { Metadata metadata = nodeTemplate.getMetaData(); @@ -506,11 +578,11 @@ public class ToscaParserImpl2 { localInput.setTemplateInvariantUUID(metadata.getValue("invariantUUID")); localInput.setTemplateCustomizationUUID(metadata.getValue("customizationUUID")); } - + return localInput; } - private CommandProperty extractCommands(String displayName, String inputName){ + private CommandProperty extractCommands(String displayName, String inputName) { CommandProperty commandProperty = new CommandProperty(); commandProperty.setDisplayName(displayName); commandProperty.setCommand(Constants.GET_INPUT); @@ -518,19 +590,8 @@ public class ToscaParserImpl2 { return commandProperty; } - private Map setPropertiesOfVnf(List properties) { - Map propertiesMap = new HashMap(); - for (Property property : properties) { - //special handling to necessary sub-property "ecomp_generated_naming" - if(property.getName().equals("nf_naming")){ - final Object ecompGeneratedNaming = ((Map) (property.getValue())).get("ecomp_generated_naming"); - if (ecompGeneratedNaming != null) { - propertiesMap.put("ecomp_generated_naming", ecompGeneratedNaming.toString()); - } - } - propertiesMap.put(property.getName(), property.getValue().toString()); - } - return propertiesMap; + private void setEcompNamingProperty(Map propertiesMap, String isUserProvidingVnfNameOptional) { + propertiesMap.put(Constants.ECOMP_GENERATED_NAMING_PROPERTY, isUserProvidingVnfNameOptional); } private String validateInstantiationType(ISdcCsarHelper csarHelper){ @@ -545,5 +606,43 @@ public class ToscaParserImpl2 { return validatedInstantiationType; } + private Map extractVnfGroupsFromCsar(ISdcCsarHelper csarHelper, List policiesTargets) { + List resourceGroups = csarHelper.getGroupsOfTopologyTemplateByToscaGroupType(Constants.RESOURCE_GROUP_TYPE); + + return resourceGroups.stream() + .filter(group -> group.getProperties().get(Constants.RESOURCE_GROUP_CONTAINED_TYPE).getValue().equals("VF")) + .collect(toMap(Group::getName, group -> parseResourceGroup(group, csarHelper, policiesTargets))); + } + + private ResourceGroup parseResourceGroup(Group group, ISdcCsarHelper csarHelper, List policiesTargets) { + return new ResourceGroup( + Constants.VNF_GROUP, + group.getMetadata().getValue(Constants.INVARIANT_UUID), + group.getMetadata().getValue(Constants.UUID), + group.getMetadata().getValue(Constants.VERSION), + group.getMetadata().getValue(Constants.NAME), + group.getMetadata().getValue(Constants.NAME), + getPropertiesOfResourceGroup(group.getProperties(), policiesTargets.contains(group.getName())), + csarHelper.getGroupMembersFromTopologyTemplate(group.getName()).stream() + .collect(toMap(NodeTemplate::getName, node -> getServiceProxyFromNodeTemplate(node, csarHelper, policiesTargets))) + ); + } + + private Map getPropertiesOfResourceGroup(Map properties, boolean hasPolicyTarget) { + Map propertiesMap = properties.entrySet().stream() + .collect(toMap(Map.Entry::getKey, e -> e.getValue().getValue())); + propertiesMap.put(Constants.ECOMP_GENERATED_NAMING_PROPERTY, String.valueOf(hasPolicyTarget)); + return propertiesMap; + } + + public List extractNamingPoliciesTargets(ISdcCsarHelper csarHelper) { + List policies = csarHelper.getPoliciesOfTopologyTemplateByToscaPolicyType(Constants.NAMING_POLICY_TYPE); + return policies.stream() + .filter(policy -> policy.getProperties().get(Constants.TYPE) != null && + policy.getProperties().get(Constants.TYPE).getValue() != null && + StringUtils.equalsIgnoreCase(policy.getProperties().get(Constants.TYPE).getValue().toString(), "naming")) + .flatMap(policy -> policy.getTargets().stream()) + .collect(toList()); + } } \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java new file mode 100644 index 00000000..ca0607b8 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/VidNotionsBuilder.java @@ -0,0 +1,130 @@ +package org.onap.vid.asdc.parser; + +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.VidNotions; +import org.onap.vid.properties.Features; +import org.togglz.core.manager.FeatureManager; + +import static org.apache.commons.lang3.StringUtils.equalsAnyIgnoreCase; +import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; + +public class VidNotionsBuilder { + + private final FeatureManager featureManager; + + public VidNotionsBuilder(FeatureManager featureManager) { + this.featureManager = featureManager; + } + + public VidNotions buildVidNotions(ISdcCsarHelper csarHelper, ServiceModel serviceModel) { + final VidNotions.InstantiationUI instantiationUI = suggestInstantiationUI(csarHelper); + + return new VidNotions(instantiationUI, suggestModelCategory(csarHelper), suggestViewEditUI(csarHelper, serviceModel)); + } + + //UI route a-la-carte services to old UI only if InstantiationUI is LEGACY + //So any other value for InstantiationUI other than LEGACY make UI to route + //a-la-carte services to new UI + VidNotions.InstantiationUI suggestInstantiationUI(ISdcCsarHelper csarHelper) { + if(featureManager.isActive(Features.FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI) && isALaCarte(csarHelper)) { + return VidNotions.InstantiationUI.ANY_ALACARTE_NEW_UI; + } + if (featureManager.isActive(Features.FLAG_1902_VNF_GROUPING) && isGrouping(csarHelper)) { + return VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING; + } + if (featureManager.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)) { + if (isUuidExactlyHardCoded1ffce89fef3f(csarHelper)) { + return VidNotions.InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de; + } else if (isALaCarte(csarHelper) && hasAnyNetworkWithPropertyNetworkTechnologyEqualsStandardSriovOrOvs(csarHelper)) { + return VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS; + } else if (isALaCarte(csarHelper) && hasFabricConfiguration(csarHelper)) { + return VidNotions.InstantiationUI.SERVICE_WITH_FABRIC_CONFIGURATION; + } + } + + return VidNotions.InstantiationUI.LEGACY; + + } + + VidNotions.ModelCategory suggestModelCategory(ISdcCsarHelper csarHelper) { + if (isALaCarte(csarHelper) && hasAnyNetworkWithPropertyNetworkTechnologyEqualsStandardSriovOrOvs(csarHelper)){ + return VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL; + } else if(isALaCarte(csarHelper) && hasFabricConfiguration(csarHelper)) { + return VidNotions.ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL; + } else { + return VidNotions.ModelCategory.OTHER; + } + } + + VidNotions.InstantiationUI suggestViewEditUI(ISdcCsarHelper csarHelper, ServiceModel serviceModel) { + if (!featureManager.isActive(Features.FLAG_ASYNC_INSTANTIATION)){ + return VidNotions.InstantiationUI.LEGACY; + } + if (featureManager.isActive(Features.FLAG_1902_VNF_GROUPING) && isGrouping(csarHelper)) { + return VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING; + } + + if (featureManager.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)) { + if (isMacro(serviceModel) && !isMacroExcludedFromAsyncFlow(serviceModel)) { + return VidNotions.InstantiationUI.MACRO_SERVICE; + } + VidNotions.InstantiationUI instantiationUISuggestion = suggestInstantiationUI(csarHelper); + if (instantiationUISuggestion!=VidNotions.InstantiationUI.LEGACY) { + return instantiationUISuggestion; + } + } + + return VidNotions.InstantiationUI.LEGACY; + } + + private boolean isMacro(ServiceModel serviceModel) { + return ToscaParserImpl2.Constants.MACRO.equals(serviceModel.getService().getInstantiationType()); + } + + private boolean isUuidExactlyHardCoded1ffce89fef3f(ISdcCsarHelper csarHelper) { + return equalsIgnoreCase( + csarHelper.getServiceMetadata().getValue(ToscaParserImpl2.Constants.UUID), "95eb2c44-bff2-4e8b-ad5d-8266870b7717"); + } + + private boolean hasAnyNetworkWithPropertyNetworkTechnologyEqualsStandardSriovOrOvs(ISdcCsarHelper csarHelper) { + return hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "network_technology","Standard-SR-IOV","OVS") ; + } + + boolean hasFabricConfiguration(ISdcCsarHelper csarHelper) { + return csarHelper.getServiceNodeTemplates().stream() + .flatMap(nodeTemplate -> csarHelper.getNodeTemplateChildren(nodeTemplate).stream()) + .anyMatch(child -> child.getType().equals(ToscaParserImpl2.Constants.FABRIC_CONFIGURATION_TYPE)); + } + + boolean hasAnyNetworkWithPropertyEqualsToAnyOf(ISdcCsarHelper csarHelper, String propertyName, String... propertyValues) { + return csarHelper + .getServiceVlList().stream() + .map(NodeTemplate::getProperties) + .flatMap(props -> props.entrySet().stream()) + .filter(prop -> equalsIgnoreCase(prop.getKey(), propertyName)) + // getValue().getValue() because value is Entry, where it's inner value is what we're looking for + .anyMatch(prop -> equalsAnyIgnoreCase(prop.getValue().getValue().toString(), propertyValues)); + } + + boolean isALaCarte(ISdcCsarHelper csarHelper) { + final String instantiationType = csarHelper.getServiceMetadata().getValue(ToscaParserImpl2.Constants.INSTANTIATION_TYPE); + return StringUtils.equalsIgnoreCase(instantiationType, ToscaParserImpl2.Constants.A_LA_CARTE); + } + + boolean isMacroExcludedFromAsyncFlow(ServiceModel serviceModel) { + return (MapUtils.isNotEmpty(serviceModel.getPnfs()) || + MapUtils.isNotEmpty(serviceModel.getCollectionResource()) || + (MapUtils.isNotEmpty(serviceModel.getNetworks()) && !featureManager.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION))); + + + } + + private boolean isGrouping(ISdcCsarHelper csarHelper) { + final String serviceRole = csarHelper.getServiceMetadata().getValue(ToscaParserImpl2.Constants.SERVICE_ROLE); + return StringUtils.equalsIgnoreCase(serviceRole, ToscaParserImpl2.Constants.GROUPING); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/ChangeManagementRequest.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/ChangeManagementRequest.java index 1d866eec..abfcd6f3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/ChangeManagementRequest.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/ChangeManagementRequest.java @@ -1,13 +1,10 @@ package org.onap.vid.changeManagement; -import java.util.List; +import com.fasterxml.jackson.annotation.*; + import java.util.HashMap; +import java.util.List; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({ "requestDetails", @@ -17,17 +14,17 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; public class ChangeManagementRequest { public static class MsoChangeManagementRequest { - public final static String SOFTWARE_UPDATE = "inPlaceSoftwareUpdate"; + public static final String SOFTWARE_UPDATE = "inPlaceSoftwareUpdate"; public static final String REPLACE = "replace"; - public final static String CONFIG_UPDATE = "applyUpdatedConfig"; + public static final String CONFIG_UPDATE = "applyUpdatedConfig"; } - public final static String VNF_IN_PLACE_SOFTWARE_UPDATE = "vnf in place software update"; + public static final String VNF_IN_PLACE_SOFTWARE_UPDATE = "vnf in place software update"; public static final String UPDATE = "update"; public static final String REPLACE = "replace"; - public final static String CONFIG_UPDATE = "vnf config update"; - public final static String SCALE_OUT = "vnf scale out"; + public static final String CONFIG_UPDATE = "vnf config update"; + public static final String SCALE_OUT = "vnf scale out"; @JsonProperty("requestDetails") private List requestDetails; @@ -36,7 +33,7 @@ public class ChangeManagementRequest { private String requestType; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonProperty("requestDetails") public List getRequestDetails() { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/CloudConfiguration.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/CloudConfiguration.java index 43d6a6a0..b7435795 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/CloudConfiguration.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/CloudConfiguration.java @@ -1,13 +1,9 @@ package org.onap.vid.changeManagement; +import com.fasterxml.jackson.annotation.*; + import java.util.HashMap; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ @@ -20,7 +16,7 @@ public class CloudConfiguration { @JsonProperty("tenantId") private String tenantId; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonProperty("lcpCloudRegionId") public String getLcpCloudRegionId() { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/LeanCloudConfiguration.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/LeanCloudConfiguration.java index 6011c7eb..480ef125 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/LeanCloudConfiguration.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/LeanCloudConfiguration.java @@ -1,20 +1,27 @@ package org.onap.vid.changeManagement; +import com.fasterxml.jackson.annotation.JsonInclude; +import org.onap.vid.mso.model.CloudConfiguration; + /** * Created by Oren on 9/5/17. */ +@JsonInclude(JsonInclude.Include.NON_EMPTY) public class LeanCloudConfiguration { public LeanCloudConfiguration() { } - public LeanCloudConfiguration(org.onap.vid.domain.mso.CloudConfiguration cloudConfiguration) { + public LeanCloudConfiguration(CloudConfiguration cloudConfiguration) { this.tenantId = cloudConfiguration.getTenantId(); this.lcpCloudRegionId = cloudConfiguration.getLcpCloudRegionId(); + this.cloudOwner = cloudConfiguration.getCloudOwner(); } public String lcpCloudRegionId; public String tenantId; + public String cloudOwner; + } diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfo.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfo.java index 8f44a4bf..ebb0ba3e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfo.java @@ -1,12 +1,9 @@ package org.onap.vid.changeManagement; + +import com.fasterxml.jackson.annotation.*; + import java.util.HashMap; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ @@ -24,7 +21,7 @@ public class ModelInfo { } - public ModelInfo(org.onap.vid.domain.mso.ModelInfo modelInfo){ + public ModelInfo(org.onap.vid.mso.model.ModelInfo modelInfo){ this.setModelType(modelInfo.getModelType().toString()); this.setModelInvariantId(modelInfo.getModelInvariantId()); this.setModelVersionId(modelInfo.getModelNameVersionId()); @@ -50,7 +47,7 @@ public class ModelInfo { @JsonProperty("modelCustomizationId") private String modelCustomizationId; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonProperty("modelType") public String getModelType() { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfoOfRelatedInstance.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfoOfRelatedInstance.java index 7e876098..7c9b709d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfoOfRelatedInstance.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/ModelInfoOfRelatedInstance.java @@ -1,13 +1,9 @@ package org.onap.vid.changeManagement; +import com.fasterxml.jackson.annotation.*; + import java.util.HashMap; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ @@ -37,7 +33,7 @@ public class ModelInfoOfRelatedInstance { @JsonProperty("modelCustomizationId") private String modelCustomizationId; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonProperty("modelType") public String getModelType() { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java index 8e1a4083..25951f25 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestDetails.java @@ -57,4 +57,9 @@ public class RequestDetails extends org.onap.vid.mso.rest.RequestDetails{ public boolean equals(Object other) { return super.equals(other); } + + @Override + public int hashCode() { + return super.hashCode(); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestInfo.java index 4aa3724a..8ecb39e4 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/RequestInfo.java @@ -1,13 +1,9 @@ package org.onap.vid.changeManagement; +import com.fasterxml.jackson.annotation.*; + import java.util.HashMap; import java.util.Map; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ @@ -23,7 +19,7 @@ public class RequestInfo { @JsonProperty("requestorId") private String requestorId; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonProperty("source") public String getSource() { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/UpdateRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/UpdateRequestInfo.java index 024e9c3c..394c8ffa 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/UpdateRequestInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/UpdateRequestInfo.java @@ -1,6 +1,6 @@ package org.onap.vid.changeManagement; -import org.onap.vid.domain.mso.*; +import org.onap.vid.mso.model.RequestInfo; /** * Created by Oren on 9/5/17. @@ -11,7 +11,7 @@ public class UpdateRequestInfo { } - public UpdateRequestInfo(org.onap.vid.domain.mso.RequestInfo requestInfo) { + public UpdateRequestInfo(RequestInfo requestInfo) { this.requestorId = requestInfo.getRequestorId(); this.suppressRollback = requestInfo.getSuppressRollback(); this.source = requestInfo.getSource(); diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetails.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetails.java index 5cc2f4d3..c5a06711 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetails.java @@ -1,7 +1,6 @@ package org.onap.vid.changeManagement; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.MoreObjects; public class VnfDetails { diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java index 4e172a10..9971df91 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/VnfDetailsWithWorkflows.java @@ -33,7 +33,13 @@ public class VnfDetailsWithWorkflows extends VnfDetails { this.workflows = workflows; } - public boolean equals(VnfDetailsWithWorkflows vnfDetailsWithWorkflows){ - return this.workflows.equals(vnfDetailsWithWorkflows.getWorkflows()); + @Override + public boolean equals(Object o) { + return super.equals(o); + } + + @Override + public int hashCode() { + return super.hashCode(); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/changeManagement/WorkflowsDetail.java b/vid-app-common/src/main/java/org/onap/vid/changeManagement/WorkflowsDetail.java index e833ecb2..0883411e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/changeManagement/WorkflowsDetail.java +++ b/vid-app-common/src/main/java/org/onap/vid/changeManagement/WorkflowsDetail.java @@ -1,7 +1,6 @@ package org.onap.vid.changeManagement; import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.MoreObjects; public class WorkflowsDetail { diff --git a/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java b/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java index 8f0d59fd..b9b2c8b7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java @@ -29,8 +29,6 @@ import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.ServletContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; -import java.text.DateFormat; -import java.text.SimpleDateFormat; /** * General HTTP client. @@ -45,9 +43,6 @@ public class HttpBasicClient{ /** The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpBasicClient.class); - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** * Obtain a basic HTTP client . * diff --git a/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java b/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java deleted file mode 100644 index 5afa0359..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/client/HttpsBasicClient.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.client; - -import org.eclipse.jetty.util.security.Password; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.onap.vid.properties.VidProperties; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - - /** - * General SSL client using the VID tomcat keystore. It doesn't use client certificates. - */ - -public class HttpsBasicClient{ - - /** The logger. */ - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsBasicClient.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** - * Retrieve an SSL client. - * - * @return Client The SSL client - * @throws Exception the exception - */ - public static Client getClient() { - String methodName = "getClient"; - ClientConfig config = new ClientConfig(); - - SSLContext ctx = null; - - try { - - config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); - - String truststore_path = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_FILENAME); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " truststore_path=" + truststore_path); - String truststore_password = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_PASSWD_X); - - - String decrypted_truststore_password = Password.deobfuscate(truststore_password); - //logger.debug(dateFormat.format(new Date()) + " " + methodName + " decrypted_truststore_password=" + decrypted_truststore_password); - - File tr = new File (truststore_path); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + " " + methodName + " absolute truststore path=" + tr.getAbsolutePath()); - - System.setProperty("javax.net.ssl.trustStore", truststore_path); - System.setProperty("javax.net.ssl.trustStorePassword", decrypted_truststore_password); - HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ - public boolean verify(String string,SSLSession ssls) { - return true; - } - }); - - //May need to make the algorithm a parameter. MSO requires TLSv1.1 or TLSv1.2 - ctx = SSLContext.getInstance("TLSv1.2"); - - ctx.init(null, null, null); - //config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, - // new HTTPSProperties( , ctx)); - - return ClientBuilder.newBuilder() - .sslContext(ctx) - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }).withConfig(config) - .build() - .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); - - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting", e); - return null; - } - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java index 9e50c445..ed1401c1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java @@ -42,11 +42,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; +import java.security.*; import java.security.cert.CertificateException; import java.util.Map; @@ -170,7 +166,7 @@ public class SyncRestClient implements SyncRestClientInterface { } private ObjectMapper defaultObjectMapper() { - org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper(); + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); return new ObjectMapper() { @Override diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/AaiController.java b/vid-app-common/src/main/java/org/onap/vid/controller/AaiController.java new file mode 100644 index 00000000..c099db80 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/AaiController.java @@ -0,0 +1,731 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.AaiGetVnfResponse; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; +import org.onap.vid.aai.ServiceInstancesSearchResults; +import org.onap.vid.aai.SubscriberFilteredResults; +import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion; +import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; +import org.onap.vid.aai.model.AaiGetPnfs.Pnf; +import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.model.VersionByInvariantIdsRequest; +import org.onap.vid.roles.Role; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.roles.RoleValidator; +import org.onap.vid.services.AaiService; +import org.onap.vid.utils.Unchecked; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.HandlerMapping; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.QueryParam; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.onap.vid.utils.Logging.getMethodName; + +/** + * Controller to handle a&ai requests. + */ + +@RestController +public class AaiController extends RestrictedBaseController { + + /** + * The from app id. + */ + private String fromAppId = "VidAaiController"; + /** + * The logger. + */ + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiController.class); + /** + * The model. + */ + private Map model = new HashMap<>(); + /** + * The servlet context. + */ + @Autowired + private ServletContext servletContext; + /** + * aai service + */ + @Autowired + private AaiService aaiService; + @Autowired + private RoleProvider roleProvider; + + @Autowired + private AAIRestInterface aaiRestInterface; + + /** + * Welcome method. + * + * @param request the request + * @return ModelAndView The view + */ + @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== AaiController welcome start"); + return new ModelAndView(getViewName()); + } + + @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET) + public ResponseEntity getAicZones(HttpServletRequest request) throws IOException { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== getAicZones controller start"); + AaiResponse response = aaiService.getAaiZones(); + return aaiResponseToResponseEntity(response); + } + + @RequestMapping(value = {"/aai_get_aic_zone_for_pnf/{globalCustomerId}/{serviceType}/{serviceId}"}, method = RequestMethod.GET) + public ResponseEntity getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId ,@PathVariable("serviceType") String serviceType , @PathVariable("serviceId") String serviceId ,HttpServletRequest request) throws IOException { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== getAicZoneForPnf controller start"); + AaiResponse response = aaiService.getAicZoneForPnf(globalCustomerId , serviceType , serviceId); + return aaiResponseToResponseEntity(response); + } + + @RequestMapping(value = {"/aai_get_instance_groups_by_vnf_instance_id/{vnfInstanceId}"}, method = RequestMethod.GET) + public ResponseEntity getInstanceGroupsByVnfInstanceId(@PathVariable("vnfInstanceId") String vnfInstanceId ,HttpServletRequest request) throws IOException { + AaiResponse response = aaiService.getInstanceGroupsByVnfInstanceId(vnfInstanceId); + return aaiResponseToResponseEntity(response); + } + /** + * Get services from a&ai. + * + * @return ResponseEntity The response entity with the logged in user uuid. + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET) + public ResponseEntity getUserID(HttpServletRequest request) { + + String userId = ControllersUtils.extractUserId(request); + + return new ResponseEntity<>(userId, HttpStatus.OK); + } + + /** + * Get services from a&ai. + * + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity doGetServices(HttpServletRequest request) throws IOException { + RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request)); + + AaiResponse subscriberList = aaiService.getServices(roleValidator); + return aaiResponseToResponseEntity(subscriberList); + } + + + @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST) + public ResponseEntity getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) { + Response result = aaiService.getVersionByInvariantId(versions.versions); + + return new ResponseEntity<>(result.readEntity(String.class), HttpStatus.OK); + } + + + private ResponseEntity aaiResponseToResponseEntity(AaiResponse aaiResponseData) + throws IOException { + ResponseEntity responseEntity; + ObjectMapper objectMapper = new ObjectMapper(); + if (aaiResponseData.getHttpCode() == 200) { + responseEntity = new ResponseEntity<>(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK); + } else { + responseEntity = new ResponseEntity<>(aaiResponseData.getErrorMessage(), HttpStatus.valueOf(aaiResponseData.getHttpCode())); + } + return responseEntity; + } + + /** + * Lookup single service instance in a&ai. Get the service-subscription and customer, too, i guess? + * + * @param serviceInstanceId the service instance Id + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) { + Response resp = null; + + if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) { + resp = doAaiGet( + "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + + serviceInstanceId, false); + } else { + resp = doAaiGet( + "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:" + + serviceInstanceId, false); + } + return convertResponseToResponseEntity(resp); + } + + /** + * Get services from a&ai. + * + * @param globalCustomerId the global customer id + * @param serviceSubscriptionId the service subscription id + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity doGetServices(@PathVariable("global-customer-id") String globalCustomerId, + @PathVariable("service-subscription-id") String serviceSubscriptionId) { + Response resp = doAaiGet("business/customers/customer/" + globalCustomerId + + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false); + return convertResponseToResponseEntity(resp); + } + + /** + * Obtain the subscriber list from a&ai. + * + * @param fullSet the full set + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity doGetSubscriberList(HttpServletRequest request, @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException { + return getFullSubscriberList(request); + } + + /** + * Obtain the Target Prov Status from the System.Properties file. + * + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getTargetProvStatus() { + String p = SystemProperties.getProperty("aai.vnf.provstatus"); + return new ResponseEntity<>(p, HttpStatus.OK); + } + + + /** + * Obtain the Target Prov Status from the System.Properties file. + * + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/get_operational_environments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public AaiResponse getOperationalEnvironments(@RequestParam(value="operationalEnvironmentType", required = false) String operationalEnvironmentType, + @RequestParam(value="operationalEnvironmentStatus", required = false) String operationalEnvironmentStatus) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({}, {})", getMethodName(), operationalEnvironmentType, operationalEnvironmentStatus); + AaiResponse response = aaiService.getOperationalEnvironments(operationalEnvironmentType,operationalEnvironmentStatus); + if (response.getHttpCode() != 200) { + String errorMessage = getAaiErrorMessage(response.getErrorMessage()); + if(errorMessage != null) { + response = new AaiResponse<>(response.getT(), errorMessage, response.getHttpCode()); + } + } + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); + return response; + } + + /** + * Obtain the full subscriber list from a&ai. + *

+ * g @return ResponseEntity The response entity + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getFullSubscriberList(HttpServletRequest request) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + ResponseEntity responseEntity; + RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request)); + SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator); + if (subscriberList.getHttpCode() == 200) { + responseEntity = new ResponseEntity<>(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK); + } else { + responseEntity = new ResponseEntity<>(subscriberList.getErrorMessage(), HttpStatus.valueOf(subscriberList.getHttpCode())); + } + + + return responseEntity; + } + + + @RequestMapping(value = "/get_vnf_data_by_globalid_and_service_type/{globalCustomerId}/{serviceType}", + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity getVnfDataByGlobalIdAndServiceType(HttpServletRequest request, + @PathVariable("globalCustomerId") String globalCustomerId, + @PathVariable("serviceType") String serviceType) throws IOException { + + AaiResponse resp = aaiService.getVNFData(globalCustomerId, serviceType); + return aaiResponseToResponseEntity(resp); + } + + + /** + * Refresh the subscriber list from a&ai. + * + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity doRefreshSubscriberList() { + return refreshSubscriberList(); + } + + /** + * Refresh the full subscriber list from a&ai. + * + * @return ResponseEntity The response entity + * @throws IOException Signals that an I/O exception has occurred. + */ + @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity doRefreshFullSubscriberList() { + return refreshSubscriberList(); + } + + protected ResponseEntity refreshSubscriberList() { + Response resp = getSubscribers(); + return convertResponseToResponseEntity(resp); + } + + /** + * Get subscriber details from a&ai. + * + * @param subscriberId the subscriber id + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET) + public ResponseEntity GetSubscriberDetails(HttpServletRequest request, @PathVariable("subscriberId") String subscriberId) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + ResponseEntity responseEntity; + List roles = roleProvider.getUserRoles(request); + RoleValidator roleValidator = new RoleValidator(roles); + AaiResponse subscriberData = aaiService.getSubscriberData(subscriberId, roleValidator); + String httpMessage = subscriberData.getT() != null ? + objectMapper.writeValueAsString(subscriberData.getT()) : + subscriberData.getErrorMessage(); + + responseEntity = new ResponseEntity(httpMessage, HttpStatus.valueOf(subscriberData.getHttpCode())); + return responseEntity; + } + + /** + * Get service instances that match the query from a&ai. + * + * @param subscriberId the subscriber id + * @param instanceIdentifier the service instance name or id. + * @param projects the projects that are related to the instance + * @param owningEntities the owningEntities that are related to the instance + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "/search_service_instances", method = RequestMethod.GET) + public ResponseEntity SearchServiceInstances(HttpServletRequest request, + @RequestParam(value="subscriberId", required = false) String subscriberId, + @RequestParam(value="serviceInstanceIdentifier", required = false) String instanceIdentifier, + @RequestParam(value="project", required = false) List projects, + @RequestParam(value="owningEntity", required = false) List owningEntities) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + ResponseEntity responseEntity; + + List roles = roleProvider.getUserRoles(request); + RoleValidator roleValidator = new RoleValidator(roles); + + AaiResponse searchResult = aaiService.getServiceInstanceSearchResults(subscriberId, instanceIdentifier, roleValidator, owningEntities, projects); + + String httpMessage = searchResult.getT() != null ? + objectMapper.writeValueAsString(searchResult.getT()) : + searchResult.getErrorMessage(); + + + if(searchResult.getT().serviceInstances.isEmpty()){ + responseEntity = new ResponseEntity(httpMessage, HttpStatus.NOT_FOUND); + + } else { + responseEntity = new ResponseEntity(httpMessage, HttpStatus.valueOf(searchResult.getHttpCode())); + + } + return responseEntity; + } + + + + /** + * Issue a named query to a&ai. + * + * @param namedQueryId the named query id + * @param globalCustomerId the global customer id + * @param serviceType the service type + * @param serviceInstance the service instance + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET) + public ResponseEntity viewEditGetComponentList( + @PathVariable("namedQueryId") String namedQueryId, + @PathVariable("globalCustomerId") String globalCustomerId, + @PathVariable("serviceType") String serviceType, + @PathVariable("serviceInstance") String serviceInstance) { + + String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance); + + Response resp = doAaiPost("search/named-query", componentListPayload, false); + return convertResponseToResponseEntity(resp); + } + + /** + * Issue a named query to a&ai. + * + * @param namedQueryId the named query id + * @param globalCustomerId the global customer id + * @param serviceType the service type + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET) + public ResponseEntity viewEditGetComponentList( + @PathVariable("namedQueryId") String namedQueryId, + @PathVariable("globalCustomerId") String globalCustomerId, + @PathVariable("serviceType") String serviceType) { + + String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType); + + Response resp = doAaiPost("search/named-query", componentListPayload, false); + return convertResponseToResponseEntity(resp); + } + + @RequestMapping(value = "/aai_get_vnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}", method = RequestMethod.GET) + public ResponseEntity getNodeTemplateInstances( + @PathVariable("globalCustomerId") String globalCustomerId, + @PathVariable("serviceType") String serviceType, + @PathVariable("modelVersionId") String modelVersionId, + @PathVariable("modelInvariantId") String modelInvariantId, + @PathVariable("cloudRegion") String cloudRegion) { + + AaiResponse resp = aaiService.getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion); + return new ResponseEntity<>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); + } + + @RequestMapping(value = "/aai_get_network_collection_details/{serviceInstanceId}", method = RequestMethod.GET) + public ResponseEntity getNetworkCollectionDetails(@PathVariable("serviceInstanceId") String serviceInstanceId) throws IOException { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + AaiResponse resp = aaiService.getNetworkCollectionDetails(serviceInstanceId); + + String httpMessage = resp.getT() != null ? + objectMapper.writeValueAsString(resp.getT()) : + resp.getErrorMessage(); + return new ResponseEntity<>(httpMessage, HttpStatus.valueOf(resp.getHttpCode())); + } + + @RequestMapping(value = "/aai_get_instance_groups_by_cloudregion/{cloudOwner}/{cloudRegionId}/{networkFunction}", method = RequestMethod.GET) + public ResponseEntity getInstanceGroupsByCloudRegion(@PathVariable("cloudOwner") String cloudOwner, + @PathVariable("cloudRegionId") String cloudRegionId, + @PathVariable("networkFunction") String networkFunction) throws IOException { + com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); + AaiResponse resp = aaiService.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction); + + String httpMessage = resp.getT() != null ? + objectMapper.writeValueAsString(resp.getT()) : + resp.getErrorMessage(); + return new ResponseEntity<>(httpMessage, HttpStatus.valueOf(resp.getHttpCode())); + } + + @RequestMapping(value = "/aai_get_by_uri/**", method = RequestMethod.GET) + public ResponseEntity getByUri(HttpServletRequest request) { + + String restOfTheUrl = (String) request.getAttribute( + HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); + String formattedUri = restOfTheUrl.replaceFirst("/aai_get_by_uri/", "").replaceFirst("^aai/v[\\d]+/", ""); + + Response resp = doAaiGet(formattedUri, false); + + return convertResponseToResponseEntity(resp); + } + + + + @RequestMapping(value = "/aai_get_configuration/{configuration_id}", method = RequestMethod.GET) + public ResponseEntity getSpecificConfiguration(@PathVariable("configuration_id") String configurationId) { + + Response resp = doAaiGet("network/configurations/configuration/"+configurationId, false); + + return convertResponseToResponseEntity(resp); + } + + @RequestMapping(value = "/aai_get_service_instance_pnfs/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET) + public List getServiceInstanceAssociatedPnfs( + @PathVariable("globalCustomerId") String globalCustomerId, + @PathVariable("serviceType") String serviceType, + @PathVariable("serviceInstanceId") String serviceInstanceId) { + + return aaiService.getServiceInstanceAssociatedPnfs(globalCustomerId, serviceType, serviceInstanceId); + } + + /** + * PNF section + */ + @RequestMapping(value = "/aai_get_pnfs/pnf/{pnf_id}", method = RequestMethod.GET) + public ResponseEntity getSpecificPnf(@PathVariable("pnf_id") String pnfId) { + AaiResponse resp; + ResponseEntity re; + try { + resp = aaiService.getSpecificPnf(pnfId); + re = new ResponseEntity<>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); + } catch (Exception e){ + return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + return re; + } + + + /** + * Obtain tenants for a given service type. + * + * @param globalCustomerId the global customer id + * @param serviceType the service type + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET) + public ResponseEntity viewEditGetTenantsFromServiceType(HttpServletRequest request, + @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) { + + ResponseEntity responseEntity; + try { + ObjectMapper objectMapper = new ObjectMapper(); + List roles = roleProvider.getUserRoles(request); + RoleValidator roleValidator = new RoleValidator(roles); + AaiResponse response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator); + if (response.getHttpCode() == 200) { + responseEntity = new ResponseEntity(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK); + } else { + responseEntity = new ResponseEntity(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode())); + } + } catch (Exception e) { + responseEntity = new ResponseEntity("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR); + } + return responseEntity; + } + + @RequestMapping(value = "/aai_get_pnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}/{equipVendor}/{equipModel}", method = RequestMethod.GET) + public ResponseEntity getPnfInstances( + @PathVariable("globalCustomerId") String globalCustomerId, + @PathVariable("serviceType") String serviceType, + @PathVariable("modelVersionId") String modelVersionId, + @PathVariable("modelInvariantId") String modelInvariantId, + @PathVariable("cloudRegion") String cloudRegion, + @PathVariable("equipVendor") String equipVendor, + @PathVariable("equipModel") String equipModel) { + + AaiResponse resp = aaiService.getPNFData(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion, equipVendor, equipModel); + return new ResponseEntity<>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); + } + + @RequestMapping(value = "/aai_getPortMirroringConfigsData", method = RequestMethod.GET) + public Map getPortMirroringConfigsData( + @RequestParam ("configurationIds") List configurationIds) { + + return configurationIds.stream() + .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringConfigData(id))) + .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); + } + + @RequestMapping(value = "/aai_getPortMirroringSourcePorts", method = RequestMethod.GET) + public Map getPortMirroringSourcePorts( + @RequestParam ("configurationIds") List configurationIds) { + + return configurationIds.stream() + .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringSourcePorts(id))) + .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); + } + + private ResponseEntity convertResponseToResponseEntity(Response resp) { + ResponseEntity respEnt; + if (resp == null) { + respEnt = new ResponseEntity<>("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR); + } else { + respEnt = new ResponseEntity<>(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus())); + } + return respEnt; + } + + /** + * Gets the subscribers. + * + * @return the subscribers + */ + private Response getSubscribers() { + + String depth = "0"; + + Response resp = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false); + if (resp != null) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== getSubscribers() resp=" + resp.getStatusInfo().toString()); + } + return resp; + } + + /** + * Send a GET request to a&ai. + * + * @param uri the uri + * @param xml the xml + * @return String The response + */ + protected Response doAaiGet(String uri, boolean xml) { + String methodName = "getSubscriberList"; + String transId = UUID.randomUUID().toString(); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " start"); + + Response resp = null; + try { + + + resp = aaiRestInterface.RestGet(fromAppId, transId, Unchecked.toURI(uri), xml).getResponse(); + + } catch (WebApplicationException e) { + final String message = e.getResponse().readEntity(String.class); + LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + message); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + message); + } catch (Exception e) { + LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + e.toString()); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + e.toString()); + } + + return resp; + } + + /** + * Send a POST request to a&ai. + * + * @param uri the uri + * @param payload the payload + * @param xml the xml + * @return String The response + */ + protected Response doAaiPost(String uri, String payload, boolean xml) { + String methodName = "getSubscriberList"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " start"); + + Response resp = null; + try { + + resp = aaiRestInterface.RestPost(fromAppId, uri, payload, xml); + + } catch (Exception e) { + LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + e.toString()); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + e.toString()); + } + + return resp; + } + + /** + * Gets the component list put payload. + * + * @param namedQueryId the named query id + * @param globalCustomerId the global customer id + * @param serviceType the service type + * @param serviceInstance the service instance + * @return the component list put payload + */ + private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType, String serviceInstance) { + return + " {" + + " \"instance-filters\": {" + + " \"instance-filter\": [" + + " {" + + " \"customer\": {" + + " \"global-customer-id\": \"" + globalCustomerId + "\"" + + " }," + + " \"service-instance\": {" + + " \"service-instance-id\": \"" + serviceInstance + "\"" + + " }," + + " \"service-subscription\": {" + + " \"service-type\": \"" + serviceType + "\"" + + " }" + + " }" + + " ]" + + " }," + + " \"query-parameters\": {" + + " \"named-query\": {" + + " \"named-query-uuid\": \"" + namedQueryId + "\"" + + " }" + + " }" + + "}"; + + } + + private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) { + // TODO Auto-generated method stub + return " {" + + " \"instance-filters\": {" + + " \"instance-filter\": [" + + " {" + + " \"customer\": {" + + " \"global-customer-id\": \"" + globalCustomerId + "\"" + + " }," + + " \"service-subscription\": {" + + " \"service-type\": \"" + serviceType + "\"" + + " }" + + " }" + + " ]" + + " }," + + " \"query-parameters\": {" + + " \"named-query\": {" + + " \"named-query-uuid\": \"" + namedQueryId + "\"" + + " }" + + " }" + + "}"; + + } + + private String getAaiErrorMessage(String message) { + try { + org.json.JSONObject json = new org.json.JSONObject(message); + json = json.getJSONObject("requestError").getJSONObject("serviceException"); + + return json.getString("messageId") + ": " + json.getString("text"); + + } catch (Exception e) { + return null; + } + } +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/AaiController2.java b/vid-app-common/src/main/java/org/onap/vid/controller/AaiController2.java new file mode 100644 index 00000000..ee287703 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/AaiController2.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.controller; + +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; +import org.onap.vid.aai.model.Permissions; +import org.onap.vid.model.aaiTree.RelatedVnf; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.services.AaiService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +/** + * Controller to handle a&ai new requests. + */ + +@RestController +public class AaiController2 extends VidRestrictedBaseController { + + private final AaiService aaiService; + private final RoleProvider roleProvider; + private final AaiClientInterface aaiClient; + + @Autowired + public AaiController2(AaiService aaiService, RoleProvider roleProvider, AaiClientInterface aaiClient) { + this.aaiService = aaiService; + this.roleProvider = roleProvider; + this.aaiClient = aaiClient; + } + + @RequestMapping(value = "/aai_get_homing_by_vfmodule/{vnfInstanceId}/{vfModuleId}", method = RequestMethod.GET) + public GetTenantsResponse getHomingDataByVfModule(@PathVariable("vnfInstanceId") String vnfInstanceId, + @PathVariable("vfModuleId") String vfModuleId){ + return aaiService.getHomingDataByVfModule(vnfInstanceId, vfModuleId); + } + + @RequestMapping(value = "/aai_get_service_instance_topology/{subscriberId}/{serviceType}/{serviceInstanceId}", + method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public String getServiceInstanceTree(@PathVariable("subscriberId") String globalCustomerId, + @PathVariable("serviceType") String serviceInstanceType, + @PathVariable("serviceInstanceId") String serviceInstanceId) { + return aaiService.getAAIServiceTree(globalCustomerId, serviceInstanceType, serviceInstanceId); + } + + @RequestMapping(value = "/aai_reset_cache/{cacheName}", method = RequestMethod.DELETE) + @ResponseStatus(HttpStatus.ACCEPTED) + public void resetCache(@PathVariable("cacheName") String cacheName) { + aaiClient.resetCache(cacheName); + } + + @RequestMapping(value = "/roles/service_permissions", method = RequestMethod.GET) + public Permissions servicePermissions(HttpServletRequest request, + @RequestParam(value = "subscriberId") String subscriberId, + @RequestParam(value = "serviceType") String serviceType) { + + final boolean isEditPermitted = roleProvider + .getUserRolesValidator(request) + .isServicePermitted(subscriberId, serviceType); + + return new Permissions(isEditPermitted); + } + + @RequestMapping(value = "/aai_search_group_members", + method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public List searchGroupMembers(@RequestParam("subscriberId") String globalCustomerId, + @RequestParam("serviceType") String serviceType, + @RequestParam("serviceInvariantId") String invariantId, + @RequestParam("groupType") String groupType, + @RequestParam("groupRole") String groupRole) { + return aaiService.searchGroupMembers(globalCustomerId, serviceType, invariantId, groupType, groupRole); + } + + +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryController.java b/vid-app-common/src/main/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryController.java new file mode 100644 index 00000000..974ac988 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryController.java @@ -0,0 +1,173 @@ +package org.onap.vid.controller; + + +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vlan; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vnf; +import org.onap.vid.aai.util.ServiceInstanceStandardQuery; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.VidNotions; +import org.onap.vid.properties.Features; +import org.onap.vid.services.VidService; +import org.onap.vid.utils.Multival; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.togglz.core.manager.FeatureManager; + +import javax.servlet.http.HttpServletRequest; +import java.util.Collection; +import java.util.Collections; +import java.util.UUID; + +import static java.util.stream.Collectors.toList; + + +@RestController +@RequestMapping(AaiServiceInstanceStandardQueryController.AAI_STANDARD_QUERY) +public class AaiServiceInstanceStandardQueryController extends VidRestrictedBaseController { + + public static final String AAI_STANDARD_QUERY = "aai/standardQuery"; + + private final ServiceInstanceStandardQuery serviceInstanceStandardQuery; + private final FeatureManager featureManager; + private final VidService sdcService; + + @Autowired + public AaiServiceInstanceStandardQueryController(FeatureManager featureManager, ServiceInstanceStandardQuery serviceInstanceStandardQuery, VidService sdcService) { + this.featureManager = featureManager; + this.serviceInstanceStandardQuery = serviceInstanceStandardQuery; + this.sdcService = sdcService; + } + + @RequestMapping(value = "vlansByNetworks", method = RequestMethod.GET) + public VlansByNetworksHierarchy getNetworksToVlansByServiceInstance(HttpServletRequest request, + @RequestParam("sdcModelUuid") UUID sdcModelUuid, + @RequestParam("globalCustomerId") String globalCustomerId, + @RequestParam("serviceType") String serviceType, + @RequestParam("serviceInstanceId") String serviceInstanceId + ) throws AsdcCatalogException { + if (!featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)) { + return new VlansByNetworksHierarchy(); + } + + if (!isModelOf5g(sdcModelUuid)) { + return new VlansByNetworksHierarchy(); + } + + final ServiceInstance serviceInstance = + serviceInstanceStandardQuery.fetchServiceInstance(globalCustomerId, serviceType, serviceInstanceId); + + Multival>> l3NetworksWithVlansForVnfForService = fetchVnfsForService(serviceInstance); + Multival> l3NetworksWithVlansForService = fetchNetworksForService(serviceInstance); + + // translate to response's format + return new VlansByNetworksHierarchy( + l3NetworksWithVlansForService.getValues().stream().map(this::translateNetworksFormat + ).collect(toList()), + + l3NetworksWithVlansForVnfForService.getValues().stream().map(vnfWithNetworks -> + new VnfVlansByNetworks(vnfWithNetworks.getKey().getVnfId(), + vnfWithNetworks.getValues().stream().map(this::translateNetworksFormat + ).collect(toList()) + ) + ).collect(toList()) + ); + } + + private Multival>> fetchVnfsForService(ServiceInstance serviceInstance) { + final Multival vnfsForService = + serviceInstanceStandardQuery.fetchRelatedVnfs(serviceInstance); + + final Multival> vnfsWithL3NetworksForService = + vnfsForService.mapEachVal(vnf -> serviceInstanceStandardQuery.fetchRelatedL3Networks("vnf", vnf)); + + return vnfsWithL3NetworksForService.mapEachVal(vnfMulti-> + vnfMulti.mapEachVal(serviceInstanceStandardQuery::fetchRelatedVlanTags) + ); + + } + + private Multival> fetchNetworksForService(ServiceInstance serviceInstance) { + final Multival l3NetworksForService = + serviceInstanceStandardQuery.fetchRelatedL3Networks("service", serviceInstance); + + return l3NetworksForService.mapEachVal(serviceInstanceStandardQuery::fetchRelatedVlanTags); + } + + private NetworksToVlans translateNetworksFormat(Multival networkWithVlan) { + return new NetworksToVlans( + networkWithVlan.getKey().getNetworkId(), + networkWithVlan.getKey().getNetworkName(), + networkWithVlan.getKey().getNetworkType(), + networkWithVlan.getKey().getOrchestrationStatus(), + networkWithVlan.getValues().stream().map( + vlan -> new NetworksToVlans.Vlan(vlan.getVlanIdInner()) + ).collect(toList()) + ); + } + + protected boolean isModelOf5g(UUID sdcModelUuid) throws AsdcCatalogException { + final ServiceModel serviceModel = sdcService.getService(sdcModelUuid.toString()); + if (serviceModel == null) { + throw new GenericUncheckedException("Internal error while fetching Service Model: " + sdcModelUuid); + } + VidNotions.ModelCategory serviceModelCategory = serviceModel.getService().getVidNotions().getModelCategory(); + return serviceModelCategory.equals(VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL) || + serviceModelCategory.equals(VidNotions.ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL); + } + + protected static class VlansByNetworksHierarchy { + public final Collection serviceNetworks; + public final Collection vnfNetworks; + + public VlansByNetworksHierarchy() { + this(Collections.emptySet(), Collections.emptySet()); + } + + public VlansByNetworksHierarchy(Collection serviceNetworks, Collection vnfNetworks) { + this.serviceNetworks = serviceNetworks; + this.vnfNetworks = vnfNetworks; + } + } + + protected static class VnfVlansByNetworks { + public final String vnfId; + public final Collection networks; + + public VnfVlansByNetworks(String vnfId, Collection networks) { + this.vnfId = vnfId; + this.networks = networks; + } + } + + protected static class NetworksToVlans { + public final String networkId; + public final String name; + public final String nodeType; + public final String nodeStatus; + public final Collection vlans; + + private NetworksToVlans(String networkId, String name, String nodeType, String nodeStatus, Collection vlans) { + this.networkId = networkId; + this.name = name; + this.nodeType = nodeType; + this.nodeStatus = nodeStatus; + this.vlans = vlans; + } + + private static class Vlan { + public final String vlanIdInner; + + private Vlan(String vlanIdInner) { + this.vlanIdInner = vlanIdInner; + } + } + + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/AsyncControllerForTests.java b/vid-app-common/src/main/java/org/onap/vid/controller/AsyncControllerForTests.java new file mode 100644 index 00000000..a67686a9 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/AsyncControllerForTests.java @@ -0,0 +1,48 @@ +package org.onap.vid.controller; + +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.model.JobModel; +import org.onap.vid.services.BulkInstantiationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.ws.rs.WebApplicationException; +import java.util.UUID; + +import static org.springframework.http.HttpStatus.BAD_REQUEST; + +@RestController +@RequestMapping("asyncForTests") +public class AsyncControllerForTests extends VidRestrictedBaseController { + + private BulkInstantiationService bulkInstantiationService; + + @Autowired + public AsyncControllerForTests(BulkInstantiationService bulkInstantiationService) { + this.bulkInstantiationService = bulkInstantiationService; + } + + @RequestMapping(value = "/job/{uuid}", method = RequestMethod.GET) + public JobModel getJob(@PathVariable UUID uuid) { + return bulkInstantiationService.getJob(uuid); + } + + @RequestMapping(value = "/error", method = RequestMethod.GET) + public void throwError() { + throw new GenericUncheckedException("dummy error"); + } + + @ExceptionHandler({IllegalArgumentException.class}) + @ResponseStatus(value=BAD_REQUEST) + private ExceptionResponse exceptionHandlerBadRequest(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } + + @ExceptionHandler(WebApplicationException.class) + private ResponseEntity webApplicationExceptionHandler(WebApplicationException e) { + return ControllersUtils.handleWebApplicationException(e, LOGGER); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java b/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java new file mode 100644 index 00000000..dcfc13b3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/AsyncInstantiationController.java @@ -0,0 +1,104 @@ +package org.onap.vid.controller; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.MsoResponseWrapper2; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.UUID; + +import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED; + + +@RestController +@RequestMapping(AsyncInstantiationController.ASYNC_INSTANTIATION) +public class AsyncInstantiationController extends VidRestrictedBaseController { + + public static final String ASYNC_INSTANTIATION = "asyncInstantiation"; + + protected final AsyncInstantiationBusinessLogic asyncInstantiationBL; + + protected ObjectMapper objectMapper = new ObjectMapper(); + + @Autowired + protected AuditService auditService; + + @Autowired + public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL) { + this.asyncInstantiationBL = asyncInstantiationBL; + } + + @ExceptionHandler(OperationNotAllowedException.class) + @ResponseStatus(value=METHOD_NOT_ALLOWED) + public ExceptionResponse illegalStateExceptionHandler(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } + + /** + * Gets the new services status. + * @param request the request + * @return the services list + */ + @RequestMapping(method = RequestMethod.GET) + public List getServicesInfo(HttpServletRequest request) { + return asyncInstantiationBL.getAllServicesInfo(); + } + + @RequestMapping(value = "bulk", method = RequestMethod.POST) + public MsoResponseWrapper2> createBulkOfServices(@RequestBody ServiceInstantiation request, HttpServletRequest httpServletRequest) { + //Push to DB according the model + try { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "incoming ServiceInstantiation request: "+ objectMapper.writeValueAsString(request)); + } + catch (Exception e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "failed to log incoming ServiceInstantiation request ", e); + } + String userId = ControllersUtils.extractUserId(httpServletRequest); + List uuids = asyncInstantiationBL.pushBulkJob(request, userId); + + return new MsoResponseWrapper2(200, uuids); + } + + @RequestMapping(value = "job/{jobId}", method = RequestMethod.DELETE) + public void deleteServiceInfo(@PathVariable("jobId") UUID jobId) { + asyncInstantiationBL.deleteJob(jobId); + } + + @RequestMapping(value = "hide/{jobId}", method = RequestMethod.POST) + public void hideServiceInfo(@PathVariable("jobId") UUID jobId) { + asyncInstantiationBL.hideServiceInfo(jobId); + } + + @RequestMapping(value = "auditStatus/{jobId}", method = RequestMethod.GET) + public List getJobAuditStatus(HttpServletRequest request, @PathVariable(value="jobId") UUID jobId, @RequestParam(value="source") JobAuditStatus.SourceStatus source){ + return asyncInstantiationBL.getAuditStatuses(jobId, source); + } + + @RequestMapping(value = "auditStatus/{jobId}/mso", method = RequestMethod.GET) + public List getJobMsoAuditStatusForAlaCarte(HttpServletRequest request, + @PathVariable(value="jobId") UUID jobId, + @RequestParam(value="requestId", required = false) UUID requestId, + @RequestParam(value="serviceInstanceId", required = false) UUID serviceInstanceId){ + if (serviceInstanceId != null) { + return auditService.getAuditStatusFromMsoByServiceInstanceId(jobId, serviceInstanceId); + } + if (requestId != null){ + return auditService.getAuditStatusFromMsoByRequestId(jobId, requestId); + } + return auditService.getAuditStatusFromMsoByJobId(jobId); + + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/ChangeManagementController.java b/vid-app-common/src/main/java/org/onap/vid/controller/ChangeManagementController.java new file mode 100644 index 00000000..90a175f6 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/ChangeManagementController.java @@ -0,0 +1,213 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.vid.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.changeManagement.*; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.model.MsoExceptionResponse; +import org.onap.vid.mso.MsoResponseWrapper2; +import org.onap.vid.mso.MsoResponseWrapperInterface; +import org.onap.vid.mso.rest.Request; +import org.onap.vid.services.ChangeManagementService; +import org.onap.vid.services.WorkflowService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; +import java.util.Collection; +import java.util.Collections; + +import static org.onap.vid.utils.Logging.getMethodName; +import static org.springframework.http.HttpStatus.*; + +/** + * Controller to handle ChangeManagement feature requests. + */ +@RestController +@RequestMapping(ChangeManagementController.CHANGE_MANAGEMENT) +public class ChangeManagementController extends UnRestrictedBaseController { + public static final String VNF_WORKFLOW_RELATION = "vnf_workflow_relation"; + public static final String CHANGE_MANAGEMENT = "change-management"; + public static final String GET_VNF_WORKFLOW_RELATION = "get_vnf_workflow_relation"; + public static final String SCHEDULER_BY_SCHEDULE_ID = "/scheduler/schedules/{scheduleId}"; + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ChangeManagementController.class); + private String fromAppId; + private final WorkflowService workflowService; + private final ChangeManagementService changeManagementService; + private final ObjectMapper objectMapper; + + + @Autowired + public ChangeManagementController(WorkflowService workflowService, ChangeManagementService changeManagementService, ObjectMapper objectMapper) { + this.fromAppId = "VidChangeManagementController"; + this.workflowService = workflowService; + this.changeManagementService = changeManagementService; + this.objectMapper = objectMapper; + } + + @RequestMapping(value = {"/workflow"}, method = RequestMethod.GET) + public ResponseEntity> getWorkflow(@RequestParam("vnfs") Collection vnfs) { + Collection result = this.workflowService.getWorkflowsForVNFs(vnfs); + return new ResponseEntity<>(result, OK); + } + + @RequestMapping(value = {"/mso"}, method = RequestMethod.GET) + public ResponseEntity> getMSOChangeManagements() { + + Collection result = this.changeManagementService.getMSOChangeManagements(); + return new ResponseEntity<>(result, OK); + } + + @RequestMapping(value = "/workflow/{vnfName}", method = RequestMethod.POST) + public ResponseEntity changeManagement(HttpServletRequest request, + @PathVariable("vnfName") String vnfName, + @RequestBody ChangeManagementRequest changeManagmentRequest) + throws Exception { + return this.changeManagementService.doChangeManagement(changeManagmentRequest, vnfName); + } + + @RequestMapping(value = "/uploadConfigUpdateFile", method = RequestMethod.POST) + public @ResponseBody ResponseEntity uploadConfigUpdateFile(@RequestPart("file") MultipartFile file) + throws Exception { + try { + String jsonString = this.changeManagementService.uploadConfigUpdateFile(file); + return new ResponseEntity<>(jsonString, HttpStatus.OK); + } + catch(WebApplicationException e){ + return new ResponseEntity<>(handleException(e), HttpStatus.valueOf(e.getResponse().getStatus())); + } + catch (Exception e) { + return new ResponseEntity<>(handleException(e), INTERNAL_SERVER_ERROR); + } + } + + + @RequestMapping(value = {"/scheduler"}, method = RequestMethod.GET) + public ResponseEntity getSchedulerChangeManagements() { + ArrayNode result = this.changeManagementService.getSchedulerChangeManagements(); + return new ResponseEntity<>(result, OK); + } + + @RequestMapping(value = {SCHEDULER_BY_SCHEDULE_ID}, method = RequestMethod.DELETE) + public ResponseEntity deleteSchedule(@PathVariable("scheduleId") String scheduleId) { + Pair result = this.changeManagementService.deleteSchedule(scheduleId); + return ResponseEntity.status(result.getRight()).build(); + } + + + @RequestMapping(value = {GET_VNF_WORKFLOW_RELATION}, method = RequestMethod.POST) + public ResponseEntity getWorkflows(@RequestBody GetVnfWorkflowRelationRequest getVnfWorkflowRelationRequest) { + try { + GetWorkflowsResponse response = new GetWorkflowsResponse(changeManagementService.getWorkflowsForVnf(getVnfWorkflowRelationRequest)); + return ResponseEntity.status(OK).body(response); + } + catch (NotFoundException exception) { + LOGGER.error(exception.getMessage(), exception); + return new ResponseEntity<>(new VnfWorkflowRelationResponse(Collections.singletonList(exception.getMessage())),HttpStatus.NOT_FOUND); + } + catch (Exception exception) { + return handleException(exception, "Failed to get workflows for vnf"); + } + } + + @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.POST) + public ResponseEntity createWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) { + VnfWorkflowRelationResponse vnfWorkflowRelationResponse; + try { + vnfWorkflowRelationResponse = changeManagementService.addVnfWorkflowRelation(vnfWorkflowRelationRequest); + } + catch (Exception exception) { + return handleException(exception, "Failed to add vnf to workflow relation"); + } + + return new ResponseEntity<>(vnfWorkflowRelationResponse, OK); + } + + @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.GET) + public ResponseEntity getAllWorkflowRelation() { + + try { + VnfWorkflowRelationAllResponse vnfWorkflowRelationAllResponse = changeManagementService.getAllVnfWorkflowRelations(); + return new ResponseEntity<>(vnfWorkflowRelationAllResponse, OK); + } + catch (Exception exception) { + return handleException(exception, "Failed to get all vnf to workflow relations"); + } + } + + @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.DELETE) + public ResponseEntity deleteWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) { + VnfWorkflowRelationResponse vnfWorkflowRelationResponse; + try { + vnfWorkflowRelationResponse = changeManagementService.deleteVnfWorkflowRelation(vnfWorkflowRelationRequest); + } + catch (Exception exception) { + return handleException(exception, "Failed to delete vnf from workflow relation"); + } + + return new ResponseEntity<>(vnfWorkflowRelationResponse, OK); + } + + private ResponseEntity handleException(Exception exception, String msg) { + LOGGER.error(msg, exception); + return new ResponseEntity<>(new VnfWorkflowRelationResponse(Collections.singletonList(msg)), HttpStatus.INTERNAL_SERVER_ERROR); + } + + + private ExceptionResponse handleException(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(value=OK) //return 200 for Backwards compatibility with the previous responses to scheduler + private MsoResponseWrapperInterface exceptionHandler(Exception e) { + return exceptionHandler(e, INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler({ + javax.ws.rs.BadRequestException.class, + }) + @ResponseStatus(value = OK) //return 200 for Backwards compatibility with the previous responses to scheduler + public MsoResponseWrapperInterface clientDerivedExceptionAsBadRequest(Exception e) { + // same handler, different HTTP Code + return exceptionHandler(e, BAD_REQUEST); + } + + private MsoResponseWrapperInterface exceptionHandler(Exception e, HttpStatus httpStatus) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodName(), ExceptionUtils.getMessage(e), e); + MsoResponseWrapper2 responseWrapper2 = new MsoResponseWrapper2<>(httpStatus.value(), new MsoExceptionResponse(e)); + return responseWrapper2; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/ControllersUtils.java b/vid-app-common/src/main/java/org/onap/vid/controller/ControllersUtils.java new file mode 100644 index 00000000..9be6ad51 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/ControllersUtils.java @@ -0,0 +1,45 @@ +package org.onap.vid.controller; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.model.ExceptionResponse; +import org.springframework.http.ResponseEntity; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import javax.ws.rs.WebApplicationException; + +import static org.onap.vid.utils.Logging.getMethodCallerName; + +public class ControllersUtils { + + + public static String extractUserId(HttpServletRequest request) { + String userId = ""; + HttpSession session = request.getSession(); + if (session != null) { + User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); + if (user != null) { + //userId = user.getHrid(); + userId = user.getLoginId(); + if (userId == null) + userId = user.getOrgUserId(); + } + } + return userId; + } + + public static ExceptionResponse handleException(Exception e, EELFLoggerDelegate logger) { + logger.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodCallerName(), ExceptionUtils.getMessage(e), e); + + ExceptionResponse exceptionResponse = new ExceptionResponse(e); + return exceptionResponse; + } + + public static ResponseEntity handleWebApplicationException(WebApplicationException e, EELFLoggerDelegate logger) { + return ResponseEntity.status(e.getResponse().getStatus()).body(ControllersUtils.handleException(e, logger)); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/FeatureTogglingController.java b/vid-app-common/src/main/java/org/onap/vid/controller/FeatureTogglingController.java new file mode 100644 index 00000000..a90e71d4 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/FeatureTogglingController.java @@ -0,0 +1,29 @@ +package org.onap.vid.controller; + +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.vid.properties.Features; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; + +@RestController +@RequestMapping("flags") +public class FeatureTogglingController extends RestrictedBaseController { + + @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public @ResponseBody Map getFeatureToggles() + { + HashMap flags = new HashMap <>(); + for(Features flag : Features.values()){ + flags.put(flag.name(), flag.isActive()); + } + return flags; + + + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/HealthCheckController.java b/vid-app-common/src/main/java/org/onap/vid/controller/HealthCheckController.java new file mode 100644 index 00000000..2c42da27 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/HealthCheckController.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.controller; + +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.dao.FnAppDoaImpl; +import org.onap.vid.model.GitRepositoryState; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; + +/** + * Controller for user profile view. The view is restricted to authenticated + * users. The view name resolves to page user_profile.jsp which uses Angular. + */ + +@RestController +@RequestMapping("/") +public class HealthCheckController extends UnRestrictedBaseController { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(HealthCheckController.class); + private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + private static final String GIT_PROPERTIES_FILENAME = "git.properties"; + private FnAppDoaImpl fnAppDoaImpl; + + @Autowired + public HealthCheckController(FnAppDoaImpl fnAppDoaImpl) { + this.fnAppDoaImpl = fnAppDoaImpl; + } + + /** + * Obtain the HealthCheck Status from the System.Properties file. + * Used by IDNS for redundancy + * + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "/healthCheck", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public HealthStatus getHealthCheckStatusForIDNS() { + return createCorrespondingStatus(); + } + + /** + * Obtain the HealthCheck Status from the System.Properties file. + * + * @return ResponseEntity The response entity + */ + @RequestMapping(value = "rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public HealthStatus getHealthCheck( + @PathVariable("User-Agent") String UserAgent, + @PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "User-Agent ", UserAgent); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID ", ECOMPRequestID); + return createCorrespondingStatus(); + } + + @RequestMapping(value = "/commitInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public GitRepositoryState getCommitInfo() throws IOException { + Properties properties = new Properties(); + properties.load(getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES_FILENAME)); + return new GitRepositoryState(properties); + } + + private HealthStatus createCorrespondingStatus() { + logData(); + try { + int count = fnAppDoaImpl.getProfileCount(getUrl(), getUsername(), getPassword()); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::", count); + return okStatus(); + } catch (Exception ex) { + String errorMsg = ex.getMessage(); + LOGGER.error(EELFLoggerDelegate.errorLogger, errorMsg); + return errorStatus(errorMsg); + } + } + + private void logData() { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::", getUrl()); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::", getUsername()); + } + + private HealthStatus okStatus() { + return new HealthStatus(OK, dateFormat.format(new Date()), "health check succeeded"); + } + + private HealthStatus errorStatus(String msg) { + return new HealthStatus(INTERNAL_SERVER_ERROR, dateFormat.format( + new Date()), "health check failed: " + msg); + } + + private String getUrl() { + return SystemProperties.getProperty("db.connectionURL"); + } + + private String getUsername() { + return SystemProperties.getProperty("db.userName"); + } + + private String getPassword() { + return SystemProperties.getProperty("db.password"); + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/HealthStatus.java b/vid-app-common/src/main/java/org/onap/vid/controller/HealthStatus.java new file mode 100644 index 00000000..14372b5d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/HealthStatus.java @@ -0,0 +1,31 @@ +package org.onap.vid.controller; + +import org.springframework.http.HttpStatus; + +/** + * Model for JSON response with health-check results. + */ +public final class HealthStatus { + + private final int statusCode; + private final String detailedMsg; + private final String date; + + public HealthStatus(HttpStatus code, String date, String detailedMsg) { + this.statusCode = code.value(); + this.detailedMsg = detailedMsg; + this.date = date; + } + + public int getStatusCode() { + return statusCode; + } + + public String getDetailedMsg() { + return detailedMsg; + } + + public String getDate() { + return date; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java b/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java new file mode 100644 index 00000000..698ea546 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/LoggerController.java @@ -0,0 +1,115 @@ +package org.onap.vid.controller; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.FileAppender; +import ch.qos.logback.core.spi.AppenderAttachable; +import org.apache.commons.io.input.ReversedLinesFileReader; +import org.apache.commons.lang3.StringUtils; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.roles.Role; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.utils.Streams; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.NotAuthorizedException; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static com.att.eelf.configuration.Configuration.GENERAL_LOGGER_NAME; + + +@RestController +@RequestMapping("logger") +public class LoggerController extends RestrictedBaseController { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(LoggerController.class); + + @Autowired + RoleProvider roleProvider; + + @RequestMapping(value = "/{loggerName:audit|error|metrics}", method = RequestMethod.GET) + public String getLog(@PathVariable String loggerName, HttpServletRequest request, + @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException { + + List roles = roleProvider.getUserRoles(request); + boolean userPermitted = roleProvider.userPermissionIsReadLogs(roles); + if (!userPermitted) { + throw new NotAuthorizedException("User not authorized to get logs"); + } + + String logfilePath = getLogfilePath(loggerName); + + try (final ReversedLinesFileReader reader = new ReversedLinesFileReader(new File(logfilePath))) { + Supplier reverseLinesSupplier = () -> { + try { + return reader.readLine(); + } catch (NullPointerException e) { + // EOF Reached + return null; + } catch (IOException e) { + throw new InternalServerErrorException("error while reading " + logfilePath, e); + } + }; + + return Streams.takeWhile( + Stream.generate(reverseLinesSupplier), + line -> !StringUtils.contains(line, "Logging is started")) + .limit(limit) + .limit(5_000) + .filter(Objects::nonNull) + .collect(Collectors.joining("\n")); + } + } + + private String getLogfilePath(String loggerName) { + /* + Find the requested logger, and pull all of it's appenders. + Find the first of the appenders that is a FileAppender, and return it's + write-out filename. + */ + LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + return context.getLoggerList().stream() + .filter(logger -> logger.getName().equals(GENERAL_LOGGER_NAME + "." + loggerName)) + .flatMap(this::pullSubAppenders) + .flatMap(appender -> { + // Appender might be "attachable", if so - roll-up its sub-appenders + return (appender instanceof AppenderAttachable) ? + pullSubAppenders((AppenderAttachable) appender) : Stream.of(appender); + }) + .filter(appender -> appender instanceof FileAppender) + .map(appender -> (FileAppender) appender) + .map(FileAppender::getFile) + .findFirst() + .orElseThrow(() -> new InternalServerErrorException("logfile for " + loggerName + " not found")); + } + + private Stream> pullSubAppenders(AppenderAttachable logger) { + return Streams.fromIterator(logger.iteratorForAppenders()); + } + + @ExceptionHandler({ NotAuthorizedException.class }) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public String notAuthorizedHandler(NotAuthorizedException e) { + return "UNAUTHORIZED"; + } + + @ExceptionHandler({ IOException.class, InternalServerErrorException.class }) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public ExceptionResponse ioExceptionHandler(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MaintenanceController.java b/vid-app-common/src/main/java/org/onap/vid/controller/MaintenanceController.java new file mode 100644 index 00000000..40b7834d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MaintenanceController.java @@ -0,0 +1,152 @@ +package org.onap.vid.controller; + +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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========================================================= + */ + +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.category.AddCategoryOptionResponse; +import org.onap.vid.category.AddCategoryOptionsRequest; +import org.onap.vid.category.CategoryParameterOptionRep; +import org.onap.vid.category.CategoryParametersResponse; +import org.onap.vid.model.CategoryParameter.Family; +import org.onap.vid.model.CategoryParameterOption; +import org.onap.vid.services.CategoryParameterService; +import org.onap.vid.services.CategoryParameterServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.ws.rs.ForbiddenException; + +import static org.onap.vid.utils.Logging.getMethodCallerName; + +/** + * Controler for APIs that are used only by vid operators + */ + +@RestController +@RequestMapping("maintenance") +public class MaintenanceController extends UnRestrictedBaseController { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(MaintenanceController.class); + private CategoryParameterService categoryParameterService; + + @Autowired + public MaintenanceController(CategoryParameterService categoryParameterService) { + this.categoryParameterService = categoryParameterService; + } + + /** + * Add list of options to one category parameter + */ + @RequestMapping(value = "/category_parameter/{categoryName}", method = RequestMethod.POST) + public ResponseEntity addCategoryOptions(@PathVariable String categoryName, + @RequestBody AddCategoryOptionsRequest option) { + debugStartLog(); + try { + AddCategoryOptionResponse response = categoryParameterService + .createCategoryParameterOptions(categoryName, option); + HttpStatus httpStatus = response.getErrors().isEmpty() ? HttpStatus.OK : HttpStatus.MULTI_STATUS; + debugEndLog(response); + return createResponseWithBody(httpStatus, response); + } catch (CategoryParameterServiceImpl.UnfoundedCategoryException exception) { + return createResponseWithBody(HttpStatus.NOT_FOUND, new AddCategoryOptionResponse(exception.getMessage())); + } catch (RuntimeException exception) { + LOGGER.error("failed to add option to parameter category " + categoryName, exception); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + @RequestMapping(value = "/category_parameter/{categoryName}", method = RequestMethod.PUT) + public ResponseEntity updateNameForOption(@PathVariable String categoryName, + @RequestBody CategoryParameterOptionRep option) { + debugStartLog(); + try { + AddCategoryOptionResponse response = categoryParameterService + .updateCategoryParameterOption(categoryName, option); + HttpStatus httpStatus = response.getErrors().isEmpty() ? HttpStatus.OK : HttpStatus.MULTI_STATUS; + debugEndLog(response); + return createResponseWithBody(httpStatus, response); + } catch (ForbiddenException exception) { + return createResponseWithBody(HttpStatus.FORBIDDEN, new AddCategoryOptionResponse(exception.getMessage())); + } catch (CategoryParameterServiceImpl.UnfoundedCategoryException | CategoryParameterServiceImpl.UnfoundedCategoryOptionException exception) { + return createResponseWithBody(HttpStatus.NOT_FOUND, new AddCategoryOptionResponse(exception.getMessage())); + + } catch (CategoryParameterServiceImpl.AlreadyExistOptionNameException exception) { + return createResponseWithBody(HttpStatus.CONFLICT, new AddCategoryOptionResponse(exception.getMessage())); + + } catch (RuntimeException exception) { + LOGGER.error("failed to update option to parameter category " + categoryName, exception); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + /** + * Gets the owning entity properties. + */ + @RequestMapping(value = "/category_parameter", method = RequestMethod.GET) + public ResponseEntity getCategoryParameter(@RequestParam(value = "familyName", required = true) Family familyName) { + debugStartLog(); + try { + CategoryParametersResponse response = categoryParameterService.getCategoryParameters(familyName); + debugEndLog(response); + return ResponseEntity.ok().body(response); + } catch (RuntimeException exception) { + LOGGER.error("failed to retrieve category parameter list from DB.", exception); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + /** + * Delete option of the category. + */ + @RequestMapping(value = "/delete_category_parameter/{categoryName}", method = RequestMethod.DELETE) + public ResponseEntity deleteCategoryOption(@PathVariable String categoryName, + @RequestBody CategoryParameterOption option) { + debugStartLog(); + + try { + categoryParameterService.deleteCategoryOption(categoryName, option); + debugEndLog(HttpStatus.OK); + return ResponseEntity.status(HttpStatus.OK).build(); + } catch (CategoryParameterServiceImpl.UnfoundedCategoryException exception) { + return createResponseWithBody(HttpStatus.NOT_FOUND, new AddCategoryOptionResponse(exception.getMessage())); + } catch (RuntimeException exception) { + LOGGER.error("failed to add/update owning entity option", exception); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); + } + } + + private ResponseEntity createResponseWithBody(HttpStatus status, AddCategoryOptionResponse response) { + return ResponseEntity.status(status).body(response); + } + + private void debugStartLog() { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodCallerName()); + } + + private void debugEndLog(Object response) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), response); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java new file mode 100644 index 00000000..7f90d6a4 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 Nokia. 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.vid.controller; + +import io.joshworks.restclient.http.mapper.ObjectMapper; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.factories.MsoRequestFactory; +import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.MsoProperties; +import org.onap.vid.mso.rest.MsoRestClientNew; +import org.onap.vid.services.CloudOwnerService; +import org.onap.vid.services.CloudOwnerServiceImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.togglz.core.manager.FeatureManager; + + +@Configuration +public class MsoConfig { + + @Bean + public MsoRequestFactory createRequestDetailsFactory(){ + return new MsoRequestFactory(); + } + + @Bean + public MsoRestClientNew msoClient(ObjectMapper unirestObjectMapper){ + // Satisfy both interfaces -- MsoInterface and RestMsoImplementation + return new MsoRestClientNew(new SyncRestClient(unirestObjectMapper), SystemProperties.getProperty( + MsoProperties.MSO_SERVER_URL)); + } + + @Bean + public MsoBusinessLogic getMsoBusinessLogic(MsoInterface msoClient, FeatureManager featureManager){ + return new MsoBusinessLogicImpl(msoClient, featureManager); + } + + @Bean + public CloudOwnerService cloudOwnerService(AaiClientInterface aaiClient, FeatureManager featureManager) { + return new CloudOwnerServiceImpl(aaiClient, featureManager); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java b/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java new file mode 100644 index 00000000..716267af --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java @@ -0,0 +1,705 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.controller; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.model.SoftDeleteRequest; +import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.mso.MsoResponseWrapper; +import org.onap.vid.mso.MsoResponseWrapper2; +import org.onap.vid.mso.rest.Request; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestDetailsWrapper; +import org.onap.vid.mso.rest.Task; +import org.onap.vid.services.CloudOwnerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.List; + +import static org.onap.vid.utils.Logging.getMethodName; + +/** + * The Class MsoController. + */ +@RestController +@RequestMapping("mso") +public class MsoController extends RestrictedBaseController { + + /** + * The logger. + */ + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(MsoController.class); + + /** + * The Constant SVC_INSTANCE_ID. + */ + public static final String SVC_INSTANCE_ID = ""; + public static final String REQUEST_TYPE = ""; + + /** + * The Constant CONFIGURATION_ID + */ + public static final String CONFIGURATION_ID = ""; + + /** + * The Constant VNF_INSTANCE_ID. + */ + public static final String VNF_INSTANCE_ID = ""; + public static final String START_LOG = " start"; + + private final MsoBusinessLogic msoBusinessLogic; + private final CloudOwnerService cloudOwnerService; + + @Autowired + public MsoController(MsoBusinessLogic msoBusinessLogic, CloudOwnerService cloudOwnerService) { + this.msoBusinessLogic = msoBusinessLogic; + this.cloudOwnerService = cloudOwnerService; + } + + /** + * Creates the svc instance. + * + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_svc_instance", method = RequestMethod.POST) + public ResponseEntity createSvcInstance(HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "createSvcInstance"; + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + // always return OK, the MSO status code is embedded in the body + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.createSvcInstance(msoRequest); + + return (new ResponseEntity<>(w.getResponse(), HttpStatus.OK)); + + } + + /** + * Creates the e2e svc instance. + * + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_e2e_svc_instance", method = RequestMethod.POST) + public ResponseEntity createE2eSvcInstance(HttpServletRequest request, @RequestBody LinkedHashMap msoRequest) { + String methodName = "createE2eSvcInstance"; + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + // always return OK, the MSO status code is embedded in the body + + //cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.createE2eSvcInstance(msoRequest.get("requestDetails")); + + return (new ResponseEntity<>(w.getResponse(), HttpStatus.OK)); + + } + + /** + * Creates the vnf. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_vnf_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.createVnf(msoRequest, serviceInstanceId); + + // always return OK, the MSO status code is embedded in the body + + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + + } + + /** + * Creates the nw instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_nw_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity createNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "createNwInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " start, serviceInstanceId = " + serviceInstanceId); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.createNwInstance(msoRequest, serviceInstanceId); + + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + + } + + /** + * Creates the volume group instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, + HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "createVolumeGroupInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.createVolumeGroupInstance(msoRequest, serviceInstanceId, vnfInstanceId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Creates the vf module instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + public ResponseEntity createVfModuleInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "createVfModuleInstance"; + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.createVfModuleInstance(msoRequest, serviceInstanceId, vnfInstanceId); + + // always return OK, the MSO status code is embedded in the body + + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Creates a configuration instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_create_configuration_instance/{serviceInstanceId}/configurations/", method = RequestMethod.POST) + public ResponseEntity createConfigurationInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request, @RequestBody RequestDetailsWrapper msoRequest) { + String methodName = "createConfigurationInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest.getRequestDetails()); + MsoResponseWrapper w = msoBusinessLogic.createConfigurationInstance(msoRequest, serviceInstanceId); + + // always return OK, the MSO status code is embedded in the body + + return (new ResponseEntity<>(w.getResponse(), HttpStatus.OK)); + } + + /** + * Delete E2e svc instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_e2e_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteE2eSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request, @RequestBody LinkedHashMap msoRequest) { + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), msoRequest); + MsoResponseWrapper w = msoBusinessLogic.deleteE2eSvcInstance(msoRequest.get("requestDetails"), serviceInstanceId); + // always return OK, the MSO status code is embedded in the body + + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + + } + + /** + * Delete svc instance. + * + * @param serviceInstanceId the service instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + + @RequestMapping(value = "/mso_delete_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) + public String deleteSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + HttpServletRequest request, @RequestBody RequestDetails msoRequest, + @RequestParam(value = "serviceStatus") String serviceStatus) { + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), msoRequest); + MsoResponseWrapper w = msoBusinessLogic.deleteSvcInstance(msoRequest, serviceInstanceId, serviceStatus); + // always return OK, the MSO status code is embedded in the body + + return w.getResponse(); + } + + /** + * Delete vnf. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_vnf_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) + + public ResponseEntity deleteVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, + HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "deleteVnf"; + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.deleteVnf(msoRequest, serviceInstanceId, vnfInstanceId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + + } + + /** + * Delete configuration instance + * @param serviceInstanceId the service instance id + * @param configurationId the configuration id + * @param msoRequest the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "mso_delete_configuration/{serviceInstanceId}/configurations/{configurationId}", + method = RequestMethod.POST) + public ResponseEntity deleteConfiguration( + @PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable ("configurationId") String configurationId, + @RequestBody RequestDetailsWrapper msoRequest) { + + String methodName = "deleteConfiguration"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, + "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest.getRequestDetails()); + MsoResponseWrapper w = msoBusinessLogic.deleteConfiguration(msoRequest, serviceInstanceId, configurationId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Activate configuration instance + * @param serviceInstanceId the service instace id + * @param configurationId the configuration id + * @param msoRequest the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "mso_activate_configuration/{serviceInstanceId}/configurations/{configurationId}", + method = RequestMethod.POST) + public ResponseEntity activateConfiguration( + @PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("configurationId") String configurationId, + @RequestBody RequestDetails msoRequest) { + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.setConfigurationActiveStatus(msoRequest, serviceInstanceId, configurationId, true); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Deactivate configuration instance + * @param serviceInstanceId the service instace id + * @param configurationId the configuration id + * @param msoRequest the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "mso_deactivate_configuration/{serviceInstanceId}/configurations/{configurationId}", + method = RequestMethod.POST) + public ResponseEntity deactivateConfiguration( + @PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("configurationId") String configurationId, + @RequestBody RequestDetails msoRequest) { + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.setConfigurationActiveStatus(msoRequest, serviceInstanceId, configurationId, false); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Disable port on configuration instance + * @param serviceInstanceId the service instance id + * @param configurationId the configuration instance id + * @param msoRequest the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "mso_disable_port_configuration/{serviceInstanceId}/configurations/{configurationId}", + method = RequestMethod.POST) + public ResponseEntity disablePortOnConfiguration( + @PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("configurationId") String configurationId, + @RequestBody RequestDetails msoRequest) { + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.setPortOnConfigurationStatus(msoRequest, serviceInstanceId, configurationId, false); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Enable port on configuration instance + * @param serviceInstanceId the service instance id + * @param configurationId the configuration instance id + * @param msoRequest the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "mso_enable_port_configuration/{serviceInstanceId}/configurations/{configurationId}", + method = RequestMethod.POST) + public ResponseEntity enablePortOnConfiguration( + @PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("configurationId") String configurationId, + @RequestBody RequestDetails msoRequest) { + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.setPortOnConfigurationStatus(msoRequest, serviceInstanceId, configurationId, true); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Delete vf module. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param vfModuleId the vf module id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + //mso_delete_vf_module/bc305d54-75b4-431b-adb2-eb6b9e546014/vnfs/fe9000-0009-9999/vfmodules/abeeee-abeeee-abeeee + @RequestMapping(value = "/mso_delete_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfModuleId}", method = RequestMethod.POST) + public ResponseEntity deleteVfModule( + @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, + @PathVariable("vfModuleId") String vfModuleId, HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + + String methodName = "deleteVfModule"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.deleteVfModule(msoRequest, serviceInstanceId, vnfInstanceId, vfModuleId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Delete volume group instance. + * + * @param serviceInstanceId the service instance id + * @param vnfInstanceId the vnf instance id + * @param volumeGroupId the volume group id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupId}", method = RequestMethod.POST) + public ResponseEntity deleteVolumeGroupInstance( + @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, @PathVariable("volumeGroupId") String volumeGroupId, + HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "deleteVolumeGroupInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.deleteVolumeGroupInstance(msoRequest, serviceInstanceId, vnfInstanceId, volumeGroupId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Delete nw instance. + * + * @param serviceInstanceId the service instance id + * @param networkInstanceId the network instance id + * @param request the request + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_delete_nw_instance/{serviceInstanceId}/networks/{networkInstanceId}", method = RequestMethod.POST) + public ResponseEntity deleteNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("networkInstanceId") String networkInstanceId, HttpServletRequest request, @RequestBody RequestDetails msoRequest) { + String methodName = "deleteNwInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + cloudOwnerService.enrichRequestWithCloudOwner(msoRequest); + MsoResponseWrapper w = msoBusinessLogic.deleteNwInstance(msoRequest, serviceInstanceId, networkInstanceId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Gets the orchestration request. + * + * @param requestId the request id + * @param request the request + * @return the orchestration request + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_req/{requestId}", method = RequestMethod.GET) + public ResponseEntity getOrchestrationRequest(@PathVariable("requestId") String requestId, + HttpServletRequest request) { + + String methodName = "getOrchestrationRequest"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + + MsoResponseWrapper w = msoBusinessLogic.getOrchestrationRequest(requestId); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * Gets the orchestration requests. + * + * @param filterString the filter string + * @param request the request + * @return the orchestration requests + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_reqs/{filterString}", method = RequestMethod.GET) + public ResponseEntity getOrchestrationRequests(@PathVariable("filterString") String filterString, + HttpServletRequest request) { + + String methodName = "getOrchestrationRequests"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + + MsoResponseWrapper w = msoBusinessLogic.getOrchestrationRequests(filterString); + + // always return OK, the MSO status code is embedded in the body + return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); + } + + /** + * activate to a pnf instance. + * + * @param serviceInstanceId the id of the service. + * @param requestDetails the body of the request. + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_activate_service_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity activateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) { + String methodName = "activateServiceInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + MsoResponseWrapper w = msoBusinessLogic.setServiceInstanceStatus(requestDetails, serviceInstanceId, true); + return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); + } + + /** + * deactivate a service instance. + * + * @param serviceInstanceId the id of the service. + * @param requestDetails the body of the request. + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_deactivate_service_instance/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity deactivateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) { + String methodName = "deactivateServiceInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + MsoResponseWrapper w = msoBusinessLogic.setServiceInstanceStatus(requestDetails, serviceInstanceId, false); + return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); + } + + /** + * Gets the orchestration requests for the dashboard. + * currently its all the orchestration requests with RequestType updateInstance or replaceInstance. + * @return the orchestration requests + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_orch_reqs/dashboard", method = RequestMethod.GET) + public List getOrchestrationRequestsForDashboard() { + + String methodName = "getOrchestrationRequestsForDashboard"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + + return msoBusinessLogic.getOrchestrationRequestsForDashboard(); + } + + /** + * Gets the Manual Tasks for the given request id. + * + * @param originalRequestId the id of the original request. + * @return the tasks + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_get_man_task/{originalRequestId}", method = RequestMethod.GET) + public List getManualTasksByRequestId(@PathVariable("originalRequestId") String originalRequestId) { + + String methodName = "getManualTasksByRequestId"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + return msoBusinessLogic.getManualTasksByRequestId(originalRequestId); + } + + /** + * Complete the manual task. + * + * @param taskId the id of the task to complete. + * @param requestDetails the body of the request. + * @return the response entity + * @throws Exception the exception + */ + @RequestMapping(value = "/mso_post_man_task/{taskId}", method = RequestMethod.POST) + public ResponseEntity manualTaskComplete(@PathVariable("taskId") String taskId , @RequestBody RequestDetails requestDetails) { + + String methodName = "manualTaskComplete"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + MsoResponseWrapper w = msoBusinessLogic.completeManualTask(requestDetails, taskId); + return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); + } + + @RequestMapping(value = "/mso_remove_relationship/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity removeRelationshipFromServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId , + @RequestBody RequestDetails requestDetails) { + + String methodName = "removeRelationshipFromServiceInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + MsoResponseWrapper w; + try { + w = msoBusinessLogic.removeRelationshipFromServiceInstance(requestDetails, serviceInstanceId); + } catch (Exception e){ + LOGGER.error("Internal error when calling MSO controller logic for {}", methodName, e); + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); + } + + @RequestMapping(value = "/mso_add_relationship/{serviceInstanceId}", method = RequestMethod.POST) + public ResponseEntity addRelationshipToServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId , + @RequestBody RequestDetails requestDetails) { + + String methodName = "addRelationshipToServiceInstance"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + MsoResponseWrapper w; + try { + w = msoBusinessLogic.addRelationshipToServiceInstance(requestDetails, serviceInstanceId); + } catch (Exception e){ + LOGGER.error("Internal error when calling MSO controller logic for {}", methodName, e); + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } + return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); + } + + @RequestMapping(value = "/mso_activate_fabric_configuration/{serviceInstanceId}", method = RequestMethod.POST) + public MsoResponseWrapper2 activateFabricConfiguration( + @PathVariable("serviceInstanceId") String serviceInstanceId , + @RequestBody RequestDetails requestDetails) { + + String methodName = "activateFabricConfiguration"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + return msoBusinessLogic.activateFabricConfiguration(serviceInstanceId, requestDetails); + } + + @RequestMapping(value = "/mso_vfmodule_soft_delete/{serviceInstanceId}/{vnfInstanceId}/{vfModuleInstanceId}", method = RequestMethod.POST) + public MsoResponseWrapper2 deactivateAndCloudDelete( + @PathVariable("serviceInstanceId") String serviceInstanceId, + @PathVariable("vnfInstanceId") String vnfInstanceId, + @PathVariable("vfModuleInstanceId") String vfModuleInstanceId, + @RequestBody SoftDeleteRequest softDeleteRequest) { + + String methodName = "deactivateAndCloudDelete"; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + START_LOG); + + RequestDetails requestDetails = msoBusinessLogic.buildRequestDetailsForSoftDelete(softDeleteRequest); + + cloudOwnerService.enrichRequestWithCloudOwner(requestDetails); + return msoBusinessLogic.deactivateAndCloudDelete(serviceInstanceId, vnfInstanceId, vfModuleInstanceId, requestDetails); + } + + + /** + * Exception handler. + * + * @param e the e + * @param response the response + * @throws IOException Signals that an I/O exception has occurred. + */ + @ExceptionHandler(Exception.class) + private void exceptionHandler(Exception e, HttpServletResponse response) throws IOException { + + ControllersUtils.handleException(e, LOGGER); + + response.setContentType("application/json; charset=UTF-8"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + + ExceptionResponse exceptionResponse = new ExceptionResponse(); + exceptionResponse.setException(e.getClass().toString().replaceFirst("^.*\\.", "")); + exceptionResponse.setMessage(e.getMessage()); + + response.getWriter().write(new ObjectMapper().writeValueAsString(exceptionResponse)); + + response.flushBuffer(); + + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java b/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java new file mode 100644 index 00000000..21aef685 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/OperationalEnvironmentController.java @@ -0,0 +1,362 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 Nokia. 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.vid.controller; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.base.MoreObjects; +import io.joshworks.restclient.http.HttpResponse; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.MsoResponseWrapper2; +import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; +import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; +import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; +import org.onap.vid.mso.rest.RequestDetails; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.onap.vid.utils.Logging.getMethodCallerName; +import static org.onap.vid.utils.Logging.getMethodName; + +@RestController +@RequestMapping("operationalEnvironment") +public class OperationalEnvironmentController extends VidRestrictedBaseController { + + private final MsoInterface restMso; + private final MsoBusinessLogic msoBusinessLogic; + + private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("from String \"(.*)\": value not"); + + + @Autowired + public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoInterface msoClientInterface) { + this.restMso = msoClientInterface; + this.msoBusinessLogic = msoBusinessLogic; + } + + @RequestMapping(value = "/create", method = RequestMethod.POST) + public MsoResponseWrapper2 createOperationalEnvironment(HttpServletRequest request, @RequestBody OperationalEnvironmentCreateBody operationalEnvironment) { + debugStart(operationalEnvironment); + String userId = ControllersUtils.extractUserId(request); + RequestDetailsWrapper requestDetailsWrapper = msoBusinessLogic.convertParametersToRequestDetails(operationalEnvironment, userId); + String path = msoBusinessLogic.getOperationalEnvironmentCreationPath(); + + HttpResponse msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); + debugEnd(msoResponse); + return new MsoResponseWrapper2<>(msoResponse); + } + + @RequestMapping(value = "/activate", method = RequestMethod.POST) + public MsoResponseWrapper2 activate(HttpServletRequest request, + @RequestParam("operationalEnvironment") String operationalEnvironmentId, + @RequestBody OperationalEnvironmentActivateBody activateRequest) throws MissingServletRequestParameterException { + + verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment"); + + //manifest is null in case of wrong manifest structure (deserialization failure of the manifest) + if (activateRequest.getManifest()==null || activateRequest.getManifest().getServiceModelList()==null) { + throw new BadManifestException("Manifest structure is wrong"); + } + + String userId = ControllersUtils.extractUserId(request); + + OperationalEnvironmentActivateInfo activateInfo = new OperationalEnvironmentActivateInfo(activateRequest, userId, operationalEnvironmentId); + debugStart(activateInfo); + + String path = msoBusinessLogic.getOperationalEnvironmentActivationPath(activateInfo); + RequestDetailsWrapper requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentActivationRequestDetails(activateInfo); + + HttpResponse msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); + + debugEnd(msoResponse); + return new MsoResponseWrapper2<>(msoResponse); + } + + @RequestMapping(value = "/deactivate", method = RequestMethod.POST) + public MsoResponseWrapper2 deactivate(HttpServletRequest request, + @RequestParam("operationalEnvironment") String operationalEnvironmentId, + @RequestBody Map deactivationRequest) throws MissingServletRequestParameterException { + + verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment"); + + String userId = ControllersUtils.extractUserId(request); + + OperationalEnvironmentDeactivateInfo deactivateInfo = new OperationalEnvironmentDeactivateInfo(userId, operationalEnvironmentId); + debugStart(deactivateInfo); + + String path = msoBusinessLogic.getOperationalEnvironmentDeactivationPath(deactivateInfo); + RequestDetailsWrapper requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentDeactivationRequestDetails(deactivateInfo); + + HttpResponse msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); + + debugEnd(msoResponse); + return new MsoResponseWrapper2<>(msoResponse); + } + + @RequestMapping(value = "/requestStatus", method = RequestMethod.GET) + public MsoResponseWrapper2 status(HttpServletRequest request, @RequestParam("requestId") String requestId) throws MissingServletRequestParameterException { + + debugStart(requestId); + + verifyIsNotEmpty(requestId, "requestId"); + String path = msoBusinessLogic.getCloudResourcesRequestsStatusPath(requestId); + + HttpResponse msoResponse = restMso.get(path, HashMap.class); + + LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), msoResponse); + return new MsoResponseWrapper2<>(msoResponse); + } + + @ExceptionHandler({ + org.springframework.web.bind.MissingServletRequestParameterException.class, + BadManifestException.class + }) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public ExceptionResponse clientDerivedExceptionAsBadRequest(Exception e) { + // same handler, different HTTP Code + return exceptionHandler(e); + } + + @ExceptionHandler({ + org.springframework.http.converter.HttpMessageNotReadableException.class, + }) + @ResponseStatus(value = HttpStatus.BAD_REQUEST) + public ExceptionResponse handlingHttpMessageNotReadableException(Exception e) { + //in case of wrong value in manifest for RecoveryAction the message contains the class name. + //The wrong value is in also part of this messages + //within the pattern of: String value '': value not + //so we use regex to find the wrong value + if (e.getMessage().contains(OperationalEnvironmentRecoveryAction.class.getName())) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodName(), ExceptionUtils.getMessage(e), e); + String message = "Wrong value for RecoveryAction in manifest. Allowed options are: "+OperationalEnvironmentRecoveryAction.options; + + Matcher matcher = RECOVERY_ACTION_MESSAGE_PATTERN.matcher(e.getMessage()); + if (matcher.find()) { + String wrongValue = matcher.group(1); + message = message+". Wrong value is: "+wrongValue; + } + return new ExceptionResponse(new BadManifestException(message)); + } + return exceptionHandler(e); + } + + + public enum OperationalEnvironmentRecoveryAction { + abort, + retry, + skip; + + public static final String options = Stream.of(OperationalEnvironmentRecoveryAction.values()).map(OperationalEnvironmentRecoveryAction::name).collect(Collectors.joining(", ")); + } + + public static class ActivateServiceModel { + private String serviceModelVersionId; + private OperationalEnvironmentRecoveryAction recoveryAction; + + public ActivateServiceModel() { + } + + public ActivateServiceModel(String serviceModelVersionId, OperationalEnvironmentRecoveryAction recoveryAction) { + this.serviceModelVersionId = serviceModelVersionId; + this.recoveryAction = recoveryAction; + } + + public String getServiceModelVersionId() { + return serviceModelVersionId; + } + + public void setServiceModelVersionId(String serviceModelVersionId) { + this.serviceModelVersionId = serviceModelVersionId; + } + + public OperationalEnvironmentRecoveryAction getRecoveryAction() { + return recoveryAction; + } + + public void setRecoveryAction(OperationalEnvironmentRecoveryAction recoveryAction) { + this.recoveryAction = recoveryAction; + } + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class OperationalEnvironmentManifest { + + + private List serviceModelList; + + public OperationalEnvironmentManifest() { + } + + public OperationalEnvironmentManifest(List serviceModelList) { + this.serviceModelList = serviceModelList; + } + + public List getServiceModelList() { + return serviceModelList; + } + + public void setServiceModelList(List serviceModelList) { + this.serviceModelList = serviceModelList; + } + } + + public static class OperationalEnvironmentActivateBody { + private final String relatedInstanceId; + private final String relatedInstanceName; + private final String workloadContext; + private final OperationalEnvironmentManifest manifest; + + public OperationalEnvironmentActivateBody(@JsonProperty(value = "relatedInstanceId", required = true) String relatedInstanceId, + @JsonProperty(value = "relatedInstanceName", required = true) String relatedInstanceName, + @JsonProperty(value = "workloadContext", required = true) String workloadContext, + @JsonProperty(value = "manifest", required = true) OperationalEnvironmentManifest manifest) { + this.relatedInstanceId = relatedInstanceId; + this.relatedInstanceName = relatedInstanceName; + this.workloadContext = workloadContext; + this.manifest = manifest; + } + + + public String getRelatedInstanceId() { + return relatedInstanceId; + } + + public String getRelatedInstanceName() { + return relatedInstanceName; + } + + public String getWorkloadContext() { + return workloadContext; + } + + public OperationalEnvironmentManifest getManifest() { + return manifest; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("relatedInstanceId", relatedInstanceId) + .add("relatedInstanceName", relatedInstanceName) + .add("workloadContext", workloadContext) + .add("manifest", manifest) + .toString(); + } + } + + public static class OperationalEnvironmentCreateBody { + private final String instanceName; + private final String ecompInstanceId; + private final String ecompInstanceName; + private final String operationalEnvironmentType; + private final String tenantContext; + private final String workloadContext; + + public OperationalEnvironmentCreateBody(@JsonProperty(value = "instanceName", required = true) String instanceName, + @JsonProperty(value = "ecompInstanceId", required = true) String ecompInstanceId, + @JsonProperty(value = "ecompInstanceName", required = true) String ecompInstanceName, + @JsonProperty(value = "operationalEnvironmentType", required = true) String operationalEnvironmentType, + @JsonProperty(value = "tenantContext", required = true) String tenantContext, + @JsonProperty(value = "workloadContext", required = true) String workloadContext) { + this.instanceName = instanceName; + this.ecompInstanceId = ecompInstanceId; + this.ecompInstanceName = ecompInstanceName; + this.operationalEnvironmentType = operationalEnvironmentType; + this.tenantContext = tenantContext; + this.workloadContext = workloadContext; + } + + public String getInstanceName() { + return instanceName; + } + + public String getEcompInstanceId() { + return ecompInstanceId; + } + + public String getEcompInstanceName() { + return ecompInstanceName; + } + + public String getOperationalEnvironmentType() { + return operationalEnvironmentType; + } + + public String getTenantContext() { + return tenantContext; + } + + public String getWorkloadContext() { + return workloadContext; + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("instanceName", instanceName) + .add("ecompInstanceId", ecompInstanceId) + .add("ecompInstanceName", ecompInstanceName) + .add("operationalEnvironmentType", operationalEnvironmentType) + .add("tenantContext", tenantContext) + .add("workloadContext", workloadContext) + .toString(); + } + } + + private void debugEnd(HttpResponse msoResponse) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), msoResponse); + } + + private void debugStart(Object requestInfo) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodCallerName(), requestInfo); + } + + private void verifyIsNotEmpty(String fieldValue, String fieldName) throws MissingServletRequestParameterException { + if (StringUtils.isEmpty(fieldValue)) { + throw new MissingServletRequestParameterException(fieldName, "String"); + } + } + + public static class BadManifestException extends RuntimeException { + public BadManifestException(String message) { + super(message); + } + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/ProbeController.java b/vid-app-common/src/main/java/org/onap/vid/controller/ProbeController.java new file mode 100644 index 00000000..1324ebb1 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/ProbeController.java @@ -0,0 +1,42 @@ +package org.onap.vid.controller; + +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.vid.aai.AaiClient; +import org.onap.vid.model.probes.ExternalComponentStatus; +import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.scheduler.SchedulerService; +import org.onap.vid.services.VidService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.List; + +@RestController +@RequestMapping("probe") +public class ProbeController extends RestrictedBaseController { + + private final AaiClient aaiClient; + private final VidService vidService; + private final MsoBusinessLogic msoBusinessLogic; + private final SchedulerService schedulerService; + + @Autowired + public ProbeController(AaiClient aaiClient, VidService vidService, MsoBusinessLogic msoBusinessLogic, SchedulerService schedulerService) { + this.aaiClient = aaiClient; + this.vidService = vidService; + this.msoBusinessLogic = msoBusinessLogic; + this.schedulerService = schedulerService; + } + + @RequestMapping(method= RequestMethod.GET) + public List getProbe() { + List componentStatuses = new ArrayList<>(); + componentStatuses.add(aaiClient.probeAaiGetAllSubscribers()); + componentStatuses.add(schedulerService.probeGetSchedulerChangeManagements()); + return componentStatuses; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/PropertyController.java b/vid-app-common/src/main/java/org/onap/vid/controller/PropertyController.java new file mode 100644 index 00000000..2f8d6e29 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/PropertyController.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.controller; + +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.category.CategoryParametersResponse; +import org.onap.vid.model.CategoryParameter.Family; +import org.onap.vid.services.CategoryParameterService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; + +import static org.onap.vid.utils.Logging.getMethodName; + +/** + * The Class PropertyController. + */ +@RestController +public class PropertyController extends RestrictedBaseController{ + + + /** The logger. */ + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(PropertyController.class); + + @Autowired + protected CategoryParameterService categoryParameterService; + + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/propertyhome" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== PropertyController welcome start"); + return new ModelAndView(getViewName()); + } + + /** + * Gets the property. + * + * @param name the name + * @param defaultvalue the defaultvalue + * @param request the request + * @return the property + * @throws Exception the exception + */ + @RequestMapping(value = "/get_property/{name}/{defaultvalue}", method = RequestMethod.GET) + public ResponseEntity getProperty (@PathVariable("name") String name, @PathVariable("defaultvalue") String defaultvalue, + HttpServletRequest request) { + + String methodName = "getProperty"; + ResponseEntity resp = null; + String pvalue = null; + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " start"); + + try { + // convert "_" to "." in the property name + if (name == null || name.length() == 0 ) { + return ( new ResponseEntity (defaultvalue, HttpStatus.OK)); + } + // convert "_" to "." in the property name + String propertyName = name.replace('_', '.'); + pvalue = SystemProperties.getProperty(propertyName); + if ( ( pvalue == null ) || ( pvalue.length() == 0 ) ) { + pvalue = defaultvalue; + } + resp = new ResponseEntity<>(pvalue, HttpStatus.OK); + } + catch (Exception e) { + LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + e.toString()); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + e.toString()); + throw e; + } + LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " returning " + pvalue); + return ( resp ); + } + + /** + * Gets the owning entity properties. + * @param request the request + * @return the property + * @throws Exception the exception + */ + @RequestMapping(value = "/category_parameter", method = RequestMethod.GET) + public ResponseEntity getCategoryParameter(HttpServletRequest request, @RequestParam(value="familyName", required = true) Family familyName) { + LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); + try { + CategoryParametersResponse response = categoryParameterService.getCategoryParameters(familyName); + LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); + return new ResponseEntity<>(response, HttpStatus.OK); + } + catch (Exception exception) { + LOGGER.error("failed to retrieve category parameter list from DB.", exception); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/RoleGeneratorController.java b/vid-app-common/src/main/java/org/onap/vid/controller/RoleGeneratorController.java new file mode 100644 index 00000000..78f1e37d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/RoleGeneratorController.java @@ -0,0 +1,26 @@ +package org.onap.vid.controller; + +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.vid.services.RoleGeneratorService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class RoleGeneratorController extends UnRestrictedBaseController { + @Autowired + private RoleGeneratorService roleGeneratorService; + public static final String GENERATE_ROLE_SCRIPT = "generateRoleScript"; + @RequestMapping(value = GENERATE_ROLE_SCRIPT +"/{firstRun}", method = RequestMethod.GET ) + public ResponseEntity generateRoleScript (@PathVariable("firstRun") boolean firstRun) { + ResponseEntity response = null; + String query = roleGeneratorService.generateRoleScript(firstRun); + response = new ResponseEntity<>(query, HttpStatus.OK); + return response; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/VersionController.java b/vid-app-common/src/main/java/org/onap/vid/controller/VersionController.java new file mode 100644 index 00000000..ba879ed1 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/VersionController.java @@ -0,0 +1,63 @@ +package org.onap.vid.controller; + + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.StringUtils; +import org.onap.portalsdk.core.controller.UnRestrictedBaseController; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import javax.inject.Inject; +import javax.servlet.ServletContext; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.apache.commons.lang3.StringUtils.substringAfterLast; + +@RestController +@RequestMapping("version") +public class VersionController extends UnRestrictedBaseController { + + private final ServletContext servletContext; + + @Inject + public VersionController(ServletContext servletContext) { + this.servletContext = servletContext; + } + + @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + public Map getVersionAndFeatures() + { + String features = SystemProperties.getProperty("features.set.filename"); + String version; + try { + final URL resource = servletContext.getResource("/app/vid/scripts/constants/version.json"); + HashMap versionFile = new HashMap <>(); + ObjectMapper mapper = new ObjectMapper(); + versionFile.putAll(mapper.readValue(resource, new TypeReference>() {})); + version = versionFile.get("Version"); + } catch (IOException e) { + version = "Error retrieving build number"; + } + String majorVersion = getDisplayVersion(features, version); + return ImmutableMap.of("Features", features, "Build", version, "DisplayVersion", majorVersion); + } + + String getDisplayVersion(String features, String build) { + Matcher matcher = Pattern.compile("([^/]+?)(\\.features|$)").matcher(features); + final String majorByFeatures = matcher.find() ? matcher.group(1) : features; + + final String buildByVersion = StringUtils.defaultIfBlank(substringAfterLast(build, "."), build); + + return StringUtils.join(majorByFeatures, ".", buildByVersion); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/VidController.java b/vid-app-common/src/main/java/org/onap/vid/controller/VidController.java new file mode 100644 index 00000000..40d0f462 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/VidController.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.vid.controller; + +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.SecureServices; +import org.onap.vid.exceptions.VidServiceUnavailableException; +import org.onap.vid.model.PombaInstance.PombaRequest; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.roles.Role; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.services.AaiService; +import org.onap.vid.services.PombaService; +import org.onap.vid.services.VidService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +@RestController +public class VidController extends RestrictedBaseController { + + private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidController.class); + + private final VidService vidService; + private final AaiService aaiService; + private final RoleProvider roleProvider; + private final PombaService pombaService; + + @Autowired + public VidController(VidService vidService, AaiService aaiService, RoleProvider roleProvider, + PombaService pombaService) { + this.vidService = vidService; + this.aaiService = aaiService; + this.roleProvider = roleProvider; + this.pombaService = pombaService; + } + + /** + * @param request the request + * @return the services + */ + @RequestMapping(value = {"/rest/models/services"}, method = RequestMethod.GET) + public SecureServices getServices(HttpServletRequest request) { + LOG.info("Start API for browse ASDC was called"); + SecureServices secureServices = new SecureServices(); + List roles = roleProvider.getUserRoles(request); + secureServices.setServices(aaiService.getServicesByDistributionStatus()); + secureServices.setReadOnly(roleProvider.userPermissionIsReadOnly(roles)); + return secureServices; + } + + + /** + * @param uuid the uuid + * @return the services + * @throws VidServiceUnavailableException the vid service unavailable exception + */ + @RequestMapping(value = {"/rest/models/services/{uuid}"}, method = RequestMethod.GET) + public ServiceModel getService(@PathVariable("uuid") String uuid) throws VidServiceUnavailableException { + try { + return vidService.getService(uuid); + } catch (AsdcCatalogException e) { + LOG.error("Failed to retrieve service definitions from SDC. Error: " + e.getMessage(), e); + throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e); + } + } + + @RequestMapping(value = "/rest/models/reset", method = RequestMethod.POST) + @ResponseStatus(HttpStatus.ACCEPTED) + public void invalidateServiceModelCache() { + vidService.invalidateServiceCache(); + } + + /** + * @return the services view + * @throws VidServiceUnavailableException the vid service unavailable exception + */ + // FIX ME: Circular view path [serviceModels]: would dispatch back to the current handler URL [/serviceModels] again. + @RequestMapping(value = {"/serviceModels"}, method = RequestMethod.GET) + public ModelAndView getServicesView() { + return new ModelAndView("serviceModels"); + } + + @RequestMapping(value = {"/rest/models/services/verifyService"}, method = RequestMethod.POST) + public void verifyServiceInstance(@RequestBody PombaRequest pombaRequest) { + pombaService.verify(pombaRequest); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/VidRestrictedBaseController.java b/vid-app-common/src/main/java/org/onap/vid/controller/VidRestrictedBaseController.java new file mode 100644 index 00000000..e13cf451 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/VidRestrictedBaseController.java @@ -0,0 +1,42 @@ +package org.onap.vid.controller; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.model.ExceptionResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import static org.onap.vid.utils.Logging.getMethodCallerName; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; + +public abstract class VidRestrictedBaseController extends RestrictedBaseController { + + protected final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(this.getClass().getName()); + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + @ResponseBody + public ResponseEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodCallerName(), ExceptionUtils.getMessage(e), e); + Class type = e.getRequiredType(); + String message; + if (type.isEnum()) { + message = "The parameter " + e.getName() + " must have a value among : " + StringUtils.join(type.getEnumConstants(), ", "); + } + else { + message = "The parameter " + e.getName() + " must be of type " + type.getTypeName(); + } + return new ResponseEntity(message, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(value=INTERNAL_SERVER_ERROR) + public ExceptionResponse exceptionHandler(Exception e) { + return ControllersUtils.handleException(e, LOGGER); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/ViewLogController.java b/vid-app-common/src/main/java/org/onap/vid/controller/ViewLogController.java new file mode 100644 index 00000000..4956c5b1 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/ViewLogController.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.controller; + +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + + +/** + * The Class ViewLogController. + */ +@RestController +public class ViewLogController extends RestrictedBaseController{ + + /** The logger. */ + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ViewLogController.class); + + /** The Constant dateFormat. */ + static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + /** The servlet context. */ + private @Autowired ServletContext servletContext; + + /** + * Welcome. + * + * @param request the request + * @return the model and view + */ + @RequestMapping(value = {"/viewlog" }, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { + + return new ModelAndView(getViewName()); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java new file mode 100644 index 00000000..68d5b71d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/controller/WebConfig.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 Nokia. 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.vid.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import io.joshworks.restclient.http.mapper.ObjectMapper; +import org.onap.vid.aai.*; +import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.util.*; +import org.onap.vid.asdc.AsdcClient; +import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.asdc.parser.VidNotionsBuilder; +import org.onap.vid.asdc.rest.SdcRestClient; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.client.SyncRestClientInterface; +import org.onap.vid.properties.AsdcClientConfiguration; +import org.onap.vid.scheduler.SchedulerService; +import org.onap.vid.scheduler.SchedulerServiceImpl; +import org.onap.vid.services.*; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.togglz.core.manager.FeatureManager; + +import javax.servlet.ServletContext; +import java.io.File; +import java.io.IOException; + +@Configuration +public class WebConfig { + + /** + * Gets the object mapper. + * + * @return the object mapper + */ + @Bean + public com.fasterxml.jackson.databind.ObjectMapper getObjectMapper() { + return new com.fasterxml.jackson.databind.ObjectMapper(); + } + + + @Bean + public VidService vidService(AsdcClient asdcClient, FeatureManager featureManager) { + return new VidServiceImpl(asdcClient, featureManager); + } + + @Bean + public SchedulerService schedulerService(ChangeManagementService changeManagementService) { + return new SchedulerServiceImpl(changeManagementService); + } + + @Bean + public AaiService getAaiService() { + return new AaiServiceImpl(); + } + + @Bean + public AaiResponseTranslator aaiResponseTranslator() { + return new AaiResponseTranslator(); + } + + @Bean + public PortDetailsTranslator portDetailsTranslator() { + return new PortDetailsTranslator(); + } + + @Bean + public AaiClientInterface getAaiRestInterface(@Qualifier("aaiRestInterface") AAIRestInterface restController, PortDetailsTranslator portsDetailsTranslator, CacheProvider cacheProvider) { + return new AaiClient(restController, portsDetailsTranslator, cacheProvider); + } + + @Bean(name = "aaiRestInterface") + public AAIRestInterface aaiRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) { + return new AAIRestInterface(httpsAuthClientFactory, servletRequestHelper, systemPropertyHelper); + } + + @Bean + public PombaRestInterface getPombaRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) { + return new PombaRestInterface(httpsAuthClientFactory, servletRequestHelper, systemPropertyHelper); + } + + @Bean + public SSLContextProvider sslContextProvider() { + return new SSLContextProvider(); + } + + @Bean + public SystemPropertyHelper systemPropertyHelper() { + return new SystemPropertyHelper(); + } + + @Bean + public ServletRequestHelper servletRequestHelper() { + return new ServletRequestHelper(); + } + + @Bean + public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider ,FeatureManager featureManager) { + final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath(); + return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider, featureManager); + } + + @Bean + public AsdcClient sdcClient(AsdcClientConfiguration asdcClientConfiguration, SyncRestClientInterface syncRestClient) { + String auth = asdcClientConfiguration.getAsdcClientAuth(); + String host = asdcClientConfiguration.getAsdcClientHost(); + String protocol = asdcClientConfiguration.getAsdcClientProtocol(); + int port = asdcClientConfiguration.getAsdcClientPort(); + + return new SdcRestClient(protocol + "://" + host + ":" + port + "/", auth, syncRestClient); + } + + @Bean + public SyncRestClientInterface syncRestClient() { + return new SyncRestClient(); + } + + @Bean + public VidNotionsBuilder vidNotionsBuilder(FeatureManager featureManager) { + return new VidNotionsBuilder(featureManager); + } + + @Bean + public ToscaParserImpl2 getToscaParser(VidNotionsBuilder vidNotionsBuilder) { + return new ToscaParserImpl2(vidNotionsBuilder); + } + + @Bean + public PombaService getVerifyServiceInstanceService() { + return new PombaServiceImpl(); + } + + @Bean + public PombaClientInterface getVerifyServiceInstanceClientInterface() { + return new PombaClientImpl(); + } + + @Bean + public ServiceInstanceStandardQuery serviceInstanceStandardQuery(AaiClientInterface aaiClient) { + return new ServiceInstanceStandardQuery(aaiClient); + } + + @Bean + public AaiOverTLSClientInterface aaiOverTLSClient(ObjectMapper unirestObjectMapper){ + return new AaiOverTLSClient(new SyncRestClient(unirestObjectMapper), new AaiOverTLSPropertySupplier()); + } + + @Bean + public ObjectMapper unirestFasterxmlObjectMapper(com.fasterxml.jackson.databind.ObjectMapper objectMapper) { + return new ObjectMapper() { + + @Override + public T readValue(String s, Class aClass) { + try { + return objectMapper.readValue(s, aClass); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public String writeValue(Object o) { + try { + return objectMapper.writeValueAsString(o); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + }; + + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java b/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java index d4c7e3c5..cba36a79 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/filter/ClientCredentialsFilter.java @@ -20,7 +20,7 @@ import java.io.IOException; @WebFilter(urlPatterns = "/change-management/workflow/*") public class ClientCredentialsFilter extends GenericFilterBean { - private final static EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ClientCredentialsFilter.class); + private static final EELFLoggerDelegate filterLogger = EELFLoggerDelegate.getLogger(ClientCredentialsFilter.class); @Override @@ -33,12 +33,12 @@ public class ClientCredentialsFilter extends GenericFilterBean { String actualAuthorization = ((HttpServletRequest)request).getHeader("Authorization"); if (verifyClientCredentials(actualAuthorization, expectedAuthorization)) { - LOGGER.warn(EELFLoggerDelegate.debugLogger,"Client credentials authenticated."); + filterLogger.warn(EELFLoggerDelegate.debugLogger,"Client credentials authenticated."); chain.doFilter(request, response); return; } - LOGGER.warn(EELFLoggerDelegate.debugLogger,"Client did not provide the expected credentials."); + filterLogger.warn(EELFLoggerDelegate.debugLogger,"Client did not provide the expected credentials."); ((HttpServletResponse) response).sendError(401); } @@ -46,13 +46,13 @@ public class ClientCredentialsFilter extends GenericFilterBean { { if (StringUtils.isEmpty(expectedAuthorization)) { - LOGGER.warn(EELFLoggerDelegate.debugLogger,String.format("Expected Authorization is not configured (key: %s)", SchedulerProperties.SCHEDULER_BASIC_AUTH)); + filterLogger.warn(EELFLoggerDelegate.debugLogger,String.format("Expected Authorization is not configured (key: %s)", SchedulerProperties.SCHEDULER_BASIC_AUTH)); return true; } if (StringUtils.isEmpty(actualAuthorization)) { - LOGGER.warn(EELFLoggerDelegate.debugLogger,"Authorization header is missing."); + filterLogger.warn(EELFLoggerDelegate.debugLogger,"Authorization header is missing."); return false; } diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/filter/PromiseEcompRequestIdFilter.java b/vid-app-common/src/main/java/org/onap/vid/controller/filter/PromiseEcompRequestIdFilter.java index 7501b103..9c1cb463 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/filter/PromiseEcompRequestIdFilter.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/filter/PromiseEcompRequestIdFilter.java @@ -3,7 +3,6 @@ package org.onap.vid.controller.filter; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; @@ -24,8 +23,7 @@ import static org.onap.portalsdk.core.util.SystemProperties.ECOMP_REQUEST_ID; @WebFilter(urlPatterns = "/*") public class PromiseEcompRequestIdFilter extends GenericFilterBean { - private final static EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(PromiseEcompRequestIdFilter.class); - private final static String REQUEST_ID_RESPONSE_HEADER = ECOMP_REQUEST_ID + "-echo"; + private static final String REQUEST_ID_RESPONSE_HEADER = ECOMP_REQUEST_ID + "-echo"; @Override @@ -48,13 +46,19 @@ public class PromiseEcompRequestIdFilter extends GenericFilterBean { final HttpServletRequest httpRequest = (HttpServletRequest) request; final String originalRequestId = httpRequest.getHeader(ECOMP_REQUEST_ID); - if (StringUtils.isEmpty(originalRequestId)) { + if (StringUtils.isEmpty(originalRequestId) || !verifyAndValidateUuid(originalRequestId)) { request = new PromiseEcompRequestIdRequestWrapper(httpRequest); } return request; } + public static boolean verifyAndValidateUuid(String value) + { + String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + return value.matches(uuidRegex); + } + private static class PromiseEcompRequestIdRequestWrapper extends HttpServletRequestWrapper { private final UUID requestId; @@ -81,12 +85,17 @@ public class PromiseEcompRequestIdFilter extends GenericFilterBean { @Override public Enumeration getHeaderNames() { + + if (null == super.getHeader(ECOMP_REQUEST_ID)) { return Collections.enumeration(ImmutableList.builder() .add(ECOMP_REQUEST_ID) .addAll(Collections.list(super.getHeaderNames())) .build()); } + return super.getHeaderNames(); + } + private boolean isRequestIdHeaderName(String name) { return ECOMP_REQUEST_ID.equalsIgnoreCase(name); } diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAaiController.java b/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAaiController.java index c57d93cb..511e8631 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAaiController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAaiController.java @@ -20,7 +20,7 @@ package org.onap.vid.controller.test; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.vid.model.ExceptionResponse; import org.springframework.web.bind.annotation.*; diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAsdcController.java b/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAsdcController.java index ae639647..da79ef9b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAsdcController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/test/TestAsdcController.java @@ -20,7 +20,7 @@ package org.onap.vid.controller.test; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.vid.model.ExceptionResponse; import org.springframework.web.bind.annotation.*; diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/test/TestMsoController.java b/vid-app-common/src/main/java/org/onap/vid/controller/test/TestMsoController.java index ba4476fa..4cb0d6c1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/test/TestMsoController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/test/TestMsoController.java @@ -20,7 +20,7 @@ package org.onap.vid.controller.test; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.vid.model.ExceptionResponse; import org.springframework.http.HttpStatus; diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java deleted file mode 100644 index 1a426ed2..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java +++ /dev/null @@ -1,763 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.controllers; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.codehaus.jackson.map.ObjectMapper; -import org.onap.vid.aai.AaiResponse; -import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; -import org.onap.vid.aai.ServiceInstancesSearchResults; -import org.onap.vid.aai.SubscriberData; -import org.onap.vid.aai.SubscriberFilteredResults; -import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion; -import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; -import org.onap.vid.aai.model.AaiGetPnfs.Pnf; -import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; -import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.vid.model.VersionByInvariantIdsRequest; -import org.onap.vid.roles.Role; -import org.onap.vid.roles.RoleProvider; -import org.onap.vid.roles.RoleValidator; -import org.onap.vid.services.AaiService; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.HandlerMapping; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.QueryParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.stream.Collectors; - -import static org.onap.vid.utils.Logging.getMethodName; - -/** - * Controller to handle a&ai requests. - */ - -@RestController -public class AaiController extends RestrictedBaseController { - /** - * The Constant dateFormat. - */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** - * The from app id. - */ - protected String fromAppId = "VidAaiController"; - /** - * The logger. - */ - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiController.class); - /** - * The model. - */ - private Map model = new HashMap(); - /** - * The servlet context. - */ - @Autowired - private ServletContext servletContext; - /** - * aai service - */ - @Autowired - private AaiService aaiService; - @Autowired - private RoleProvider roleProvider; - - @Autowired - private AAIRestInterface aaiRestInterface; - - /** - * Welcome method. - * - * @param request the request - * @return ModelAndView The view - */ - @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== AaiController welcome start"); - return new ModelAndView(getViewName()); - } - - @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET) - public ResponseEntity getAicZones(HttpServletRequest request) throws IOException { - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZones controller start"); - AaiResponse response = aaiService.getAaiZones(); - return aaiResponseToResponseEntity(response); - } - - @RequestMapping(value = {"/aai_get_aic_zone_for_pnf/{globalCustomerId}/{serviceType}/{serviceId}"}, method = RequestMethod.GET) - public ResponseEntity getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId ,@PathVariable("serviceType") String serviceType , @PathVariable("serviceId") String serviceId ,HttpServletRequest request) throws IOException { - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZoneForPnf controller start"); - AaiResponse response = aaiService.getAicZoneForPnf(globalCustomerId , serviceType , serviceId); - return aaiResponseToResponseEntity(response); - } - - @RequestMapping(value = {"/aai_get_instance_groups_by_vnf_instance_id/{vnfInstanceId}"}, method = RequestMethod.GET) - public ResponseEntity getInstanceGroupsByVnfInstanceId(@PathVariable("vnfInstanceId") String vnfInstanceId ,HttpServletRequest request) throws IOException { - AaiResponse response = aaiService.getInstanceGroupsByVnfInstanceId(vnfInstanceId); - return aaiResponseToResponseEntity(response); - } - /** - * Get services from a&ai. - * - * @return ResponseEntity The response entity with the logged in user uuid. - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET) - public ResponseEntity getUserID(HttpServletRequest request) { - - String userId = ControllersUtils.extractUserId(request); - - return new ResponseEntity(userId, HttpStatus.OK); - } - - /** - * Get services from a&ai. - * - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity doGetServices(HttpServletRequest request) throws IOException { - RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request)); - - AaiResponse subscriberList = aaiService.getServices(roleValidator); - ResponseEntity responseEntity = aaiResponseToResponseEntity(subscriberList); - - return responseEntity; - } - - - @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST) - public ResponseEntity getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) { - ResponseEntity responseEntity; - ObjectMapper objectMapper = new ObjectMapper(); - - Response result = aaiService.getVersionByInvariantId(versions.versions); - - return new ResponseEntity(result.readEntity(String.class), HttpStatus.OK); - } - - - private ResponseEntity aaiResponseToResponseEntity(AaiResponse aaiResponseData) - throws IOException { - ResponseEntity responseEntity; - ObjectMapper objectMapper = new ObjectMapper(); - if (aaiResponseData.getHttpCode() == 200) { - responseEntity = new ResponseEntity(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK); - } else { - responseEntity = new ResponseEntity(aaiResponseData.getErrorMessage(), HttpStatus.valueOf(aaiResponseData.getHttpCode())); - } - return responseEntity; - } - - /** - * Lookup single service instance in a&ai. Get the service-subscription and customer, too, i guess? - * - * @param serviceInstanceId the service instance Id - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) { - Response resp = null; - - if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) { - resp = doAaiGet( - "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:" - + serviceInstanceId, false); - } else { - resp = doAaiGet( - "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:" - + serviceInstanceId, false); - } - return convertResponseToResponseEntity(resp); - } - - /** - * Get services from a&ai. - * - * @param globalCustomerId the global customer id - * @param serviceSubscriptionId the service subscription id - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity doGetServices(@PathVariable("global-customer-id") String globalCustomerId, - @PathVariable("service-subscription-id") String serviceSubscriptionId) { - Response resp = doAaiGet("business/customers/customer/" + globalCustomerId - + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false); - return convertResponseToResponseEntity(resp); - } - - /** - * Obtain the subscriber list from a&ai. - * - * @param fullSet the full set - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity doGetSubscriberList(HttpServletRequest request, @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException { - return getFullSubscriberList(request); - } - - /** - * Obtain the Target Prov Status from the System.Properties file. - * - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getTargetProvStatus() { - String p = SystemProperties.getProperty("aai.vnf.provstatus"); - return new ResponseEntity(p, HttpStatus.OK); - } - - - /** - * Obtain the Target Prov Status from the System.Properties file. - * - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/get_operational_environments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public AaiResponse getOperationalEnvironments(@RequestParam(value="operationalEnvironmentType", required = false) String operationalEnvironmentType, - @RequestParam(value="operationalEnvironmentStatus", required = false) String operationalEnvironmentStatus) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({}, {})", getMethodName(), operationalEnvironmentType, operationalEnvironmentStatus); - AaiResponse response = aaiService.getOperationalEnvironments(operationalEnvironmentType,operationalEnvironmentStatus); - if (response.getHttpCode() != 200) { - String errorMessage = getAaiErrorMessage(response.getErrorMessage()); - if(errorMessage != null) { - response = new AaiResponse(response.getT(), errorMessage, response.getHttpCode()); - } - } - - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); - return response; - } - - /** - * Obtain the full subscriber list from a&ai. - *

- * g @return ResponseEntity The response entity - * - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getFullSubscriberList(HttpServletRequest request) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - ResponseEntity responseEntity; - RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request)); - SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator); - if (subscriberList.getHttpCode() == 200) { - responseEntity = new ResponseEntity(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK); - } else { - responseEntity = new ResponseEntity(subscriberList.getErrorMessage(), HttpStatus.valueOf(subscriberList.getHttpCode())); - } - - - return responseEntity; - } - - - @RequestMapping(value = "/get_vnf_data_by_globalid_and_service_type/{globalCustomerId}/{serviceType}", - method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getVnfDataByGlobalIdAndServiceType(HttpServletRequest request, - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType) { - - Response resp = aaiService.getVNFData(globalCustomerId, serviceType); - return convertResponseToResponseEntity(resp); - } - - - /** - * Refresh the subscriber list from a&ai. - * - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity doRefreshSubscriberList() { - Response resp = getSubscribers(false); - return convertResponseToResponseEntity(resp); - } - - /** - * Refresh the full subscriber list from a&ai. - * - * @return ResponseEntity The response entity - * @throws IOException Signals that an I/O exception has occurred. - */ - @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity doRefreshFullSubscriberList() { - Response resp = getSubscribers(false); - return convertResponseToResponseEntity(resp); - } - - /** - * Get subscriber details from a&ai. - * - * @param subscriberId the subscriber id - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET) - public ResponseEntity GetSubscriberDetails(HttpServletRequest request, @PathVariable("subscriberId") String subscriberId) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - ResponseEntity responseEntity; - List roles = roleProvider.getUserRoles(request); - RoleValidator roleValidator = new RoleValidator(roles); - AaiResponse subscriberData = aaiService.getSubscriberData(subscriberId, roleValidator); - String httpMessage = subscriberData.getT() != null ? - objectMapper.writeValueAsString(subscriberData.getT()) : - subscriberData.getErrorMessage(); - - responseEntity = new ResponseEntity(httpMessage, HttpStatus.valueOf(subscriberData.getHttpCode())); - return responseEntity; - } - - /** - * Get service instances that match the query from a&ai. - * - * @param subscriberId the subscriber id - * @param instanceIdentifier the service instance name or id. - * @param projects the projects that are related to the instance - * @param owningEntities the owningEntities that are related to the instance - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "/search_service_instances", method = RequestMethod.GET) - public ResponseEntity SearchServiceInstances(HttpServletRequest request, - @RequestParam(value="subscriberId", required = false) String subscriberId, - @RequestParam(value="serviceInstanceIdentifier", required = false) String instanceIdentifier, - @RequestParam(value="project", required = false) List projects, - @RequestParam(value="owningEntity", required = false) List owningEntities) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - ResponseEntity responseEntity; - - List roles = roleProvider.getUserRoles(request); - RoleValidator roleValidator = new RoleValidator(roles); - - AaiResponse searchResult = aaiService.getServiceInstanceSearchResults(subscriberId, instanceIdentifier, roleValidator, owningEntities, projects); - - String httpMessage = searchResult.getT() != null ? - objectMapper.writeValueAsString(searchResult.getT()) : - searchResult.getErrorMessage(); - - - if(searchResult.getT().serviceInstances.size() == 0){ - responseEntity = new ResponseEntity(httpMessage, HttpStatus.NOT_FOUND); - - } else { - responseEntity = new ResponseEntity(httpMessage, HttpStatus.valueOf(searchResult.getHttpCode())); - - } - return responseEntity; - } - - - - /** - * Issue a named query to a&ai. - * - * @param namedQueryId the named query id - * @param globalCustomerId the global customer id - * @param serviceType the service type - * @param serviceInstance the service instance - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET) - public ResponseEntity viewEditGetComponentList( - @PathVariable("namedQueryId") String namedQueryId, - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType, - @PathVariable("serviceInstance") String serviceInstance) { - - String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance); - - Response resp = doAaiPost("search/named-query", componentListPayload, false); - return convertResponseToResponseEntity(resp); - } - - @RequestMapping(value = "/aai_get_vnf_data/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET) - public AaiResponse getVnfData( - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType, - @PathVariable("serviceInstanceId") String serviceInstanceId) { - - return aaiService.getVNFData(globalCustomerId, serviceType, serviceInstanceId); - - } - - - /** - * Issue a named query to a&ai. - * - * @param namedQueryId the named query id - * @param globalCustomerId the global customer id - * @param serviceType the service type - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET) - public ResponseEntity viewEditGetComponentList( - @PathVariable("namedQueryId") String namedQueryId, - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType) { - - String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType); - - Response resp = doAaiPost("search/named-query", componentListPayload, false); - return convertResponseToResponseEntity(resp); - } - - @RequestMapping(value = "/aai_get_vnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}", method = RequestMethod.GET) - public ResponseEntity getNodeTemplateInstances( - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType, - @PathVariable("modelVersionId") String modelVersionId, - @PathVariable("modelInvariantId") String modelInvariantId, - @PathVariable("cloudRegion") String cloudRegion) { - - AaiResponse resp = aaiService.getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion); - return new ResponseEntity(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); - } - - @RequestMapping(value = "/aai_get_network_collection_details/{serviceInstanceId}", method = RequestMethod.GET) - public ResponseEntity getNetworkCollectionDetails(@PathVariable("serviceInstanceId") String serviceInstanceId) throws IOException { - com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); - AaiResponse resp = aaiService.getNetworkCollectionDetails(serviceInstanceId); - - String httpMessage = resp.getT() != null ? - objectMapper.writeValueAsString(resp.getT()) : - resp.getErrorMessage(); - return new ResponseEntity(httpMessage, HttpStatus.valueOf(resp.getHttpCode())); - } - - @RequestMapping(value = "/aai_get_instance_groups_by_cloudregion/{cloudOwner}/{cloudRegionId}/{networkFunction}", method = RequestMethod.GET) - public ResponseEntity getInstanceGroupsByCloudRegion(@PathVariable("cloudOwner") String cloudOwner, - @PathVariable("cloudRegionId") String cloudRegionId, - @PathVariable("networkFunction") String networkFunction) throws IOException { - com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper(); - AaiResponse resp = aaiService.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction); - - String httpMessage = resp.getT() != null ? - objectMapper.writeValueAsString(resp.getT()) : - resp.getErrorMessage(); - return new ResponseEntity(httpMessage, HttpStatus.valueOf(resp.getHttpCode())); - } - - @RequestMapping(value = "/aai_get_by_uri/**", method = RequestMethod.GET) - public ResponseEntity getByUri(HttpServletRequest request) { - - String restOfTheUrl = (String) request.getAttribute( - HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); - String formattedUri = restOfTheUrl.replaceFirst("/aai_get_by_uri/", "").replaceFirst("^aai/v[\\d]+/", ""); - - Response resp = doAaiGet(formattedUri, false); - - return convertResponseToResponseEntity(resp); - } - - - - @RequestMapping(value = "/aai_get_configuration/{configuration_id}", method = RequestMethod.GET) - public ResponseEntity getSpecificConfiguration(@PathVariable("configuration_id") String configurationId) { - - Response resp = doAaiGet("network/configurations/configuration/"+configurationId, false); - - return convertResponseToResponseEntity(resp); - } - - @RequestMapping(value = "/aai_get_service_instance_pnfs/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET) - public List getServiceInstanceAssociatedPnfs( - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType, - @PathVariable("serviceInstanceId") String serviceInstanceId) { - - return aaiService.getServiceInstanceAssociatedPnfs(globalCustomerId, serviceType, serviceInstanceId); - } - - /** - * PNF section - */ - @RequestMapping(value = "/aai_get_pnfs/pnf/{pnf_id}", method = RequestMethod.GET) - public ResponseEntity getSpecificPnf(@PathVariable("pnf_id") String pnfId) { - //logger.trace(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), pnfId); - AaiResponse resp; - ResponseEntity re; - try { - resp = aaiService.getSpecificPnf(pnfId); - re = new ResponseEntity(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); - } catch (Exception e){ - return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - //logger.trace(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), resp.getHttpCode()); - return re; - } - - - /** - * Obtain tenants for a given service type. - * - * @param globalCustomerId the global customer id - * @param serviceType the service type - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET) - public ResponseEntity viewEditGetTenantsFromServiceType(HttpServletRequest request, - @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) { - - ResponseEntity responseEntity; - try { - ObjectMapper objectMapper = new ObjectMapper(); - List roles = roleProvider.getUserRoles(request); - RoleValidator roleValidator = new RoleValidator(roles); - AaiResponse response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator); - if (response.getHttpCode() == 200) { - responseEntity = new ResponseEntity(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK); - } else { - responseEntity = new ResponseEntity(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode())); - } - } catch (Exception e) { - responseEntity = new ResponseEntity("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR); - } - return responseEntity; - } - - @RequestMapping(value = "/aai_get_pnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}/{equipVendor}/{equipModel}", method = RequestMethod.GET) - public ResponseEntity getPnfInstances( - @PathVariable("globalCustomerId") String globalCustomerId, - @PathVariable("serviceType") String serviceType, - @PathVariable("modelVersionId") String modelVersionId, - @PathVariable("modelInvariantId") String modelInvariantId, - @PathVariable("cloudRegion") String cloudRegion, - @PathVariable("equipVendor") String equipVendor, - @PathVariable("equipModel") String equipModel) { - - AaiResponse resp = aaiService.getPNFData(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion, equipVendor, equipModel); - return new ResponseEntity(resp.getT(), HttpStatus.valueOf(resp.getHttpCode())); - } - - @RequestMapping(value = "/aai_getPortMirroringConfigsData", method = RequestMethod.GET) - public Map getPortMirroringConfigsData( - @RequestParam ("configurationIds") List configurationIds) { - - return configurationIds.stream() - .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringConfigData(id))) - .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); - } - - @RequestMapping(value = "/aai_getPortMirroringSourcePorts", method = RequestMethod.GET) - public Map getPortMirroringSourcePorts( - @RequestParam ("configurationIds") List configurationIds) { - - return configurationIds.stream() - .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringSourcePorts(id))) - .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); - } - - private ResponseEntity convertResponseToResponseEntity(Response resp) { - ResponseEntity respEnt; - ObjectMapper objectMapper = new ObjectMapper(); - if (resp == null) { - respEnt = new ResponseEntity("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR); - } else { - respEnt = new ResponseEntity(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus())); - } - return respEnt; - } - - /** - * Gets the subscribers. - * - * @param isFullSet the is full set - * @return the subscribers - */ - private Response getSubscribers(boolean isFullSet) { - - String depth = "0"; - - Response resp = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false); - if (resp != null) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString()); - } - return resp; - } - - /** - * Gets the subscriber details. - * - * @param subscriberId the subscriber id - * @return the subscriber details - */ - private Response getSubscriberDetails(String subscriberId) { - Response resp = doAaiGet("business/customers/customer/" + subscriberId + "?depth=2", false); - //String resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId, false); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscriberDetails() resp=" + resp.getStatusInfo().toString()); - return resp; - } - - /** - * Send a GET request to a&ai. - * - * @param uri the uri - * @param xml the xml - * @return String The response - */ - protected Response doAaiGet(String uri, boolean xml) { - String methodName = "getSubscriberList"; - String transId = UUID.randomUUID().toString(); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - Response resp = null; - try { - - - resp = aaiRestInterface.RestGet(fromAppId, transId, uri, xml).getResponse(); - - } catch (WebApplicationException e) { - final String message = e.getResponse().readEntity(String.class); - LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message); - } catch (Exception e) { - LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - } - - return resp; - } - - /** - * Send a POST request to a&ai. - * - * @param uri the uri - * @param payload the payload - * @param xml the xml - * @return String The response - */ - protected Response doAaiPost(String uri, String payload, boolean xml) { - String methodName = "getSubscriberList"; - String transId = UUID.randomUUID().toString(); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - Response resp = null; - try { - - resp = aaiRestInterface.RestPost(fromAppId, uri, payload, xml); - - } catch (Exception e) { - LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - } - - return resp; - } - - /** - * Gets the component list put payload. - * - * @param namedQueryId the named query id - * @param globalCustomerId the global customer id - * @param serviceType the service type - * @param serviceInstance the service instance - * @return the component list put payload - */ - private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType, String serviceInstance) { - return - " {" + - " \"instance-filters\": {" + - " \"instance-filter\": [" + - " {" + - " \"customer\": {" + - " \"global-customer-id\": \"" + globalCustomerId + "\"" + - " }," + - " \"service-instance\": {" + - " \"service-instance-id\": \"" + serviceInstance + "\"" + - " }," + - " \"service-subscription\": {" + - " \"service-type\": \"" + serviceType + "\"" + - " }" + - " }" + - " ]" + - " }," + - " \"query-parameters\": {" + - " \"named-query\": {" + - " \"named-query-uuid\": \"" + namedQueryId + "\"" + - " }" + - " }" + - "}"; - - } - - private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) { - // TODO Auto-generated method stub - return " {" + - " \"instance-filters\": {" + - " \"instance-filter\": [" + - " {" + - " \"customer\": {" + - " \"global-customer-id\": \"" + globalCustomerId + "\"" + - " }," + - " \"service-subscription\": {" + - " \"service-type\": \"" + serviceType + "\"" + - " }" + - " }" + - " ]" + - " }," + - " \"query-parameters\": {" + - " \"named-query\": {" + - " \"named-query-uuid\": \"" + namedQueryId + "\"" + - " }" + - " }" + - "}"; - - } - - private String getAaiErrorMessage(String message) { - try { - org.json.JSONObject json = new org.json.JSONObject(message); - json = json.getJSONObject("requestError").getJSONObject("serviceException"); - - return json.getString("messageId") + ": " + json.getString("text"); - - } catch (Exception e) { - return null; - } - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java b/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java deleted file mode 100644 index c4d82932..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncControllerForTests.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.onap.vid.controllers; - -import org.onap.vid.exceptions.GenericUncheckedException; -import org.onap.vid.model.ExceptionResponse; -import org.onap.vid.model.JobBulk; -import org.onap.vid.model.JobModel; -import org.onap.vid.services.BulkInstantiationService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; - -import javax.ws.rs.WebApplicationException; -import java.util.Map; -import java.util.UUID; - -import static org.springframework.http.HttpStatus.BAD_REQUEST; - -@RestController -@RequestMapping("asyncForTests") -public class AsyncControllerForTests extends VidRestrictedBaseController { - - private BulkInstantiationService bulkInstantiationService; - - @Autowired - public AsyncControllerForTests(BulkInstantiationService bulkInstantiationService) { - this.bulkInstantiationService = bulkInstantiationService; - } - - @RequestMapping(method = RequestMethod.POST) - public JobBulk createAsyncJob(@RequestBody Map body) { - return bulkInstantiationService.saveBulk(body); - } - - @RequestMapping(value = "/job/{uuid}", method = RequestMethod.GET) - public JobModel getJob(@PathVariable UUID uuid) { - return bulkInstantiationService.getJob(uuid); - } - - @RequestMapping(value = "/error", method = RequestMethod.GET) - public void throwError() { - throw new GenericUncheckedException("dummy error"); - } - - @ExceptionHandler({IllegalArgumentException.class}) - @ResponseStatus(value=BAD_REQUEST) - private ExceptionResponse exceptionHandlerBadRequest(Exception e) { - return ControllersUtils.handleException(e, LOGGER); - } - - @ExceptionHandler(WebApplicationException.class) - private ResponseEntity webApplicationExceptionHandler(WebApplicationException e) { - return ControllersUtils.handleWebApplicationException(e, LOGGER); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java deleted file mode 100644 index c5621a30..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/AsyncInstantiationController.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.onap.vid.controllers; - - -import org.onap.vid.exceptions.OperationNotAllowedException; -import org.onap.vid.model.ExceptionResponse; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.exception.ExceptionUtils; - -import org.onap.vid.model.JobAuditStatus; -import org.onap.vid.model.ServiceInfo; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.mso.MsoResponseWrapper2; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.UUID; -import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED; - - -@RestController -@RequestMapping(AsyncInstantiationController.ASYNC_INSTANTIATION) -public class AsyncInstantiationController extends VidRestrictedBaseController { - - public static final String ASYNC_INSTANTIATION = "asyncInstantiation"; - - protected final AsyncInstantiationBusinessLogic asyncInstantiationBL; - - @Autowired - public AsyncInstantiationController(AsyncInstantiationBusinessLogic asyncInstantiationBL) { - this.asyncInstantiationBL = asyncInstantiationBL; - } - - @ExceptionHandler(OperationNotAllowedException.class) - @ResponseStatus(value=METHOD_NOT_ALLOWED) - public ExceptionResponse illegalStateExceptionHandler(Exception e) { - return ControllersUtils.handleException(e, LOGGER); - } - - /** - * Gets the new services status. - * @param request the request - * @return the services list - */ - @RequestMapping(method = RequestMethod.GET) - public List getServicesInfo(HttpServletRequest request) { - return asyncInstantiationBL.getAllServicesInfo(); - } - - @RequestMapping(value = "bulk", method = RequestMethod.POST) - public MsoResponseWrapper2> createBulkOfServices(@RequestBody ServiceInstantiation request, HttpServletRequest httpServletRequest) { - //Push to DB according the model - - String userId = ControllersUtils.extractUserId(httpServletRequest); - List uuids = asyncInstantiationBL.pushBulkJob(request, userId); - - return new MsoResponseWrapper2(200, uuids); - } - - @RequestMapping(value = "job/{jobId}", method = RequestMethod.DELETE) - public void deleteServiceInfo(@PathVariable("jobId") UUID jobId) { - asyncInstantiationBL.deleteJob(jobId); - } - - @RequestMapping(value = "hide/{jobId}", method = RequestMethod.POST) - public void hideServiceInfo(@PathVariable("jobId") UUID jobId) { - asyncInstantiationBL.hideServiceInfo(jobId); - } - - @RequestMapping(value = "auditStatus/{jobId}", method = RequestMethod.GET) - public List getJobAuditStatus(HttpServletRequest request, @PathVariable(value="jobId") UUID jobId, @RequestParam(value="source") JobAuditStatus.SourceStatus source){ - return asyncInstantiationBL.getAuditStatuses(jobId, source); - } - - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java deleted file mode 100644 index 88875b51..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/ChangeManagementController.java +++ /dev/null @@ -1,227 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright © 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.vid.controllers; - -import static org.onap.vid.utils.Logging.getMethodName; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; -import static org.springframework.http.HttpStatus.OK; - -import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.Collection; -import java.util.Collections; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.WebApplicationException; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.json.simple.JSONArray; -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.changeManagement.ChangeManagementRequest; -import org.onap.vid.changeManagement.GetVnfWorkflowRelationRequest; -import org.onap.vid.changeManagement.GetWorkflowsResponse; -import org.onap.vid.changeManagement.VnfWorkflowRelationAllResponse; -import org.onap.vid.changeManagement.VnfWorkflowRelationRequest; -import org.onap.vid.changeManagement.VnfWorkflowRelationResponse; -import org.onap.vid.exceptions.NotFoundException; -import org.onap.vid.model.ExceptionResponse; -import org.onap.vid.model.MsoExceptionResponse; -import org.onap.vid.mso.MsoResponseWrapper2; -import org.onap.vid.mso.MsoResponseWrapperInterface; -import org.onap.vid.mso.rest.Request; -import org.onap.vid.services.ChangeManagementService; -import org.onap.vid.services.WorkflowService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -/** - * Controller to handle ChangeManagement feature requests. - */ -@RestController -@RequestMapping(ChangeManagementController.CHANGE_MANAGEMENT) -public class ChangeManagementController extends UnRestrictedBaseController { - public static final String VNF_WORKFLOW_RELATION = "vnf_workflow_relation"; - public static final String CHANGE_MANAGEMENT = "change-management"; - public static final String GET_VNF_WORKFLOW_RELATION = "get_vnf_workflow_relation"; - public static final String SCHEDULER_BY_SCHEDULE_ID = "/scheduler/schedules/{scheduleId}"; - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ChangeManagementController.class); - private String fromAppId; - private final WorkflowService workflowService; - private final ChangeManagementService changeManagementService; - private final ObjectMapper objectMapper; - - - @Autowired - public ChangeManagementController(WorkflowService workflowService, ChangeManagementService changeManagementService, ObjectMapper objectMapper) { - this.fromAppId = "VidChangeManagementController"; - this.workflowService = workflowService; - this.changeManagementService = changeManagementService; - this.objectMapper = objectMapper; - } - - @RequestMapping(value = {"/workflow"}, method = RequestMethod.GET) - public ResponseEntity> getWorkflow(@RequestParam("vnfs") Collection vnfs) { - Collection result = this.workflowService.getWorkflowsForVNFs(vnfs); - return new ResponseEntity<>(result, OK); - } - - @RequestMapping(value = {"/mso"}, method = RequestMethod.GET) - public ResponseEntity> getMSOChangeManagements() { - - Collection result = this.changeManagementService.getMSOChangeManagements(); - return new ResponseEntity<>(result, OK); - } - - @RequestMapping(value = "/workflow/{vnfName}", method = RequestMethod.POST) - public ResponseEntity changeManagement(HttpServletRequest request, @PathVariable("vnfName") String vnfName, - @RequestBody ChangeManagementRequest changeManagmentRequest) - throws Exception { - return this.changeManagementService.doChangeManagement(changeManagmentRequest, vnfName); - } - - @RequestMapping(value = "/uploadConfigUpdateFile", method = RequestMethod.POST) - public @ResponseBody ResponseEntity uploadConfigUpdateFile(@RequestPart("file") MultipartFile file) - throws Exception { - try { - String jsonString = this.changeManagementService.uploadConfigUpdateFile(file); - return new ResponseEntity<>(jsonString, HttpStatus.OK); - } - catch(WebApplicationException e){ - return new ResponseEntity<>(handleException(e), HttpStatus.valueOf(e.getResponse().getStatus())); - } - catch (Exception e) { - return new ResponseEntity<>(handleException(e), INTERNAL_SERVER_ERROR); - } - } - - - @RequestMapping(value = {"/scheduler"}, method = RequestMethod.GET) - public ResponseEntity getSchedulerChangeManagements() { - JSONArray result = this.changeManagementService.getSchedulerChangeManagements(); - return new ResponseEntity<>(result, OK); - } - - @RequestMapping(value = {SCHEDULER_BY_SCHEDULE_ID}, method = RequestMethod.DELETE) - public ResponseEntity deleteSchedule(@PathVariable("scheduleId") String scheduleId) { - Pair result = this.changeManagementService.deleteSchedule(scheduleId); - return ResponseEntity.status(result.getRight()).build(); - } - - - @RequestMapping(value = {GET_VNF_WORKFLOW_RELATION}, method = RequestMethod.POST) - public ResponseEntity getWorkflows(@RequestBody GetVnfWorkflowRelationRequest getVnfWorkflowRelationRequest) { - try { - GetWorkflowsResponse response = new GetWorkflowsResponse(changeManagementService.getWorkflowsForVnf(getVnfWorkflowRelationRequest)); - return ResponseEntity.status(OK).body(response); - } - catch (NotFoundException exception) { - LOGGER.error(exception.getMessage(), exception); - return new ResponseEntity<>(new VnfWorkflowRelationResponse(Collections.singletonList(exception.getMessage())),HttpStatus.NOT_FOUND); - } - catch (Exception exception) { - return handleException(exception, "Failed to get workflows for vnf"); - } - } - - @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.POST) - public ResponseEntity createWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) { - VnfWorkflowRelationResponse vnfWorkflowRelationResponse; - try { - vnfWorkflowRelationResponse = changeManagementService.addVnfWorkflowRelation(vnfWorkflowRelationRequest); - } - catch (Exception exception) { - return handleException(exception, "Failed to add vnf to workflow relation"); - } - - return new ResponseEntity<>(vnfWorkflowRelationResponse, OK); - } - - @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.GET) - public ResponseEntity getAllWorkflowRelation() { - - try { - VnfWorkflowRelationAllResponse vnfWorkflowRelationAllResponse = changeManagementService.getAllVnfWorkflowRelations(); - return new ResponseEntity<>(vnfWorkflowRelationAllResponse, OK); - } - catch (Exception exception) { - return handleException(exception, "Failed to get all vnf to workflow relations"); - } - } - - @RequestMapping(value = {VNF_WORKFLOW_RELATION}, method = RequestMethod.DELETE) - public ResponseEntity deleteWorkflowRelation(@RequestBody VnfWorkflowRelationRequest vnfWorkflowRelationRequest) { - VnfWorkflowRelationResponse vnfWorkflowRelationResponse; - try { - vnfWorkflowRelationResponse = changeManagementService.deleteVnfWorkflowRelation(vnfWorkflowRelationRequest); - } - catch (Exception exception) { - return handleException(exception, "Failed to delete vnf from workflow relation"); - } - - return new ResponseEntity<>(vnfWorkflowRelationResponse, OK); - } - - private ResponseEntity handleException(Exception exception, String msg) { - LOGGER.error(msg, exception); - return new ResponseEntity<>(new VnfWorkflowRelationResponse(Collections.singletonList(msg)), HttpStatus.INTERNAL_SERVER_ERROR); - } - - - private ExceptionResponse handleException(Exception e) { - return ControllersUtils.handleException(e, LOGGER); - } - - @ExceptionHandler(Exception.class) - @ResponseStatus(value=OK) //return 200 for Backwards compatibility with the previous responses to scheduler - private MsoResponseWrapperInterface exceptionHandler(Exception e) { - return exceptionHandler(e, INTERNAL_SERVER_ERROR); - } - - @ExceptionHandler({ - javax.ws.rs.BadRequestException.class, - }) - @ResponseStatus(value = OK) //return 200 for Backwards compatibility with the previous responses to scheduler - public MsoResponseWrapperInterface clientDerivedExceptionAsBadRequest(Exception e) { - // same handler, different HTTP Code - return exceptionHandler(e, BAD_REQUEST); - } - - private MsoResponseWrapperInterface exceptionHandler(Exception e, HttpStatus httpStatus) { - LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodName(), ExceptionUtils.getMessage(e), e); - MsoResponseWrapper2 responseWrapper2 = new MsoResponseWrapper2<>(httpStatus.value(), new MsoExceptionResponse(e)); - return responseWrapper2; - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java deleted file mode 100644 index 1abe300e..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/ControllersUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.onap.vid.controllers; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.model.ExceptionResponse; -import org.slf4j.MDC; -import org.springframework.http.ResponseEntity; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.WebApplicationException; - -import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID; -import static org.onap.vid.utils.Logging.getMethodName; - -public class ControllersUtils { - - - public static String extractUserId(HttpServletRequest request) { - String userId = ""; - HttpSession session = request.getSession(); - if (session != null) { - User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)); - if (user != null) { - //userId = user.getHrid(); - userId = user.getLoginId(); - if (userId == null) - userId = user.getOrgUserId(); - } - } - return userId; - } - - public static ExceptionResponse handleException(Exception e, EELFLoggerDelegate logger) { - logger.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodName(), ExceptionUtils.getMessage(e), e); - - ExceptionResponse exceptionResponse = new ExceptionResponse(e); - return exceptionResponse; - } - - public static ResponseEntity handleWebApplicationException(WebApplicationException e, EELFLoggerDelegate logger) { - return ResponseEntity.status(e.getResponse().getStatus()).body(ControllersUtils.handleException(e, logger)); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java deleted file mode 100644 index 36dfdaa0..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/FeatureTogglingController.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.onap.vid.controllers; - -import org.onap.vid.properties.Features; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -@RestController -@RequestMapping("flags") -public class FeatureTogglingController extends RestrictedBaseController { - - @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public @ResponseBody Map getFeatureToggles() - { - HashMap flags = new HashMap (); - for(Features flag : Features.values()){ - flags.put(flag.name(), flag.isActive()); - } - return flags; - - - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java deleted file mode 100644 index 86e832ba..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.controllers; - -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.dao.FnAppDoaImpl; -import org.onap.vid.model.GitRepositoryState; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; - -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; -import static org.springframework.http.HttpStatus.OK; - -/** - * Controller for user profile view. The view is restricted to authenticated - * users. The view name resolves to page user_profile.jsp which uses Angular. - */ - -@RestController -@RequestMapping("/") -public class HealthCheckController extends UnRestrictedBaseController { - - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(HealthCheckController.class); - private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - private static final String GIT_PROPERTIES_FILENAME = "git.properties"; - private FnAppDoaImpl fnAppDoaImpl; - - @Autowired - public HealthCheckController(FnAppDoaImpl fnAppDoaImpl) { - this.fnAppDoaImpl = fnAppDoaImpl; - } - - /** - * Obtain the HealthCheck Status from the System.Properties file. - * Used by IDNS for redundancy - * - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "/healthCheck", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public HealthStatus getHealthCheckStatusForIDNS() { - return createCorrespondingStatus(); - } - - /** - * Obtain the HealthCheck Status from the System.Properties file. - * - * @return ResponseEntity The response entity - */ - @RequestMapping(value = "rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public HealthStatus getHealthCheck( - @PathVariable("User-Agent") String UserAgent, - @PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "User-Agent ", UserAgent); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID ", ECOMPRequestID); - return createCorrespondingStatus(); - } - - @RequestMapping(value = "/commitInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public GitRepositoryState getCommitInfo() throws IOException { - Properties properties = new Properties(); - properties.load(getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES_FILENAME)); - return new GitRepositoryState(properties); - } - - private HealthStatus createCorrespondingStatus() { - logData(); - try { - int count = fnAppDoaImpl.getProfileCount(getUrl(), getUsername(), getPassword()); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::", count); - return okStatus(); - } catch (Exception ex) { - String errorMsg = ex.getMessage(); - LOGGER.error(EELFLoggerDelegate.errorLogger, errorMsg); - return errorStatus(errorMsg); - } - } - - private void logData() { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::", getUrl()); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::", getUsername()); - } - - private HealthStatus okStatus() { - return new HealthStatus(OK, dateFormat.format(new Date()), "health check succeeded"); - } - - private HealthStatus errorStatus(String msg) { - return new HealthStatus(INTERNAL_SERVER_ERROR, dateFormat.format( - new Date()), "health check failed: " + msg); - } - - private String getUrl() { - return SystemProperties.getProperty("db.connectionURL"); - } - - private String getUsername() { - return SystemProperties.getProperty("db.userName"); - } - - private String getPassword() { - return SystemProperties.getProperty("db.password"); - } -} - diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java deleted file mode 100644 index 6056c289..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.onap.vid.controllers; - -import org.springframework.http.HttpStatus; - -/** - * Model for JSON response with health-check results. - */ -public final class HealthStatus { - - private final int statusCode; - private final String detailedMsg; - private final String date; - - public HealthStatus(HttpStatus code, String date, String detailedMsg) { - this.statusCode = code.value(); - this.detailedMsg = detailedMsg; - this.date = date; - } - - public int getStatusCode() { - return statusCode; - } - - public String getDetailedMsg() { - return detailedMsg; - } - - public String getDate() { - return date; - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/LoggerController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/LoggerController.java deleted file mode 100644 index 14d02721..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/LoggerController.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.onap.vid.controllers; - -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.core.Appender; -import ch.qos.logback.core.FileAppender; -import ch.qos.logback.core.spi.AppenderAttachable; -import org.apache.commons.io.input.ReversedLinesFileReader; -import org.apache.commons.lang3.StringUtils; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.model.ExceptionResponse; -import org.onap.vid.roles.Role; -import org.onap.vid.roles.RoleProvider; -import org.onap.vid.utils.Streams; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAuthorizedException; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Objects; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static com.att.eelf.configuration.Configuration.GENERAL_LOGGER_NAME; - - -@RestController -@RequestMapping("logger") -public class LoggerController extends RestrictedBaseController { - - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(LoggerController.class); - - @Autowired - RoleProvider roleProvider; - - @RequestMapping(value = "/{loggerName:audit|error|metrics}", method = RequestMethod.GET) - public String getLog(@PathVariable String loggerName, HttpServletRequest request, - @RequestParam(value="limit", defaultValue = "5000") Integer limit) throws IOException { - - List roles = roleProvider.getUserRoles(request); - boolean userPermitted = roleProvider.userPermissionIsReadLogs(roles); - if (!userPermitted) { - throw new NotAuthorizedException("User not authorized to get logs"); - } - - String logfilePath = getLogfilePath(loggerName); - - try (final ReversedLinesFileReader reader = new ReversedLinesFileReader(new File(logfilePath))) { - Supplier reverseLinesSupplier = () -> { - try { - return reader.readLine(); - } catch (NullPointerException e) { - // EOF Reached - return null; - } catch (IOException e) { - throw new InternalServerErrorException("error while reading " + logfilePath, e); - } - }; - - return Streams.takeWhile( - Stream.generate(reverseLinesSupplier), - line -> !StringUtils.contains(line, "Logging is started")) - .limit(limit) - .limit(5_000) - .filter(Objects::nonNull) - .collect(Collectors.joining("\n")); - } - } - - private String getLogfilePath(String loggerName) { - /* - Find the requested logger, and pull all of it's appenders. - Find the first of the appenders that is a FileAppender, and return it's - write-out filename. - */ - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - return context.getLoggerList().stream() - .filter(logger -> logger.getName().equals(GENERAL_LOGGER_NAME + "." + loggerName)) - .flatMap(this::pullSubAppenders) - .flatMap(appender -> { - // Appender might be "attachable", if so - roll-up its sub-appenders - return (appender instanceof AppenderAttachable) ? - pullSubAppenders((AppenderAttachable) appender) : Stream.of(appender); - }) - .filter(appender -> appender instanceof FileAppender) - .map(appender -> (FileAppender) appender) - .map(FileAppender::getFile) - .findFirst() - .orElseThrow(() -> new InternalServerErrorException("logfile for " + loggerName + " not found")); - } - - private Stream> pullSubAppenders(AppenderAttachable logger) { - return Streams.fromIterator(logger.iteratorForAppenders()); - } - - @ExceptionHandler({ NotAuthorizedException.class }) - @ResponseStatus(HttpStatus.UNAUTHORIZED) - public String notAuthorizedHandler(NotAuthorizedException e) { - return "UNAUTHORIZED"; - } - - @ExceptionHandler({ IOException.class, InternalServerErrorException.class }) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public ExceptionResponse ioExceptionHandler(Exception e) { - return org.onap.vid.controllers.ControllersUtils.handleException(e, LOGGER); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java deleted file mode 100644 index 1a3eb42f..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MaintenanceController.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.onap.vid.controllers; - -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright © 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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========================================================= - */ - -import static org.onap.vid.utils.Logging.getMethodCallerName; - -import javax.ws.rs.ForbiddenException; -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.category.AddCategoryOptionResponse; -import org.onap.vid.category.AddCategoryOptionsRequest; -import org.onap.vid.category.CategoryParameterOptionRep; -import org.onap.vid.category.CategoryParametersResponse; -import org.onap.vid.model.CategoryParameter.Family; -import org.onap.vid.model.CategoryParameterOption; -import org.onap.vid.services.CategoryParameterService; -import org.onap.vid.services.CategoryParameterServiceImpl; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -/** - * Controler for APIs that are used only by vid operators - */ - -@RestController -@RequestMapping("maintenance") -public class MaintenanceController extends UnRestrictedBaseController { - - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(MaintenanceController.class); - private CategoryParameterService categoryParameterService; - - @Autowired - public MaintenanceController(CategoryParameterService categoryParameterService) { - this.categoryParameterService = categoryParameterService; - } - - /** - * Add list of options to one category parameter - */ - @RequestMapping(value = "/category_parameter/{categoryName}", method = RequestMethod.POST) - public ResponseEntity addCategoryOptions(@PathVariable String categoryName, - @RequestBody AddCategoryOptionsRequest option) { - debugStartLog(); - try { - AddCategoryOptionResponse response = categoryParameterService - .createCategoryParameterOptions(categoryName, option); - HttpStatus httpStatus = response.getErrors().isEmpty() ? HttpStatus.OK : HttpStatus.MULTI_STATUS; - debugEndLog(response); - return createResponseWithBody(httpStatus, response); - } catch (CategoryParameterServiceImpl.UnfoundedCategoryException exception) { - return createResponseWithBody(HttpStatus.NOT_FOUND, new AddCategoryOptionResponse(exception.getMessage())); - } catch (RuntimeException exception) { - LOGGER.error("failed to add option to parameter category " + categoryName, exception); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - } - - @RequestMapping(value = "/category_parameter/{categoryName}", method = RequestMethod.PUT) - public ResponseEntity updateNameForOption(@PathVariable String categoryName, - @RequestBody CategoryParameterOptionRep option) { - debugStartLog(); - try { - AddCategoryOptionResponse response = categoryParameterService - .updateCategoryParameterOption(categoryName, option); - HttpStatus httpStatus = response.getErrors().isEmpty() ? HttpStatus.OK : HttpStatus.MULTI_STATUS; - debugEndLog(response); - return createResponseWithBody(httpStatus, response); - } catch (ForbiddenException exception) { - return createResponseWithBody(HttpStatus.FORBIDDEN, new AddCategoryOptionResponse(exception.getMessage())); - } catch (CategoryParameterServiceImpl.UnfoundedCategoryException | CategoryParameterServiceImpl.UnfoundedCategoryOptionException exception) { - return createResponseWithBody(HttpStatus.NOT_FOUND, new AddCategoryOptionResponse(exception.getMessage())); - - } catch (CategoryParameterServiceImpl.AlreadyExistOptionNameException exception) { - return createResponseWithBody(HttpStatus.CONFLICT, new AddCategoryOptionResponse(exception.getMessage())); - - } catch (RuntimeException exception) { - LOGGER.error("failed to update option to parameter category " + categoryName, exception); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - } - - /** - * Gets the owning entity properties. - */ - @RequestMapping(value = "/category_parameter", method = RequestMethod.GET) - public ResponseEntity getCategoryParameter(@RequestParam(value = "familyName", required = true) Family familyName) { - debugStartLog(); - try { - CategoryParametersResponse response = categoryParameterService.getCategoryParameters(familyName); - debugEndLog(response); - return ResponseEntity.ok().body(response); - } catch (RuntimeException exception) { - LOGGER.error("failed to retrieve category parameter list from DB.", exception); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - } - - /** - * Delete option of the category. - */ - @RequestMapping(value = "/delete_category_parameter/{categoryName}", method = RequestMethod.DELETE) - public ResponseEntity deleteCategoryOption(@PathVariable String categoryName, - @RequestBody CategoryParameterOption option) { - debugStartLog(); - - try { - categoryParameterService.deleteCategoryOption(categoryName, option); - debugEndLog(HttpStatus.OK); - return ResponseEntity.status(HttpStatus.OK).build(); - } catch (CategoryParameterServiceImpl.UnfoundedCategoryException exception) { - return createResponseWithBody(HttpStatus.NOT_FOUND, new AddCategoryOptionResponse(exception.getMessage())); - } catch (RuntimeException exception) { - LOGGER.error("failed to add/update owning entity option", exception); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); - } - } - - private ResponseEntity createResponseWithBody(HttpStatus status, AddCategoryOptionResponse response) { - return ResponseEntity.status(status).body(response); - } - - private void debugStartLog() { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodCallerName()); - } - - private void debugEndLog(Object response) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), response); - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java deleted file mode 100644 index 020018ad..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.controllers; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.portalsdk.core.util.SystemProperties; - -import org.onap.vid.client.SyncRestClient; -import org.onap.vid.factories.MsoRequestFactory; -import org.onap.vid.mso.MsoBusinessLogic; -import org.onap.vid.mso.MsoBusinessLogicImpl; -import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.MsoProperties; -import org.onap.vid.mso.rest.MsoRestClientNew; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.togglz.core.manager.FeatureManager; - - -@Configuration -public class MsoConfig { - - /** - * Gets the object mapper. - * - * @return the object mapper - */ - @Bean - public ObjectMapper getObjectMapper() { - return new ObjectMapper(); - } - - @Bean - public MsoRequestFactory createRequestDetailsFactory(){ - return new MsoRequestFactory(); - } - - @Bean - public MsoInterface getMsoClient(){ - return new MsoRestClientNew(new SyncRestClient(MsoInterface.objectMapper()), SystemProperties.getProperty( - MsoProperties.MSO_SERVER_URL)); - } - - @Bean - public MsoBusinessLogic getMsoBusinessLogic(MsoInterface msoClient, FeatureManager featureManager){ - return new MsoBusinessLogicImpl(msoClient, featureManager); - } - - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java deleted file mode 100644 index 62c64b75..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoController.java +++ /dev/null @@ -1,693 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.controllers; - - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.vid.model.ExceptionResponse; -import org.onap.vid.mso.MsoBusinessLogic; -import org.onap.vid.mso.MsoResponseWrapper; -import org.onap.vid.mso.rest.Request; -import org.onap.vid.mso.rest.RequestDetails; -import org.onap.vid.mso.rest.RequestDetailsWrapper; -import org.onap.vid.mso.rest.Task; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; - -import static org.onap.vid.utils.Logging.getMethodName; - -//import java.util.UUID; -//import org.springframework.http.ResponseEntity; -//import org.springframework.http.RequestEntity; - -/** - * The Class MsoController. - */ -@RestController -@RequestMapping("mso") -public class MsoController extends RestrictedBaseController { - - /** - * The logger. - */ - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(MsoController.class); - - /** - * The Constant dateFormat. - */ - private final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** - * The Constant SVC_INSTANCE_ID. - */ - public final static String SVC_INSTANCE_ID = ""; - public final static String REQUEST_TYPE = ""; - - /** - * The Constant CONFIGURATION_ID - */ - public final static String CONFIGURATION_ID = ""; - - /** - * The Constant VNF_INSTANCE_ID. - */ - public final static String VNF_INSTANCE_ID = ""; - - private final MsoBusinessLogic msoBusinessLogic; - - @Autowired - public MsoController(MsoBusinessLogic msoBusinessLogic) { - this.msoBusinessLogic = msoBusinessLogic; - } - - /** - * Creates the svc instance. - * - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_svc_instance", method = RequestMethod.POST) - public ResponseEntity createSvcInstance(HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "createSvcInstance"; - - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - // always return OK, the MSO status code is embedded in the body - - MsoResponseWrapper w = msoBusinessLogic.createSvcInstance(mso_request); - - return (new ResponseEntity<>(w.getResponse(), HttpStatus.OK)); - - } - - /** - * Creates the e2e svc instance. - * - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_e2e_svc_instance", method = RequestMethod.POST) - public ResponseEntity createE2eSvcInstance(HttpServletRequest request, @RequestBody LinkedHashMap mso_request) { - String methodName = "createE2eSvcInstance"; - - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - // always return OK, the MSO status code is embedded in the body - - MsoResponseWrapper w = msoBusinessLogic.createE2eSvcInstance(mso_request.get("requestDetails")); - - return (new ResponseEntity<>(w.getResponse(), HttpStatus.OK)); - - } - - /** - * Creates the vnf. - * - * @param serviceInstanceId the service instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_vnf_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity createVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { - - MsoResponseWrapper w = msoBusinessLogic.createVnf(mso_request, serviceInstanceId); - - // always return OK, the MSO status code is embedded in the body - - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - - } - - /** - * Creates the nw instance. - * - * @param serviceInstanceId the service instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_nw_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity createNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "createNwInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start, serviceInstanceId = " + serviceInstanceId); - - MsoResponseWrapper w = msoBusinessLogic.createNwInstance(mso_request, serviceInstanceId); - - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - - } - - /** - * Creates the volume group instance. - * - * @param serviceInstanceId the service instance id - * @param vnfInstanceId the vnf instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) - public ResponseEntity createVolumeGroupInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "createVolumeGroupInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.createVolumeGroupInstance(mso_request, serviceInstanceId, vnfInstanceId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Creates the vf module instance. - * - * @param serviceInstanceId the service instance id - * @param vnfInstanceId the vnf instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) - public ResponseEntity createVfModuleInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("vnfInstanceId") String vnfInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "createVfModuleInstance"; - - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.createVfModuleInstance(mso_request, serviceInstanceId, vnfInstanceId); - - // always return OK, the MSO status code is embedded in the body - - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Creates a configuration instance. - * - * @param serviceInstanceId the service instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_create_configuration_instance/{serviceInstanceId}/configurations/", method = RequestMethod.POST) - public ResponseEntity createConfigurationInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - HttpServletRequest request, @RequestBody RequestDetailsWrapper mso_request) { - String methodName = "createConfigurationInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.createConfigurationInstance(mso_request, serviceInstanceId); - - // always return OK, the MSO status code is embedded in the body - - return (new ResponseEntity<>(w.getResponse(), HttpStatus.OK)); - } - - /** - * Delete E2e svc instance. - * - * @param serviceInstanceId the service instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_delete_e2e_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity deleteE2eSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - HttpServletRequest request, @RequestBody LinkedHashMap mso_request) { - - String methodName = "deleteE2eSvcInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), mso_request); - - MsoResponseWrapper w = msoBusinessLogic.deleteE2eSvcInstance(mso_request.get("requestDetails"), serviceInstanceId); - - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); - // always return OK, the MSO status code is embedded in the body - - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - - } - - /** - * Delete svc instance. - * - * @param serviceInstanceId the service instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - - @RequestMapping(value = "/mso_delete_svc_instance/{serviceInstanceId}", method = RequestMethod.POST) - public String deleteSvcInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request, - @RequestParam(value = "serviceStatus") String serviceStatus) { - - String methodName = "deleteSvcInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), mso_request); - MsoResponseWrapper w = msoBusinessLogic.deleteSvcInstance(mso_request, serviceInstanceId, serviceStatus); - // always return OK, the MSO status code is embedded in the body - - return w.getResponse(); - } - - /** - * Delete vnf. - * - * @param serviceInstanceId the service instance id - * @param vnfInstanceId the vnf instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_delete_vnf_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}", method = RequestMethod.POST) - - public ResponseEntity deleteVnf(@PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "deleteVnf"; - - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.deleteVnf(mso_request, serviceInstanceId, vnfInstanceId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - - } - - /** - * Delete configuration instance - * @param serviceInstanceId the service instance id - * @param configurationId the configuration id - * @param mso_request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "mso_delete_configuration/{serviceInstanceId}/configurations/{configurationId}", - method = RequestMethod.POST) - public ResponseEntity deleteConfiguration( - @PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable ("configurationId") String configurationId, - @RequestBody RequestDetailsWrapper mso_request) { - - String methodName = "deleteConfiguration"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, - dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.deleteConfiguration(mso_request, serviceInstanceId, configurationId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Activate configuration instance - * @param serviceInstanceId the service instace id - * @param configurationId the configuration id - * @param mso_request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "mso_activate_configuration/{serviceInstanceId}/configurations/{configurationId}", - method = RequestMethod.POST) - public ResponseEntity activateConfiguration( - @PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) { - - MsoResponseWrapper w = msoBusinessLogic.setConfigurationActiveStatus(mso_request, serviceInstanceId, configurationId, true); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Deactivate configuration instance - * @param serviceInstanceId the service instace id - * @param configurationId the configuration id - * @param mso_request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "mso_deactivate_configuration/{serviceInstanceId}/configurations/{configurationId}", - method = RequestMethod.POST) - public ResponseEntity deactivateConfiguration( - @PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) { - - MsoResponseWrapper w = msoBusinessLogic.setConfigurationActiveStatus(mso_request, serviceInstanceId, configurationId, false); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Disable port on configuration instance - * @param serviceInstanceId the service instance id - * @param configurationId the configuration instance id - * @param mso_request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "mso_disable_port_configuration/{serviceInstanceId}/configurations/{configurationId}", - method = RequestMethod.POST) - public ResponseEntity disablePortOnConfiguration( - @PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) { - - MsoResponseWrapper w = msoBusinessLogic.setPortOnConfigurationStatus(mso_request, serviceInstanceId, configurationId, false); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Enable port on configuration instance - * @param serviceInstanceId the service instance id - * @param configurationId the configuration instance id - * @param mso_request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "mso_enable_port_configuration/{serviceInstanceId}/configurations/{configurationId}", - method = RequestMethod.POST) - public ResponseEntity enablePortOnConfiguration( - @PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("configurationId") String configurationId, - @RequestBody RequestDetails mso_request) { - - MsoResponseWrapper w = msoBusinessLogic.setPortOnConfigurationStatus(mso_request, serviceInstanceId, configurationId, true); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Delete vf module. - * - * @param serviceInstanceId the service instance id - * @param vnfInstanceId the vnf instance id - * @param vfModuleId the vf module id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - //mso_delete_vf_module/bc305d54-75b4-431b-adb2-eb6b9e546014/vnfs/fe9000-0009-9999/vfmodules/abeeee-abeeee-abeeee - @RequestMapping(value = "/mso_delete_vfmodule_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfModuleId}", method = RequestMethod.POST) - public ResponseEntity deleteVfModule( - @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, - @PathVariable("vfModuleId") String vfModuleId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { - - String methodName = "deleteVfModule"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.deleteVfModule(mso_request, serviceInstanceId, vnfInstanceId, vfModuleId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Delete volume group instance. - * - * @param serviceInstanceId the service instance id - * @param vnfInstanceId the vnf instance id - * @param volumeGroupId the volume group id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_delete_volumegroup_instance/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupId}", method = RequestMethod.POST) - public ResponseEntity deleteVolumeGroupInstance( - @PathVariable("serviceInstanceId") String serviceInstanceId, @PathVariable("vnfInstanceId") String vnfInstanceId, @PathVariable("volumeGroupId") String volumeGroupId, - HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "deleteVolumeGroupInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.deleteVolumeGroupInstance(mso_request, serviceInstanceId, vnfInstanceId, volumeGroupId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Delete nw instance. - * - * @param serviceInstanceId the service instance id - * @param networkInstanceId the network instance id - * @param request the request - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_delete_nw_instance/{serviceInstanceId}/networks/{networkInstanceId}", method = RequestMethod.POST) - public ResponseEntity deleteNwInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, - @PathVariable("networkInstanceId") String networkInstanceId, HttpServletRequest request, @RequestBody RequestDetails mso_request) { - String methodName = "deleteNwInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.deleteNwInstance(mso_request, serviceInstanceId, networkInstanceId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Gets the orchestration request. - * - * @param requestId the request id - * @param request the request - * @return the orchestration request - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_get_orch_req/{requestId}", method = RequestMethod.GET) - public ResponseEntity getOrchestrationRequest(@PathVariable("requestId") String requestId, - HttpServletRequest request) { - - String methodName = "getOrchestrationRequest"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - - MsoResponseWrapper w = msoBusinessLogic.getOrchestrationRequest(requestId); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * Gets the orchestration requests. - * - * @param filterString the filter string - * @param request the request - * @return the orchestration requests - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_get_orch_reqs/{filterString}", method = RequestMethod.GET) - public ResponseEntity getOrchestrationRequests(@PathVariable("filterString") String filterString, - HttpServletRequest request) { - - String methodName = "getOrchestrationRequests"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - - MsoResponseWrapper w = msoBusinessLogic.getOrchestrationRequests(filterString); - - // always return OK, the MSO status code is embedded in the body - return (new ResponseEntity(w.getResponse(), HttpStatus.OK)); - } - - /** - * activate to a pnf instance. - * - * @param serviceInstanceId the id of the service. - * @param requestDetails the body of the request. - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_activate_service_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity activateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) { - String methodName = "activateServiceInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.setServiceInstanceStatus(requestDetails, serviceInstanceId, true); - return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); - } - - /** - * deactivate a service instance. - * - * @param serviceInstanceId the id of the service. - * @param requestDetails the body of the request. - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_deactivate_service_instance/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity deactivateServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId, @RequestBody RequestDetails requestDetails) { - String methodName = "deactivateServiceInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.setServiceInstanceStatus(requestDetails, serviceInstanceId, false); - return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); - } - - /** - * Gets the orchestration requests for the dashboard. - * currently its all the orchestration requests with RequestType updateInstance or replaceInstance. - * @return the orchestration requests - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_get_orch_reqs/dashboard", method = RequestMethod.GET) - public List getOrchestrationRequestsForDashboard() { - - String methodName = "getOrchestrationRequestsForDashboard"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - - return msoBusinessLogic.getOrchestrationRequestsForDashboard(); - } - - /** - * Gets the Manual Tasks for the given request id. - * - * @param originalRequestId the id of the original request. - * @return the tasks - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_get_man_task/{originalRequestId}", method = RequestMethod.GET) - public List getManualTasksByRequestId(@PathVariable("originalRequestId") String originalRequestId) { - - String methodName = "getManualTasksByRequestId"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - return msoBusinessLogic.getManualTasksByRequestId(originalRequestId); - } - - /** - * Complete the manual task. - * - * @param taskId the id of the task to complete. - * @param requestDetails the body of the request. - * @return the response entity - * @throws Exception the exception - */ - @RequestMapping(value = "/mso_post_man_task/{taskId}", method = RequestMethod.POST) - public ResponseEntity manualTaskComplete(@PathVariable("taskId") String taskId , @RequestBody RequestDetails requestDetails) { - - String methodName = "manualTaskComplete"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w = msoBusinessLogic.completeManualTask(requestDetails, taskId); - return new ResponseEntity(w.getResponse(), HttpStatus.OK); - } - - @RequestMapping(value = "/mso_remove_relationship/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity removeRelationshipFromServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId , - @RequestBody RequestDetails requestDetails) { - - String methodName = "removeRelationshipFromServiceInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w; - try { - w = msoBusinessLogic.removeRelationshipFromServiceInstance(requestDetails, serviceInstanceId); - } catch (Exception e){ - LOGGER.error("Internal error when calling MSO controller logic for {}", methodName, e); - return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); - } - - @RequestMapping(value = "/mso_add_relationship/{serviceInstanceId}", method = RequestMethod.POST) - public ResponseEntity addRelationshipToServiceInstance(@PathVariable("serviceInstanceId") String serviceInstanceId , - @RequestBody RequestDetails requestDetails) { - - String methodName = "addRelationshipToServiceInstance"; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - MsoResponseWrapper w; - try { - w = msoBusinessLogic.addRelationshipToServiceInstance(requestDetails, serviceInstanceId); - } catch (Exception e){ - LOGGER.error("Internal error when calling MSO controller logic for {}", methodName, e); - return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); - } - return new ResponseEntity<>(w.getResponse(), HttpStatus.OK); - } - - /** - * Exception handler. - * - * @param e the e - * @param response the response - * @throws IOException Signals that an I/O exception has occurred. - */ - @ExceptionHandler(Exception.class) - private void exceptionHandler(Exception e, HttpServletResponse response) throws IOException { - - /* - * The following "logger.error" lines "should" be sufficient for logging the exception. - * However, the console output in my Eclipse environment is NOT showing ANY of the - * logger statements in this class. Thus the temporary "e.printStackTrace" statement - * is also included. - */ - - String methodName = "exceptionHandler"; - LOGGER.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - LOGGER.error(EELFLoggerDelegate.errorLogger, sw.toString()); - - /* - * Temporary - IF the above mentioned "logger.error" glitch is resolved ... - * this statement could be removed since it would then likely result in duplicate - * trace output. - */ - e.printStackTrace(System.err); - - response.setContentType("application/json; charset=UTF-8"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - - ExceptionResponse exceptionResponse = new ExceptionResponse(); - exceptionResponse.setException(e.getClass().toString().replaceFirst("^.*\\.", "")); - exceptionResponse.setMessage(e.getMessage()); - - response.getWriter().write(new ObjectMapper().writeValueAsString(exceptionResponse)); - - response.flushBuffer(); - - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java deleted file mode 100644 index 6a4527cb..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java +++ /dev/null @@ -1,362 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.controllers; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.MoreObjects; -import io.joshworks.restclient.http.HttpResponse; -import java.util.HashMap; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.model.ExceptionResponse; -import org.onap.vid.model.RequestReferencesContainer; -import org.onap.vid.mso.MsoBusinessLogic; -import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.MsoResponseWrapper2; -import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; -import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; -import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; -import org.onap.vid.mso.rest.RequestDetails; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.onap.vid.utils.Logging.getMethodCallerName; -import static org.onap.vid.utils.Logging.getMethodName; - -@RestController -@RequestMapping("operationalEnvironment") -public class OperationalEnvironmentController extends VidRestrictedBaseController { - - private final MsoInterface restMso; - private final MsoBusinessLogic msoBusinessLogic; - - private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("String value \'(.*)\': value not"); - - - @Autowired - public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoInterface msoClientInterface) { - this.restMso = msoClientInterface; - this.msoBusinessLogic = msoBusinessLogic; - } - - @RequestMapping(value = "/create", method = RequestMethod.POST) - public MsoResponseWrapper2 createOperationalEnvironment(HttpServletRequest request, @RequestBody OperationalEnvironmentCreateBody operationalEnvironment) { - debugStart(operationalEnvironment); - String userId = ControllersUtils.extractUserId(request); - RequestDetailsWrapper requestDetailsWrapper = msoBusinessLogic.convertParametersToRequestDetails(operationalEnvironment, userId); - String path = msoBusinessLogic.getOperationalEnvironmentCreationPath(); - - HttpResponse msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); - debugEnd(msoResponse); - return new MsoResponseWrapper2<>(msoResponse); - } - - @RequestMapping(value = "/activate", method = RequestMethod.POST) - public MsoResponseWrapper2 activate(HttpServletRequest request, - @RequestParam("operationalEnvironment") String operationalEnvironmentId, - @RequestBody OperationalEnvironmentActivateBody activateRequest) throws MissingServletRequestParameterException { - - verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment"); - - //manifest is null in case of wrong manifest structure (deserialization failure of the manifest) - if (activateRequest.getManifest()==null || activateRequest.getManifest().getServiceModelList()==null) { - throw new BadManifestException("Manifest structure is wrong"); - } - - String userId = ControllersUtils.extractUserId(request); - - OperationalEnvironmentActivateInfo activateInfo = new OperationalEnvironmentActivateInfo(activateRequest, userId, operationalEnvironmentId); - debugStart(activateInfo); - - String path = msoBusinessLogic.getOperationalEnvironmentActivationPath(activateInfo); - RequestDetailsWrapper requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentActivationRequestDetails(activateInfo); - - HttpResponse msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); - - debugEnd(msoResponse); - return new MsoResponseWrapper2<>(msoResponse); - } - - @RequestMapping(value = "/deactivate", method = RequestMethod.POST) - public MsoResponseWrapper2 deactivate(HttpServletRequest request, - @RequestParam("operationalEnvironment") String operationalEnvironmentId, - @RequestBody Map deactivationRequest) throws MissingServletRequestParameterException { - - verifyIsNotEmpty(operationalEnvironmentId, "operationalEnvironment"); - - String userId = ControllersUtils.extractUserId(request); - - OperationalEnvironmentDeactivateInfo deactivateInfo = new OperationalEnvironmentDeactivateInfo(userId, operationalEnvironmentId); - debugStart(deactivateInfo); - - String path = msoBusinessLogic.getOperationalEnvironmentDeactivationPath(deactivateInfo); - RequestDetailsWrapper requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentDeactivationRequestDetails(deactivateInfo); - - HttpResponse msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); - - debugEnd(msoResponse); - return new MsoResponseWrapper2<>(msoResponse); - } - - @RequestMapping(value = "/requestStatus", method = RequestMethod.GET) - public MsoResponseWrapper2 status(HttpServletRequest request, @RequestParam("requestId") String requestId) throws MissingServletRequestParameterException { - - debugStart(requestId); - - verifyIsNotEmpty(requestId, "requestId"); - String path = msoBusinessLogic.getCloudResourcesRequestsStatusPath(requestId); - - HttpResponse msoResponse = restMso.get(path, HashMap.class); - - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), msoResponse); - return new MsoResponseWrapper2<>(msoResponse); - } - - @ExceptionHandler({ - org.springframework.web.bind.MissingServletRequestParameterException.class, - BadManifestException.class - }) - @ResponseStatus(value = HttpStatus.BAD_REQUEST) - public ExceptionResponse clientDerivedExceptionAsBadRequest(Exception e) { - // same handler, different HTTP Code - return exceptionHandler(e); - } - - @ExceptionHandler({ - org.springframework.http.converter.HttpMessageNotReadableException.class, - }) - @ResponseStatus(value = HttpStatus.BAD_REQUEST) - public ExceptionResponse handlingHttpMessageNotReadableException(Exception e) { - //in case of wrong value in manifest for RecoveryAction the message contains the class name. - //The wrong value is in also part of this messages - //within the pattern of: String value '': value not - //so we use regex to find the wrong value - if (e.getMessage().contains(OperationalEnvironmentRecoveryAction.class.getName())) { - LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodName(), ExceptionUtils.getMessage(e), e); - String message = "Wrong value for RecoveryAction in manifest. Allowed options are: "+OperationalEnvironmentRecoveryAction.options; - - Matcher matcher = RECOVERY_ACTION_MESSAGE_PATTERN.matcher(e.getMessage()); - if (matcher.find()) { - String wrongValue = matcher.group(1); - message = message+". Wrong value is: "+wrongValue; - } - return new ExceptionResponse(new BadManifestException(message)); - } - return exceptionHandler(e); - } - - - public enum OperationalEnvironmentRecoveryAction { - abort, - retry, - skip; - - public static final String options = Stream.of(OperationalEnvironmentRecoveryAction.values()).map(OperationalEnvironmentRecoveryAction::name).collect(Collectors.joining(", ")); - } - - public static class ActivateServiceModel { - private String serviceModelVersionId; - private OperationalEnvironmentRecoveryAction recoveryAction; - - public ActivateServiceModel() { - } - - public ActivateServiceModel(String serviceModelVersionId, OperationalEnvironmentRecoveryAction recoveryAction) { - this.serviceModelVersionId = serviceModelVersionId; - this.recoveryAction = recoveryAction; - } - - public String getServiceModelVersionId() { - return serviceModelVersionId; - } - - public void setServiceModelVersionId(String serviceModelVersionId) { - this.serviceModelVersionId = serviceModelVersionId; - } - - public OperationalEnvironmentRecoveryAction getRecoveryAction() { - return recoveryAction; - } - - public void setRecoveryAction(OperationalEnvironmentRecoveryAction recoveryAction) { - this.recoveryAction = recoveryAction; - } - } - - @JsonIgnoreProperties(ignoreUnknown = true) - public static class OperationalEnvironmentManifest { - - - private List serviceModelList; - - public OperationalEnvironmentManifest() { - } - - public OperationalEnvironmentManifest(List serviceModelList) { - this.serviceModelList = serviceModelList; - } - - public List getServiceModelList() { - return serviceModelList; - } - - public void setServiceModelList(List serviceModelList) { - this.serviceModelList = serviceModelList; - } - } - - public static class OperationalEnvironmentActivateBody { - private final String relatedInstanceId; - private final String relatedInstanceName; - private final String workloadContext; - private final OperationalEnvironmentManifest manifest; - - public OperationalEnvironmentActivateBody(@JsonProperty(value = "relatedInstanceId", required = true) String relatedInstanceId, - @JsonProperty(value = "relatedInstanceName", required = true) String relatedInstanceName, - @JsonProperty(value = "workloadContext", required = true) String workloadContext, - @JsonProperty(value = "manifest", required = true) OperationalEnvironmentManifest manifest) { - this.relatedInstanceId = relatedInstanceId; - this.relatedInstanceName = relatedInstanceName; - this.workloadContext = workloadContext; - this.manifest = manifest; - } - - - public String getRelatedInstanceId() { - return relatedInstanceId; - } - - public String getRelatedInstanceName() { - return relatedInstanceName; - } - - public String getWorkloadContext() { - return workloadContext; - } - - public OperationalEnvironmentManifest getManifest() { - return manifest; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("relatedInstanceId", relatedInstanceId) - .add("relatedInstanceName", relatedInstanceName) - .add("workloadContext", workloadContext) - .add("manifest", manifest) - .toString(); - } - } - - public static class OperationalEnvironmentCreateBody { - private final String instanceName; - private final String ecompInstanceId; - private final String ecompInstanceName; - private final String operationalEnvironmentType; - private final String tenantContext; - private final String workloadContext; - - public OperationalEnvironmentCreateBody(@JsonProperty(value = "instanceName", required = true) String instanceName, - @JsonProperty(value = "ecompInstanceId", required = true) String ecompInstanceId, - @JsonProperty(value = "ecompInstanceName", required = true) String ecompInstanceName, - @JsonProperty(value = "operationalEnvironmentType", required = true) String operationalEnvironmentType, - @JsonProperty(value = "tenantContext", required = true) String tenantContext, - @JsonProperty(value = "workloadContext", required = true) String workloadContext) { - this.instanceName = instanceName; - this.ecompInstanceId = ecompInstanceId; - this.ecompInstanceName = ecompInstanceName; - this.operationalEnvironmentType = operationalEnvironmentType; - this.tenantContext = tenantContext; - this.workloadContext = workloadContext; - } - - public String getInstanceName() { - return instanceName; - } - - public String getEcompInstanceId() { - return ecompInstanceId; - } - - public String getEcompInstanceName() { - return ecompInstanceName; - } - - public String getOperationalEnvironmentType() { - return operationalEnvironmentType; - } - - public String getTenantContext() { - return tenantContext; - } - - public String getWorkloadContext() { - return workloadContext; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("instanceName", instanceName) - .add("ecompInstanceId", ecompInstanceId) - .add("ecompInstanceName", ecompInstanceName) - .add("operationalEnvironmentType", operationalEnvironmentType) - .add("tenantContext", tenantContext) - .add("workloadContext", workloadContext) - .toString(); - } - } - - private void debugEnd(HttpResponse msoResponse) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), msoResponse); - } - - private void debugStart(Object requestInfo) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodCallerName(), requestInfo); - } - - private void verifyIsNotEmpty(String fieldValue, String fieldName) throws MissingServletRequestParameterException { - if (StringUtils.isEmpty(fieldValue)) { - throw new MissingServletRequestParameterException(fieldName, "String"); - } - } - - public static class BadManifestException extends RuntimeException { - public BadManifestException(String message) { - super(message); - } - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java deleted file mode 100644 index 80b4739d..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/PolicyController.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.controllers; - -import org.json.simple.JSONObject; -import org.onap.vid.policy.*; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import java.util.UUID; - -/** - * Controller to handle Policy requests. - */ - -@RestController -public class PolicyController extends RestrictedBaseController{ - - /** The logger. */ - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(PolicyController.class); - - @RequestMapping(value="/get_policy",method = RequestMethod.POST) - public ResponseEntity getPolicyInfo( HttpServletRequest request, @RequestBody JSONObject policy_request) { - - LOGGER.debug("#####################POLICY API CALL STARTED ###############"+ PolicyProperties.POLICY_GET_CONFIG_VAL); - LOGGER.debug("#####################Policy Request ###############"+policy_request.toString()); - - String path = PolicyProperties.getProperty(PolicyProperties.POLICY_GET_CONFIG_VAL); - PolicyResponseWrapper policyResWrapper = getPolicyConfig(policy_request,path); - - LOGGER.debug("$$$$$$$$$$$$$$$$$$$$$$ " + new ResponseEntity(policyResWrapper.getResponse(), HttpStatus.OK).toString()); - - return ( new ResponseEntity(policyResWrapper.getResponse(), HttpStatus.valueOf(policyResWrapper.getStatus())) ); - } - - protected static PolicyResponseWrapper getPolicyConfig(JSONObject request, String path) { - String methodName = "getPolicyConfig"; - String uuid = UUID.randomUUID().toString(); - LOGGER.debug( "starting getPolicyConfig "); - - try { - //STARTING REST API CALL AS AN FACTORY INSTACE - PolicyRestInterfaceIfc restController = PolicyRestInterfaceFactory.getInstance(); - - RestObject restObjStr = new RestObject(); - String str = new String(); - restObjStr.set(str); - restController.Post(str, request, uuid, path, restObjStr ); - PolicyResponseWrapper policyRespWrapper = PolicyUtil.wrapResponse (restObjStr); - - LOGGER.debug( "<== " + methodName + " w=" + policyRespWrapper.getResponse()); - return policyRespWrapper; - } catch (Exception e) { - LOGGER.debug( "EXCEPTION in getPolicyConfig <== " + "." + methodName + e.toString()); - throw e; - } - } -} - diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java deleted file mode 100644 index a2145de3..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/ProbeController.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.onap.vid.controllers; - -import org.onap.vid.aai.AaiClient; -import org.onap.vid.model.probes.ExternalComponentStatus; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import java.util.ArrayList; -import java.util.List; - -@RestController -@RequestMapping("probe") -public class ProbeController extends RestrictedBaseController { - @Autowired - private AaiClient aaiClient; - - @RequestMapping(method= RequestMethod.GET) - public List getProbe(){ - List componentStatuses = new ArrayList<>(); - componentStatuses.add(aaiClient.probeAaiGetAllSubscribers()); - return componentStatuses; - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java deleted file mode 100644 index 2c823863..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/PropertyController.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.controllers; - -import org.onap.vid.category.CategoryParametersResponse; -import org.onap.vid.model.CategoryParameter.Family; -import org.onap.vid.services.CategoryParameterService; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.http.HttpServletRequest; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import static org.onap.vid.utils.Logging.getMethodName; - -/** - * The Class PropertyController. - */ -@RestController -public class PropertyController extends RestrictedBaseController{ - - - /** The logger. */ - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(PropertyController.class); - - /** The Constant dateFormat. */ - final protected static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - @Autowired - protected CategoryParameterService categoryParameterService; - - - /** - * Welcome. - * - * @param request the request - * @return the model and view - */ - @RequestMapping(value = {"/propertyhome" }, method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== PropertyController welcome start"); - return new ModelAndView(getViewName()); - } - - /** - * Gets the property. - * - * @param name the name - * @param defaultvalue the defaultvalue - * @param request the request - * @return the property - * @throws Exception the exception - */ - @RequestMapping(value = "/get_property/{name}/{defaultvalue}", method = RequestMethod.GET) - public ResponseEntity getProperty (@PathVariable("name") String name, @PathVariable("defaultvalue") String defaultvalue, - HttpServletRequest request) { - - String methodName = "getProperty"; - ResponseEntity resp = null; - String pvalue = null; - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); - - try { - // convert "_" to "." in the property name - if (name == null || name.length() == 0 ) { - return ( new ResponseEntity (defaultvalue, HttpStatus.OK)); - } - // convert "_" to "." in the property name - String propertyName = name.replace('_', '.'); - pvalue = SystemProperties.getProperty(propertyName); - if ( ( pvalue == null ) || ( pvalue.length() == 0 ) ) { - pvalue = defaultvalue; - } - resp = new ResponseEntity(pvalue, HttpStatus.OK); - } - catch (Exception e) { - LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - throw e; - } - LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " returning " + pvalue); - return ( resp ); - } - - /** - * Gets the owning entity properties. - * @param request the request - * @return the property - * @throws Exception the exception - */ - @RequestMapping(value = "/category_parameter", method = RequestMethod.GET) - public ResponseEntity getCategoryParameter(HttpServletRequest request, @RequestParam(value="familyName", required = true) Family familyName) { - LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName()); - try { - CategoryParametersResponse response = categoryParameterService.getCategoryParameters(familyName); - LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response); - return new ResponseEntity<>(response, HttpStatus.OK); - } - catch (Exception exception) { - LOGGER.error("failed to retrieve category parameter list from DB.", exception); - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); - } - } - - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java deleted file mode 100644 index dd6388d8..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/RoleGeneratorController.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.onap.vid.controllers; - -import org.onap.vid.services.RoleGeneratorService; -import org.onap.portalsdk.core.controller.UnRestrictedBaseController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class RoleGeneratorController extends UnRestrictedBaseController { - @Autowired - private RoleGeneratorService roleGeneratorService; - public static final String GENERATE_ROLE_SCRIPT = "generateRoleScript"; - @RequestMapping(value = GENERATE_ROLE_SCRIPT +"/{firstRun}", method = RequestMethod.GET ) - public ResponseEntity generateRoleScript (@PathVariable("firstRun") boolean firstRun) { - ResponseEntity response = null; - String query = roleGeneratorService.generateRoleScript(firstRun); - response = new ResponseEntity(query, HttpStatus.OK); - return response; - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java deleted file mode 100644 index b9d67b6d..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.vid.controllers; - -import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.beans.SecureServices; -import org.onap.vid.exceptions.VidServiceUnavailableException; -import org.onap.vid.model.PombaInstance.PombaRequest; -import org.onap.vid.model.ServiceModel; -import org.onap.vid.roles.Role; -import org.onap.vid.roles.RoleProvider; -import org.onap.vid.services.AaiService; -import org.onap.vid.services.PombaService; -import org.onap.vid.services.VidService; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -@RestController -public class VidController extends RestrictedBaseController { - - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidController.class); - - private final VidService vidService; - private final AaiService aaiService; - private final RoleProvider roleProvider; - private final PombaService pombaService; - - @Autowired - public VidController(VidService vidService, AaiService aaiService, RoleProvider roleProvider, - PombaService pombaService) { - this.vidService = vidService; - this.aaiService = aaiService; - this.roleProvider = roleProvider; - this.pombaService = pombaService; - } - - /** - * @param request the request - * @return the services - */ - @RequestMapping(value = {"/rest/models/services"}, method = RequestMethod.GET) - public SecureServices getServices(HttpServletRequest request) { - LOG.info("Start API for browse ASDC was called"); - SecureServices secureServices = new SecureServices(); - List roles = roleProvider.getUserRoles(request); - secureServices.setServices(aaiService.getServicesByDistributionStatus()); - secureServices.setReadOnly(roleProvider.userPermissionIsReadOnly(roles)); - return secureServices; - } - - - /** - * @param uuid the uuid - * @return the services - * @throws VidServiceUnavailableException the vid service unavailable exception - */ - @RequestMapping(value = {"/rest/models/services/{uuid}"}, method = RequestMethod.GET) - public ServiceModel getService(@PathVariable("uuid") String uuid) throws VidServiceUnavailableException { - try { - return vidService.getService(uuid); - } catch (AsdcCatalogException e) { - LOG.error("Failed to retrieve service definitions from SDC. Error: " + e.getMessage(), e); - throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e); - } - } - - @RequestMapping(value = "/rest/models/reset", method = RequestMethod.POST) - @ResponseStatus(HttpStatus.ACCEPTED) - public void invalidateServiceModelCache() { - vidService.invalidateServiceCache(); - } - - /** - * @return the services view - * @throws VidServiceUnavailableException the vid service unavailable exception - */ - // FIX ME: Circular view path [serviceModels]: would dispatch back to the current handler URL [/serviceModels] again. - @RequestMapping(value = {"/serviceModels"}, method = RequestMethod.GET) - public ModelAndView getServicesView() { - return new ModelAndView("serviceModels"); - } - - @RequestMapping(value = {"/rest/models/services/verifyService"}, method = RequestMethod.POST) - public void verifyServiceInstance(@RequestBody PombaRequest pombaRequest) { - pombaService.verify(pombaRequest); - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java deleted file mode 100644 index b520bc02..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/VidRestrictedBaseController.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.onap.vid.controllers; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.exception.ExceptionUtils; -import org.onap.vid.model.ExceptionResponse; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; - -import static org.onap.vid.utils.Logging.getMethodCallerName; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; - -public abstract class VidRestrictedBaseController extends RestrictedBaseController { - - protected final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(this.getClass().getName()); - - @ExceptionHandler(MethodArgumentTypeMismatchException.class) - @ResponseBody - public ResponseEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) { - LOGGER.error(EELFLoggerDelegate.errorLogger, "{}: {}", getMethodCallerName(), ExceptionUtils.getMessage(e), e); - Class type = e.getRequiredType(); - String message; - if (type.isEnum()) { - message = "The parameter " + e.getName() + " must have a value among : " + StringUtils.join(type.getEnumConstants(), ", "); - } - else { - message = "The parameter " + e.getName() + " must be of type " + type.getTypeName(); - } - ResponseEntity response = new ResponseEntity(message, HttpStatus.BAD_REQUEST); - return response; - } - - @ExceptionHandler(Exception.class) - @ResponseStatus(value=INTERNAL_SERVER_ERROR) - public ExceptionResponse exceptionHandler(Exception e) { - return ControllersUtils.handleException(e, LOGGER); - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/ViewLogController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/ViewLogController.java deleted file mode 100644 index a95f0add..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/ViewLogController.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.controllers; - -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.ModelAndView; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - - -/** - * The Class ViewLogController. - */ -@RestController -public class ViewLogController extends RestrictedBaseController{ - - /** The logger. */ - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ViewLogController.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The servlet context. */ - private @Autowired ServletContext servletContext; - - /** - * Welcome. - * - * @param request the request - * @return the model and view - */ - @RequestMapping(value = {"/viewlog" }, method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request) { - - return new ModelAndView(getViewName()); - } - - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java deleted file mode 100644 index 56dce9ac..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java +++ /dev/null @@ -1,226 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.controllers; - -import com.fasterxml.jackson.core.JsonProcessingException; -import io.joshworks.restclient.http.mapper.ObjectMapper; -import java.io.IOException; -import org.onap.vid.aai.AaiClient; -import org.onap.vid.aai.AaiClientInterface; -import org.onap.vid.aai.AaiOverTLSClient; -import org.onap.vid.aai.AaiOverTLSClientInterface; -import org.onap.vid.aai.AaiOverTLSPropertySupplier; -import org.onap.vid.aai.AaiResponseTranslator; -import org.onap.vid.aai.PombaClientImpl; -import org.onap.vid.aai.PombaClientInterface; -import org.onap.vid.aai.PombaRestInterface; -import org.onap.vid.aai.model.PortDetailsTranslator; -import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.vid.aai.util.HttpsAuthClient; -import org.onap.vid.aai.util.SSLContextProvider; -import org.onap.vid.aai.util.ServletRequestHelper; -import org.onap.vid.aai.util.SystemPropertyHelper; -import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.parser.ToscaParserImpl2; -import org.onap.vid.asdc.rest.SdcRestClient; -import org.onap.vid.client.SyncRestClient; -import org.onap.vid.client.SyncRestClientInterface; -import org.onap.vid.properties.AsdcClientConfiguration; -import org.onap.vid.services.AaiService; -import org.onap.vid.services.AaiServiceImpl; -import org.onap.vid.services.PombaService; -import org.onap.vid.services.PombaServiceImpl; -import org.onap.vid.services.VidService; -import org.onap.vid.services.VidServiceImpl; -import org.onap.vid.scheduler.SchedulerRestInterface; -import org.onap.vid.scheduler.SchedulerRestInterfaceIfc; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.togglz.core.manager.FeatureManager; - -import javax.servlet.ServletContext; -import java.io.File; - -@Configuration -public class WebConfig { - - /** - * Gets the object mapper. - * - * @return the object mapper - */ - @Bean - public com.fasterxml.jackson.databind.ObjectMapper getObjectMapper() { - return new com.fasterxml.jackson.databind.ObjectMapper(); - } - - - @Bean - public VidService vidService(AsdcClient asdcClient, FeatureManager featureManager) { - return new VidServiceImpl(asdcClient, featureManager); - } - - @Bean - public AaiService getAaiService() { - return new AaiServiceImpl(); - } - - @Bean - public AaiResponseTranslator aaiResponseTranslator() { - return new AaiResponseTranslator(); - } - - @Bean - public PortDetailsTranslator portDetailsTranslator() { - return new PortDetailsTranslator(); - } - - @Bean - public AaiClientInterface getAaiRestInterface(@Qualifier("aaiRestInterface") AAIRestInterface restController, PortDetailsTranslator portsDetailsTranslator) { - return new AaiClient(restController, portsDetailsTranslator); - } - - @Bean(name = "aaiRestInterface") - public AAIRestInterface aaiRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) { - return new AAIRestInterface(httpsAuthClientFactory, servletRequestHelper, systemPropertyHelper); - } - - @Bean - public PombaRestInterface getPombaRestInterface(HttpsAuthClient httpsAuthClientFactory, ServletRequestHelper servletRequestHelper, SystemPropertyHelper systemPropertyHelper) { - return new PombaRestInterface(httpsAuthClientFactory, servletRequestHelper, systemPropertyHelper); - } - - @Bean - public SSLContextProvider sslContextProvider() { - return new SSLContextProvider(); - } - - @Bean - public SystemPropertyHelper systemPropertyHelper() { - return new SystemPropertyHelper(); - } - - @Bean - public ServletRequestHelper servletRequestHelper() { - return new ServletRequestHelper(); - } - - @Bean - public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider) { - final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath(); - return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider); - } - - @Bean - public AsdcClient sdcClient(AsdcClientConfiguration asdcClientConfiguration, SyncRestClientInterface syncRestClient) { - String auth = asdcClientConfiguration.getAsdcClientAuth(); - String host = asdcClientConfiguration.getAsdcClientHost(); - String protocol = asdcClientConfiguration.getAsdcClientProtocol(); - int port = asdcClientConfiguration.getAsdcClientPort(); - - return new SdcRestClient(protocol + "://" + host + ":" + port + "/", auth, syncRestClient); - } - - @Bean - public SyncRestClientInterface syncRestClient() { - return new SyncRestClient(); - } - - @Bean - public ToscaParserImpl2 getToscaParser() { - return new ToscaParserImpl2(); - } - - @Bean - public PombaService getVerifyServiceInstanceService() { - return new PombaServiceImpl(); - } - - @Bean - public PombaClientInterface getVerifyServiceInstanceClientInterface() { - return new PombaClientImpl(); - } - - @Bean - public SchedulerRestInterfaceIfc getSchedulerRestInterface(){ - return new SchedulerRestInterface(); - } - - @Bean(name = "aaiClientForFasterXmlMapping") - public AaiOverTLSClientInterface getAaiClientForFasterXmlMapping(){ - ObjectMapper objectMapper = new ObjectMapper() { - - com.fasterxml.jackson.databind.ObjectMapper om = new com.fasterxml.jackson.databind.ObjectMapper(); - - @Override - public T readValue(String s, Class aClass) { - try { - return om.readValue(s, aClass); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public String writeValue(Object o) { - try { - return om.writeValueAsString(o); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - } - }; - - return new AaiOverTLSClient(new SyncRestClient(objectMapper), new AaiOverTLSPropertySupplier()); - } - - - @Bean(name = "aaiClientForCodehausMapping") - public AaiOverTLSClientInterface getAaiClientForCodehausMapping() { - - ObjectMapper objectMapper = new ObjectMapper() { - - org.codehaus.jackson.map.ObjectMapper om = new org.codehaus.jackson.map.ObjectMapper(); - - @Override - public T readValue(String s, Class aClass) { - try { - return om.readValue(s, aClass); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public String writeValue(Object o) { - try { - return om.writeValueAsString(o); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - - return new AaiOverTLSClient(new SyncRestClient(objectMapper), new AaiOverTLSPropertySupplier()); - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/Job.java b/vid-app-common/src/main/java/org/onap/vid/job/Job.java index 77f348dc..144c96ca 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/Job.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/Job.java @@ -1,6 +1,7 @@ package org.onap.vid.job; import com.fasterxml.jackson.annotation.JsonIgnore; +import org.onap.vid.job.impl.JobSharedData; import java.util.Map; import java.util.UUID; @@ -18,30 +19,49 @@ public interface Job { @JsonIgnore Map getData(); + JobSharedData getSharedData(); + void setTypeAndData(JobType jobType, Map data); UUID getTemplateId(); void setTemplateId(UUID templateId); + Integer getIndexInBulk(); + void setIndexInBulk(Integer indexInBulk); JobType getType(); enum JobStatus { - COMPLETED(true), - FAILED(true), + COMPLETED(true, false), + FAILED(true, true), IN_PROGRESS(false), + RESOURCE_IN_PROGRESS(false), PAUSE(false), PENDING(false), - STOPPED(true); + STOPPED(true, true), + COMPLETED_WITH_ERRORS(true, true), + COMPLETED_WITH_NO_ACTION(true, false), + CREATING(false); private final Boolean finalStatus; public Boolean isFinal(){return finalStatus;} + private final Boolean failure; + public Boolean isFailure() { + return failure; + } + JobStatus(Boolean finalStatus) { - this.finalStatus = finalStatus ; + this(finalStatus, false); } + + JobStatus(Boolean finalStatus, boolean failure) { + this.finalStatus = finalStatus; + this.failure = failure; + } + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java b/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java index 1701092b..f281f98a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobAdapter.java @@ -1,9 +1,8 @@ package org.onap.vid.job; -import org.onap.vid.model.JobBulk; +import org.onap.vid.job.impl.JobSharedData; import org.onap.vid.model.JobModel; -import java.util.List; import java.util.Map; import java.util.UUID; @@ -13,14 +12,12 @@ import java.util.UUID; public interface JobAdapter { JobModel toModel(Job job); - JobBulk toModelBulk(List jobList); + Job createServiceInstantiationJob(JobType jobType, AsyncJobRequest request, UUID templateId, String userId, String optimisticUniqueServiceInstanceName, Integer indexInBulk); - List createBulkOfJobs(Map bulkRequest); - - Job createJob(JobType jobType, AsyncJobRequest request, UUID templateId, String userId, Integer indexInBulk); + Job createChildJob(JobType jobType, Job.JobStatus jobStatus, AsyncJobRequest request, JobSharedData parentSharedData, Map jobData); // Marks types that are an AsyncJob payload - public interface AsyncJobRequest { + interface AsyncJobRequest { } } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java index c32645ca..7f62bcac 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobCommand.java @@ -1,7 +1,8 @@ package org.onap.vid.job; +import org.onap.vid.job.impl.JobSharedData; + import java.util.Map; -import java.util.UUID; /** @@ -13,11 +14,11 @@ public interface JobCommand { /** * Initialize the command state - * @param jobUuid Parent job's uuid - * @param data An input to be set into the command. Each implementation may expect different keys in the map. + * @param sharedData shared data cross all job commands + * @param commandData An input to be set into the command. Each implementation may expect different keys in the map. * @return Returns itself */ - default JobCommand init(UUID jobUuid, Map data) { + default JobCommand init(JobSharedData sharedData, Map commandData) { return this; } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobException.java b/vid-app-common/src/main/java/org/onap/vid/job/JobException.java new file mode 100644 index 00000000..ca389b03 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobException.java @@ -0,0 +1,16 @@ +package org.onap.vid.job; + +import java.util.UUID; + +public class JobException extends RuntimeException { + private final UUID jobUuid; + + public JobException(String message, UUID jobUuid, Throwable cause) { + super(message, cause); + this.jobUuid = jobUuid; + } + + public UUID getJobUuid() { + return jobUuid; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobType.java b/vid-app-common/src/main/java/org/onap/vid/job/JobType.java index 9846d277..e856ba0d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/JobType.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobType.java @@ -6,15 +6,33 @@ import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; +import static org.onap.vid.utils.Streams.not; + public enum JobType { HttpCall(HttpCallCommand.class), AggregateState(AggregateStateCommand.class), - ServiceInstantiation(ServiceInstantiationCommand.class), - InProgressStatus(InProgressStatusCommand.class), + ServiceInstantiation(MacroServiceInstantiationCommand.class), + MacroServiceInstantiation(MacroServiceInstantiationCommand.class), + ALaCarteServiceInstantiation(ALaCarteServiceInstantiationCommand.class), + ALaCarteService(ALaCarteServiceCommand.class), + VnfInstantiation(VnfInstantiationCommand.class), + VfmoduleInstantiation(VfmoduleInstantiationCommand.class), + VolumeGroupInstantiation(VolumeGroupInstantiationCommand.class), + VolumeGroupInProgressStatus(VolumeGroupInProgressStatusCommand.class), + NetworkInstantiation(NetworkInstantiationCommand.class), + InstanceGroupInstantiation(InstanceGroupInstantiationCommand.class), + InstanceGroup(InstanceGroupCommand.class), + InProgressStatus(ServiceInProgressStatusCommand.class), + ResourceInProgressStatus(ResourceInProgressStatusCommand.class), + VnfInProgressStatus(VnfInProgressStatusCommand.class), + Watching(WatchingCommand.class), + WatchingBaseModule(WatchingCommandBaseModule.class), NoOp(NoOpCommand.class); - private static final Map REVERSE_MAP = Stream.of(values()).collect(Collectors.toMap(t -> t.getCommandClass(), t -> t)); + private static final Map REVERSE_MAP = Stream.of(values()) + .filter(not(jobType -> jobType.equals(ServiceInstantiation))) + .collect(Collectors.toMap(t -> t.getCommandClass(), t -> t)); private final Class commandClass; diff --git a/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java b/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java index 856f50b2..98925d07 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/JobsBrokerService.java @@ -18,4 +18,6 @@ public interface JobsBrokerService { void delete(UUID jobId); + boolean mute(UUID jobId); + } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceCommand.kt new file mode 100644 index 00000000..f88e9d65 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceCommand.kt @@ -0,0 +1,122 @@ +package org.onap.vid.job.command + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate +import org.onap.vid.changeManagement.RequestDetailsWrapper +import org.onap.vid.job.* +import org.onap.vid.model.Action +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation +import org.onap.vid.mso.RestMsoImplementation +import org.onap.vid.mso.model.ServiceDeletionRequestDetails +import org.onap.vid.properties.VidProperties +import org.onap.vid.services.AsyncInstantiationBusinessLogic +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.http.HttpMethod +import org.springframework.stereotype.Component +import java.time.ZonedDateTime +import java.time.temporal.ChronoUnit +import java.util.* + +class ServiceExpiryChecker : ExpiryChecker { + + override fun isExpired(jobStartTime: ZonedDateTime?): Boolean { + val now = ZonedDateTime.now() + val maxHoursInProgress = VidProperties.getLongProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS) + val hoursBetween = ChronoUnit.HOURS.between(jobStartTime, now) + return maxHoursInProgress in 1..hoursBetween + } +} + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +class ALaCarteServiceCommand @Autowired constructor( + inProgressStatusService: InProgressStatusService, + watchChildrenJobsBL: WatchChildrenJobsBL, + private val asyncInstantiationBL: AsyncInstantiationBusinessLogic, + private val jobsBrokerService: JobsBrokerService, + msoResultHandlerService: MsoResultHandlerService, + private val jobAdapter: JobAdapter, + restMso: RestMsoImplementation +) : ResourceCommand(restMso, inProgressStatusService, msoResultHandlerService, watchChildrenJobsBL), JobCommand { + + override fun getExpiryChecker(): ExpiryChecker { + return ServiceExpiryChecker(); + } + + companion object { + private val LOGGER = EELFLoggerDelegate.getLogger(ALaCarteServiceCommand::class.java) + } + + override fun getRequest(): ServiceInstantiation { + return msoResultHandlerService.getRequest(sharedData) + } + + override fun createChildren(): Job.JobStatus { + val dataForChild = buildDataForChild(getRequest())//.plus(ACTION_PHASE to actionPhase) + + val childJobType = when (actionPhase) { + Action.Create -> JobType.InstanceGroupInstantiation + Action.Delete -> JobType.InstanceGroup + else -> return Job.JobStatus.COMPLETED + } + + childJobs = getRequest().vnfGroups + .map { jobAdapter.createChildJob(childJobType, Job.JobStatus.CREATING, it.value, sharedData, dataForChild) } + .map { jobsBrokerService.add(it) } + .map { it.toString() } + + return Job.JobStatus.COMPLETED_WITH_NO_ACTION + } + + private fun buildDataForChild(request: ServiceInstantiation): Map { + val commandParentData = CommandParentData() + commandParentData.addInstanceId(CommandParentData.CommandDataKey.SERVICE_INSTANCE_ID, request.instanceId) + commandParentData.addModelInfo(CommandParentData.CommandDataKey.SERVICE_MODEL_INFO, request.modelInfo) + return commandParentData.parentData + } + + override fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan { + TODO("not implemented") + } + + override fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan { + val requestDetailsWrapper = generateServiceDeletionRequest() + val path = asyncInstantiationBL.getServiceDeletionPath(getRequest().instanceId) + return MsoRestCallPlan(HttpMethod.DELETE, path, Optional.of(requestDetailsWrapper), Optional.empty(), + "delete instance with id ${getRequest().instanceId}") + + } + + override fun handleInProgressStatus(jobStatus: Job.JobStatus): Job.JobStatus { + if (jobStatus==Job.JobStatus.FAILED) { + asyncInstantiationBL.handleFailedInstantiation(sharedData.jobUuid) + return jobStatus + } + + asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, jobStatus) + return if (jobStatus == Job.JobStatus.PAUSE) Job.JobStatus.IN_PROGRESS else jobStatus + } + + + private fun generateServiceDeletionRequest(): RequestDetailsWrapper { + return asyncInstantiationBL.generateALaCarteServiceDeletionRequest( + sharedData.jobUuid, getRequest(), sharedData.userId + ) + } + + override fun getExternalInProgressStatus() = Job.JobStatus.IN_PROGRESS + + override fun isServiceCommand(): Boolean = true + + override fun onFinal(jobStatus: Job.JobStatus) { + asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, jobStatus) + } + + override fun onInitial(phase: Action) { + if (phase== Action.Delete) { + asyncInstantiationBL.updateServiceInfoAndAuditStatus(sharedData.jobUuid, Job.JobStatus.IN_PROGRESS) + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceInstantiationCommand.java new file mode 100644 index 00000000..8a1346d2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ALaCarteServiceInstantiationCommand.java @@ -0,0 +1,21 @@ +package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.JobCommand; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ALaCarteServiceInstantiationCommand extends ServiceInstantiationCommand implements JobCommand { + + @Override + protected RequestDetailsWrapper generateServiceInstantiationRequest() { + return asyncInstantiationBL.generateALaCarteServiceInstantiationRequest( + getSharedData().getJobUuid(), getRequest(), optimisticUniqueServiceInstanceName, getSharedData().getUserId() + ); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/BaseInProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseInProgressStatusCommand.java new file mode 100644 index 00000000..a035708f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseInProgressStatusCommand.java @@ -0,0 +1,95 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.job.*; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.togglz.core.manager.FeatureManager; + +import javax.inject.Inject; +import java.util.Map; + +public abstract class BaseInProgressStatusCommand extends BaseInstantiationCommand implements JobCommand { + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(BaseInProgressStatusCommand.class); + + @Inject + protected AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + protected JobsBrokerService jobsBrokerService; + + @Inject + protected JobAdapter jobAdapter; + + @Inject + protected RestMsoImplementation restMso; + + @Inject + protected FeatureManager featureManager; + + @Inject + protected InProgressStatusService inProgressStatusService; + + + protected String requestId; + + protected String instanceId; + + + @Override + public NextCommand call() { + + try { + Job.JobStatus jobStatus = inProgressStatusService.call(getExpiryChecker(), getSharedData(), requestId); + return processJobStatus(jobStatus); + } catch (javax.ws.rs.ProcessingException e) { + // Retry when we can't connect MSO during getStatus + LOGGER.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, will retry: {}", requestId, e, e); + return new NextCommand(Job.JobStatus.IN_PROGRESS, this); + } catch (InProgressStatusService.BadResponseFromMso e) { + return handleFailedMsoResponse(e.getMsoResponse()); + } + catch (RuntimeException e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, stopping: {}", requestId, e, e); + return new NextCommand(Job.JobStatus.STOPPED, this); + } + } + + protected abstract ExpiryChecker getExpiryChecker(); + + abstract NextCommand processJobStatus(Job.JobStatus jobStatus); + + private NextCommand handleFailedMsoResponse(RestObject msoResponse) { + inProgressStatusService.handleFailedMsoResponse(getSharedData().getJobUuid(), requestId, msoResponse); + return new NextCommand(Job.JobStatus.IN_PROGRESS, this); + } + + @Override + public BaseInProgressStatusCommand init(JobSharedData sharedData, Map commandData) { + return init(sharedData, (String) commandData.get("requestId"), (String) commandData.get("instanceId")); + } + + + protected BaseInProgressStatusCommand init(JobSharedData sharedData, + String requestId, + String instanceId) { + init(sharedData); + this.requestId = requestId; + this.instanceId = instanceId; + return this; + } + + @Override + public Map getData() { + return ImmutableMap.of( + "requestId", requestId, + "instanceId", instanceId + ); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/BaseInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseInstantiationCommand.java new file mode 100644 index 00000000..6f78eafa --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseInstantiationCommand.java @@ -0,0 +1,18 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.impl.JobSharedData; + +import java.util.Map; + + +public abstract class BaseInstantiationCommand extends CommandBase{ + + + protected CommandParentData commandParentData = new CommandParentData(); + + protected BaseInstantiationCommand init(JobSharedData sharedData, Map commandData) { + super.init(sharedData); + commandParentData.initParentData(commandData); + return this; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/BaseRootCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseRootCommand.java new file mode 100644 index 00000000..4930c94c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseRootCommand.java @@ -0,0 +1,41 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.RestObject; + +import javax.inject.Inject; + + +public abstract class BaseRootCommand extends CommandBase{ + + @Inject + private MsoResultHandlerService msoResultHandlerService; + + @Override + protected CommandBase init(JobSharedData sharedData) { + super.init(sharedData); + return this; + } + + protected ServiceInstantiation getRequest() { + return msoResultHandlerService.getRequest(getSharedData()); + } + + protected NextCommand handleRootResponse(RestObject msoResponse){ + MsoResult msoResult = msoResultHandlerService.handleRootResponse(getSharedData().getJobUuid(), msoResponse); + return new NextCommand(msoResult.getJobStatus(), + (msoResult.getMsoResourceIds()!=null) ? + new ServiceInProgressStatusCommand(getSharedData(), msoResult.getMsoResourceIds()) : + null + ); + + } + + protected NextCommand handleCommandFailed() { + return new NextCommand(msoResultHandlerService.handleRootCommandFailed(getSharedData().getJobUuid()).getJobStatus()); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/BaseWatchingCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseWatchingCommand.java new file mode 100644 index 00000000..b619eddf --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/BaseWatchingCommand.java @@ -0,0 +1,70 @@ +package org.onap.vid.job.command; + +import org.apache.commons.lang3.ObjectUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; + +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class BaseWatchingCommand extends BaseInstantiationCommand implements JobCommand { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(BaseWatchingCommand.class); + + @Inject + protected AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + private WatchChildrenJobsBL watchChildrenJobsBL; + + private List childrenJobsIds; + + protected boolean isService; + + public BaseWatchingCommand() {} + + public BaseWatchingCommand(JobSharedData sharedData, List childrenJobsIds, boolean isService) { + init(sharedData, childrenJobsIds, isService); + } + + @Override + public NextCommand call() { + Job.JobStatus cumulativeJobsStatus = watchChildrenJobsBL.cumulateJobStatus( + watchChildrenJobsBL.retrieveChildrenJobsStatus(childrenJobsIds), + Job.JobStatus.COMPLETED); + return getNextCommand(cumulativeJobsStatus); + } + + protected abstract NextCommand getNextCommand(Job.JobStatus cumulativeJobsStatus); + + @Override + public BaseWatchingCommand init(JobSharedData sharedData, Map commandData) { + return init( + sharedData, + (List) commandData.get("childrenJobs"), + (boolean) commandData.get("isService") + ); + } + + protected BaseWatchingCommand init(JobSharedData sharedData, List childrenJobsIds, boolean isService) { + super.init(sharedData); + this.childrenJobsIds = ObjectUtils.defaultIfNull(childrenJobsIds, new ArrayList<>()); + this.isService = isService; + return this; + } + + @Override + public Map getData() { + Map data = new HashMap<>(); + data.put("childrenJobs", childrenJobsIds); + data.put("isService", isService); + return data; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/CommandBase.java b/vid-app-common/src/main/java/org/onap/vid/job/command/CommandBase.java new file mode 100644 index 00000000..163106c0 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/CommandBase.java @@ -0,0 +1,27 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.impl.JobSharedData; + +import javax.inject.Inject; + + +public abstract class CommandBase { + + @Inject + protected CommandUtils commandUtils; + + private JobSharedData sharedData; + + protected CommandBase init(JobSharedData sharedData) { + this.setSharedData(sharedData); + return this; + } + + public JobSharedData getSharedData() { + return sharedData; + } + + private void setSharedData(JobSharedData sharedData) { + this.sharedData = sharedData; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/CommandParentData.java b/vid-app-common/src/main/java/org/onap/vid/job/command/CommandParentData.java new file mode 100644 index 00000000..25c19727 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/CommandParentData.java @@ -0,0 +1,80 @@ +package org.onap.vid.job.command; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.vid.mso.model.ModelInfo; + +import java.util.HashMap; +import java.util.Map; + +public class CommandParentData { + + + public enum CommandDataKey{ + SERVICE_MODEL_INFO, + SERVICE_INSTANCE_ID, + VNF_INSTANCE_ID, + VNF_MODEL_INFO, + VG_INSTANCE_ID, + ; + } + + private static final String RESOURCE_INSTANCE_IDS = "resourceInstancesIds"; + private static final String RESOURCE_MODEL_INFOS = "resourceModelInfos"; + + private final TypeReference> mapCommandKeyToString = + new TypeReference> () {}; + + private final TypeReference> mapCommandKeyToModelInfo = + new TypeReference> () {}; + + + private ObjectMapper objectMapper = new ObjectMapper(); + + private Map getModelInfosByCommandData(Map commandData) { + Object object = commandData.get(RESOURCE_MODEL_INFOS); + if (object != null) { + return objectMapper.convertValue(object, mapCommandKeyToModelInfo); + } + return null; + } + + private Map getInstanceIdsByCommandData(Map commandData) { + Object object = commandData.get(RESOURCE_INSTANCE_IDS); + if (object != null) { + return objectMapper.convertValue(object, mapCommandKeyToString); + } + return null; + } + + public Map getParentData() { + Map data = new HashMap<>(); + data.put(RESOURCE_INSTANCE_IDS, resourceInstancesIds); + data.put(RESOURCE_MODEL_INFOS, resourceModelInfos); + return data; + } + private Map resourceInstancesIds = new HashMap<>(); + private Map resourceModelInfos = new HashMap<>(); + + public void addModelInfo(CommandDataKey modelInfoKey, ModelInfo modelInfo) { + resourceModelInfos.put(modelInfoKey, modelInfo); + } + + public void addInstanceId(CommandDataKey instanceIdKey, String instanceId) { + resourceInstancesIds.put(instanceIdKey, instanceId); + } + public ModelInfo getModelInfo(CommandDataKey modelInfoKey) { + return resourceModelInfos.get(modelInfoKey); + } + + public String getInstanceId(CommandDataKey instanceIdKey) { + return resourceInstancesIds.get(instanceIdKey); + } + + public CommandParentData initParentData(Map commandData) { + resourceModelInfos = getModelInfosByCommandData(commandData); + resourceInstancesIds = getInstanceIdsByCommandData(commandData); + return this; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/CommandUtils.java b/vid-app-common/src/main/java/org/onap/vid/job/command/CommandUtils.java new file mode 100644 index 00000000..497eafda --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/CommandUtils.java @@ -0,0 +1,46 @@ +package org.onap.vid.job.command; + +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.services.VidService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class CommandUtils { + + private final VidService vidService; + + @Autowired + public CommandUtils(VidService vidService) { + this.vidService = vidService; + } + + public boolean isVfModuleBaseModule(String serviceModelUuid, String vfModuleModelUUID) throws AsdcCatalogException{ + ServiceModel serviceModel = vidService.getService(serviceModelUuid); + + if (serviceModel==null) { + throw new AsdcCatalogException("Failed to retrieve model with uuid "+serviceModelUuid +" from SDC"); + } + + if (serviceModel.getVfModules() == null) { + throw createAsdcCatalogVfModuleModelUUIDNotFoundException(serviceModelUuid, vfModuleModelUUID); + } + + return serviceModel.getVfModules() + .values() + .stream() + .filter(vfModule -> StringUtils.equals(vfModule.getUuid(), vfModuleModelUUID)) + .findFirst() + .orElseThrow(() -> createAsdcCatalogVfModuleModelUUIDNotFoundException(serviceModelUuid, vfModuleModelUUID)) + .getProperties() + .getBaseModule(); + } + + private AsdcCatalogException createAsdcCatalogVfModuleModelUUIDNotFoundException(String serviceModelUuid, String vfModuleModelUUID) { + return new AsdcCatalogException("Failed to find vfModuleModelUUID: " + vfModuleModelUUID + + "in model with uuid: " + serviceModelUuid); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ExpiryChecker.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ExpiryChecker.java new file mode 100644 index 00000000..1ae5d218 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ExpiryChecker.java @@ -0,0 +1,8 @@ +package org.onap.vid.job.command; + +import java.time.ZonedDateTime; + +public interface ExpiryChecker { + + boolean isExpired(ZonedDateTime jobStartTime); +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java index 5951d7c8..7ee48a8e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/HttpCallCommand.java @@ -4,13 +4,13 @@ import com.google.common.collect.ImmutableMap; import org.onap.vid.job.Job; import org.onap.vid.job.JobCommand; import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; -import javax.ws.rs.core.Response; import java.util.Map; import java.util.UUID; @@ -30,13 +30,13 @@ public class HttpCallCommand implements JobCommand { @Override public NextCommand call() { - final Response response = ClientBuilder.newClient().target(url).request().post(Entity.text(uuid.toString())); + ClientBuilder.newClient().target(url).request().post(Entity.text(uuid.toString())); return new NextCommand(Job.JobStatus.COMPLETED); } @Override - public HttpCallCommand init(UUID jobUuid, Map data) { - return init((String) data.get("url"), jobUuid); + public HttpCallCommand init(JobSharedData sharedData, Map commandData) { + return init((String) commandData.get("url"), sharedData.getJobUuid()); } private HttpCallCommand init(String url, UUID jobUuid) { diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java deleted file mode 100644 index 6685a63d..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.job.command; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.ImmutableMap; -import io.joshworks.restclient.http.HttpResponse; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.job.Job.JobStatus; -import org.onap.vid.job.JobCommand; -import org.onap.vid.job.NextCommand; -import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.rest.AsyncRequestStatus; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.services.AuditService; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; - -import javax.inject.Inject; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; - - -@Component -@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class InProgressStatusCommand implements JobCommand { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(InProgressStatusCommand.class); - - @Inject - private AsyncInstantiationBusinessLogic asyncInstantiationBL; - - @Inject - private MsoInterface restMso; - - @Inject - private AuditService auditService; - - private String requestId; - - private UUID jobUuid; - - public InProgressStatusCommand() { - } - - InProgressStatusCommand(UUID jobUuid, String requestId) { - init(jobUuid, requestId); - } - - InProgressStatusCommand(AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, MsoInterface msoInterface, AuditService auditService, UUID jobUuid, String requestId) { - this(jobUuid, requestId); - this.asyncInstantiationBL = asyncInstantiationBusinessLogic; - this.restMso = msoInterface; - this.auditService = auditService; - } - - @Override - public NextCommand call() { - - try { - String path = asyncInstantiationBL.getOrchestrationRequestsPath() + "/" + requestId; - HttpResponse msoResponse = restMso.get(path, AsyncRequestStatus.class); - - - JobStatus jobStatus; - if (msoResponse.getStatus() >= 400 || msoResponse.getBody() == null) { - auditService.setFailedAuditStatusFromMso(jobUuid, requestId, msoResponse.getStatus(), Objects.toString(msoResponse.getBody())); - LOGGER.error(EELFLoggerDelegate.errorLogger, - "Failed to get orchestration status for {}. Status code: {}, Body: {}", - requestId, msoResponse.getStatus(), Objects.toString(msoResponse.getRawBody())); - return new NextCommand(JobStatus.IN_PROGRESS, this); - } else { - jobStatus = asyncInstantiationBL.calcStatus(msoResponse.getBody()); - } - - asyncInstantiationBL.auditMsoStatus(jobUuid, msoResponse.getBody().request); - - - if (jobStatus == JobStatus.FAILED) { - asyncInstantiationBL.handleFailedInstantiation(jobUuid); - } else { - asyncInstantiationBL.updateServiceInfoAndAuditStatus(jobUuid, jobStatus); - } - //in case of JobStatus.PAUSE we leave the job itself as IN_PROGRESS, for keep tracking job progress - if (jobStatus == JobStatus.PAUSE) { - return new NextCommand(JobStatus.IN_PROGRESS, this); - } - return new NextCommand(jobStatus, this); - } catch (javax.ws.rs.ProcessingException e) { - // Retry when we can't connect MSO during getStatus - LOGGER.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, will retry: {}", requestId, e, e); - return new NextCommand(JobStatus.IN_PROGRESS, this); - } catch (RuntimeException e) { - LOGGER.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, stopping: {}", requestId, e, e); - return new NextCommand(JobStatus.STOPPED, this); - } - } - - @Override - public InProgressStatusCommand init(UUID jobUuid, Map data) { - return init(jobUuid, (String) data.get("requestId")); - } - - private InProgressStatusCommand init(UUID jobUuid, String requestId) { - this.requestId = requestId; - this.jobUuid = jobUuid; - return this; - } - - @Override - public Map getData() { - return ImmutableMap.of("requestId", requestId); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusService.java b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusService.java new file mode 100644 index 00000000..4799f008 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusService.java @@ -0,0 +1,87 @@ +package org.onap.vid.job.command; + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.job.Job; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.UUID; + +import static org.onap.vid.utils.TimeUtils.parseZonedDateTime; + +@Service +public class InProgressStatusService { + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(InProgressStatusService.class); + + private final AsyncInstantiationBusinessLogic asyncInstantiationBL; + + private final RestMsoImplementation restMso; + + private final AuditService auditService; + + @Autowired + public InProgressStatusService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation restMso, AuditService auditService) { + this.asyncInstantiationBL = asyncInstantiationBL; + this.restMso = restMso; + this.auditService = auditService; + } + + + public Job.JobStatus call(ExpiryChecker expiryChecker, JobSharedData sharedData, String requestId) { + + RestObject asyncRequestStatus = getAsyncRequestStatus(requestId); + asyncInstantiationBL.auditMsoStatus(sharedData.getRootJobId(), asyncRequestStatus.get().request); + Job.JobStatus jobStatus = asyncInstantiationBL.calcStatus(asyncRequestStatus.get()); + ZonedDateTime jobStartTime = getZonedDateTime(asyncRequestStatus, requestId); + jobStatus = expiryChecker.isExpired(jobStartTime) ? Job.JobStatus.FAILED : jobStatus; + return jobStatus; + } + + private RestObject getAsyncRequestStatus(String requestId) { + String path = asyncInstantiationBL.getOrchestrationRequestsPath()+"/"+requestId; + RestObject msoResponse = restMso.GetForObject(path, AsyncRequestStatus.class); + if (msoResponse.getStatusCode() >= 400 || msoResponse.get() == null) { + throw new BadResponseFromMso(msoResponse); + } + return msoResponse; + } + + public void handleFailedMsoResponse(UUID jobUUID, String requestId, RestObject msoResponse) { + auditService.setFailedAuditStatusFromMso(jobUUID, requestId, msoResponse.getStatusCode(), msoResponse.getRaw()); + LOGGER.error(EELFLoggerDelegate.errorLogger, + "Failed to get orchestration status for {}. Status code: {}, Body: {}", + requestId, msoResponse.getStatusCode(), msoResponse.getRaw()); + } + + public static class BadResponseFromMso extends RuntimeException { + private final RestObject msoResponse; + + public BadResponseFromMso(RestObject msoResponse) { + this.msoResponse = msoResponse; + } + + public RestObject getMsoResponse() { + return msoResponse; + } + } + + private ZonedDateTime getZonedDateTime(RestObject asyncRequestStatusResponse, String requestId) { + ZonedDateTime jobStartTime; + try { + jobStartTime = parseZonedDateTime(asyncRequestStatusResponse.get().request.startTime); + } catch (DateTimeParseException | NullPointerException e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to parse start time for {}, body: {}. Current time will be used", requestId, asyncRequestStatusResponse.getRaw(), e); + jobStartTime = ZonedDateTime.now(); + } + return jobStartTime; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupCommand.kt new file mode 100644 index 00000000..36da5084 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupCommand.kt @@ -0,0 +1,59 @@ +package org.onap.vid.job.command + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate +import org.onap.vid.job.Job +import org.onap.vid.job.JobAdapter +import org.onap.vid.job.JobCommand +import org.onap.vid.model.serviceInstantiation.InstanceGroup +import org.onap.vid.mso.RestMsoImplementation +import org.onap.vid.services.AsyncInstantiationBusinessLogic +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.beans.factory.config.ConfigurableBeanFactory +import org.springframework.context.annotation.Scope +import org.springframework.http.HttpMethod +import org.springframework.stereotype.Component +import java.util.* + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +class InstanceGroupCommand @Autowired constructor( + private val asyncInstantiationBL: AsyncInstantiationBusinessLogic, + restMso: RestMsoImplementation, + msoResultHandlerService: MsoResultHandlerService, + inProgressStatusService:InProgressStatusService, + watchChildrenJobsBL: WatchChildrenJobsBL +) : ResourceCommand(restMso, inProgressStatusService, msoResultHandlerService, watchChildrenJobsBL), JobCommand { + + companion object { + private val LOGGER = EELFLoggerDelegate.getLogger(InstanceGroupCommand::class.java) + } + + override fun createChildren(): Job.JobStatus { + return Job.JobStatus.COMPLETED_WITH_NO_ACTION + } + + override fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan { + val serviceInstanceId = commandParentData.getInstanceId(CommandParentData.CommandDataKey.SERVICE_INSTANCE_ID) + val serviceModelInfo = commandParentData.getModelInfo(CommandParentData.CommandDataKey.SERVICE_MODEL_INFO) + + val instantiatePath = asyncInstantiationBL.getInstanceGroupInstantiationPath() + + val requestDetailsWrapper = asyncInstantiationBL.generateInstanceGroupInstantiationRequest( + request as InstanceGroup, + serviceModelInfo, serviceInstanceId, + userId + ) + + val actionDescription = "create instance group in $serviceInstanceId" + + return MsoRestCallPlan(HttpMethod.POST, instantiatePath, Optional.of(requestDetailsWrapper), Optional.empty(), actionDescription) + } + + override fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan { + val path = asyncInstantiationBL.getInstanceGroupDeletePath(getRequest().instanceId) + return MsoRestCallPlan(HttpMethod.DELETE, path, Optional.empty(), Optional.of(userId), + "delete instance group with id ${getRequest().instanceId}") + + } + +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupInstantiationCommand.java new file mode 100644 index 00000000..17b3f355 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/InstanceGroupInstantiationCommand.java @@ -0,0 +1,47 @@ +package org.onap.vid.job.command;//package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.model.Action; +import org.onap.vid.model.serviceInstantiation.InstanceGroup; +import org.onap.vid.mso.model.InstanceGroupInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class InstanceGroupInstantiationCommand extends ResourceInstantiationCommand { + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Override + protected String getRequestPath() { + return asyncInstantiationBL.getInstanceGroupInstantiationPath(); + } + + @Override + protected RequestDetailsWrapper generateMSORequest(JobAdapter.AsyncJobRequest request, String userId) { + return asyncInstantiationBL.generateInstanceGroupInstantiationRequest( + (InstanceGroup) getSharedData().getRequest(), + commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID), + getSharedData().getUserId() + ); + } + + @Override + protected String getJobAuditMSOStatus() { + return "INSTANCE_GROUP_REQUESTED"; + } + + @Override + protected boolean shouldInstantiateMyself() { + return Action.Create == ((InstanceGroup) getSharedData().getRequest()).getAction(); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java b/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java index 1e613c58..5661663b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/JobCommandFactory.java @@ -34,7 +34,7 @@ public class JobCommandFactory { public JobCommand toCommand(Job job) { final JobCommand command = jobFactory.apply(job.getType().getCommandClass()); - command.init(job.getUuid(), job.getData()); + command.init(job.getSharedData(), job.getData()); return command; } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceInstantiationCommand.java new file mode 100644 index 00000000..e03f9b8d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/MacroServiceInstantiationCommand.java @@ -0,0 +1,26 @@ +package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.JobCommand; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class MacroServiceInstantiationCommand extends ServiceInstantiationCommand implements JobCommand { + + public MacroServiceInstantiationCommand() { + // empty constructor + } + + @Override + protected RequestDetailsWrapper generateServiceInstantiationRequest() { + return asyncInstantiationBL.generateMacroServiceInstantiationRequest( + getSharedData().getJobUuid(), getRequest(), optimisticUniqueServiceInstanceName, getSharedData().getUserId() + ); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResult.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResult.kt new file mode 100644 index 00000000..95f520f8 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResult.kt @@ -0,0 +1,9 @@ +package org.onap.vid.job.command + +import org.onap.vid.job.Job + +data class MsoResourceIds (val requestId:String, val instanceId:String) + +val EMPTY_MSO_RESOURCE_ID = MsoResourceIds("","") + +data class MsoResult @JvmOverloads constructor(val jobStatus: Job.JobStatus, val msoResourceIds: MsoResourceIds = EMPTY_MSO_RESOURCE_ID) diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt new file mode 100644 index 00000000..9760f667 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/MsoResultHandlerService.kt @@ -0,0 +1,66 @@ +package org.onap.vid.job.command + +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate +import org.onap.vid.job.Job +import org.onap.vid.job.impl.JobSharedData +import org.onap.vid.model.RequestReferencesContainer +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation +import org.onap.vid.mso.RestObject +import org.onap.vid.services.AsyncInstantiationBusinessLogic +import org.onap.vid.services.AuditService +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service +import java.util.* + +@Service +class MsoResultHandlerService +@Autowired constructor(private val asyncInstantiationBL: AsyncInstantiationBusinessLogic, private val auditService: AuditService) { + + companion object { + private val LOGGER = EELFLoggerDelegate.getLogger(MsoResultHandlerService::class.java) + } + + fun getRequest(jobSharedData: JobSharedData): ServiceInstantiation { + return jobSharedData.request as ServiceInstantiation + } + + fun handleRootResponse(jobUUID: UUID, msoResponse: RestObject): MsoResult { + return if (msoResponse.statusCode in 200..399) { + val jobStatus = Job.JobStatus.IN_PROGRESS + val msoResourceIds = MsoResourceIds(msoResponse.get().requestReferences.requestId, msoResponse.get().requestReferences.instanceId) + asyncInstantiationBL.auditVidStatus(jobUUID, jobStatus) + setInitialRequestAuditStatusFromMso(jobUUID, msoResourceIds.requestId) + asyncInstantiationBL.updateServiceInfo(jobUUID) { x -> + x.jobStatus = jobStatus + x.serviceInstanceId = msoResourceIds.instanceId + x.msoRequestId = UUID.fromString(msoResourceIds.requestId) + } + MsoResult(jobStatus, msoResourceIds) + } else { + auditService.setFailedAuditStatusFromMso(jobUUID, null, msoResponse.statusCode, msoResponse.raw) + handleRootCommandFailed(jobUUID) + } + } + + fun handleResponse(msoResponse: RestObject, actionDescription: String): MsoResult { + return if (msoResponse.statusCode in 200..399) { + val msoResourceIds = MsoResourceIds(msoResponse.get().requestReferences.requestId, msoResponse.get().requestReferences.instanceId) + LOGGER.debug("Successfully sent $actionDescription. Request id: ${msoResourceIds.requestId}") + MsoResult(Job.JobStatus.COMPLETED_WITH_NO_ACTION, msoResourceIds) + } else { + LOGGER.debug("Failed to $actionDescription. Details: ${msoResponse.raw}") + MsoResult(Job.JobStatus.FAILED) + } + } + + + fun handleRootCommandFailed(jobUUID: UUID): MsoResult { + asyncInstantiationBL.handleFailedInstantiation(jobUUID) + return MsoResult(Job.JobStatus.FAILED) + } + + private fun setInitialRequestAuditStatusFromMso(jobUUID: UUID, requestId: String) { + val initialMsoRequestStatus = "REQUESTED" + asyncInstantiationBL.auditMsoStatus(jobUUID, initialMsoRequestStatus, requestId, null) + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/NetworkInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/NetworkInstantiationCommand.java new file mode 100644 index 00000000..401bab72 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/NetworkInstantiationCommand.java @@ -0,0 +1,41 @@ +package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.model.serviceInstantiation.Network; +import org.onap.vid.mso.model.NetworkInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class NetworkInstantiationCommand extends ResourceInstantiationCommand { + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Override + protected String getRequestPath() { + return asyncInstantiationBL.getNetworkInstantiationPath(commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID)); + } + + @Override + protected RequestDetailsWrapper generateMSORequest(JobAdapter.AsyncJobRequest request, String userId) { + return asyncInstantiationBL.generateNetworkInstantiationRequest( + (Network) getSharedData().getRequest(), + commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID), + getSharedData().getUserId() + ); + } + + @Override + protected String getJobAuditMSOStatus() { + return "NETWORK_REQUESTED"; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt new file mode 100644 index 00000000..6dfcbdf3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceCommand.kt @@ -0,0 +1,324 @@ +package org.onap.vid.job.command + +import com.fasterxml.jackson.module.kotlin.convertValue +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate +import org.onap.vid.changeManagement.RequestDetailsWrapper +import org.onap.vid.job.Job +import org.onap.vid.job.Job.JobStatus +import org.onap.vid.job.JobAdapter +import org.onap.vid.job.JobCommand +import org.onap.vid.job.NextCommand +import org.onap.vid.job.impl.JobSharedData +import org.onap.vid.model.Action +import org.onap.vid.model.RequestReferencesContainer +import org.onap.vid.model.serviceInstantiation.BaseResource +import org.onap.vid.mso.RestMsoImplementation +import org.onap.vid.utils.JACKSON_OBJECT_MAPPER +import org.onap.vid.utils.getEnumFromMapOfStrings +import org.springframework.http.HttpMethod +import java.util.* + +const val INTERNAL_STATE = "internalState" +const val ACTION_PHASE = "actionPhase" +const val CHILD_JOBS = "childJobs" +const val MSO_RESOURCE_ID = "msoResourceIds" +const val CUMULATIVE_STATUS = "cumulativeStatus" + +enum class InternalState constructor(val immediate:Boolean=false) { + INITIAL, + CREATING_CHILDREN(true), + WATCHING, + DELETE_MYSELF, + CREATE_MYSELF, + IN_PROGRESS, + TERMINAL +} + +data class NextInternalState(val nextActionPhase: Action, val nextInternalState: InternalState) + + +data class MsoRestCallPlan( + val httpMethod: HttpMethod, + val path: String, + val payload: Optional>, + val userId: Optional, + val actionDescription: String +) + +abstract class ResourceCommand( + protected val restMso: RestMsoImplementation, + protected val inProgressStatusService: InProgressStatusService, + protected val msoResultHandlerService: MsoResultHandlerService, + protected val watchChildrenJobsBL: WatchChildrenJobsBL +) : CommandBase(), JobCommand { + + companion object { + private val Logger = EELFLoggerDelegate.getLogger(ResourceCommand::class.java) + } + + abstract fun createChildren():JobStatus + + abstract fun planCreateMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan + + abstract fun planDeleteMyselfRestCall(commandParentData: CommandParentData, request: JobAdapter.AsyncJobRequest, userId: String): MsoRestCallPlan + + private val commandByInternalState: Map JobStatus> = hashMapOf( + Pair(InternalState.CREATING_CHILDREN, ::createChildren), + Pair(InternalState.WATCHING, ::watchChildren), + Pair(InternalState.CREATE_MYSELF, ::createMyself), + Pair(InternalState.DELETE_MYSELF, ::deleteMyself), + Pair(InternalState.IN_PROGRESS, ::inProgress) + ) + + private lateinit var internalState:InternalState + protected lateinit var actionPhase: Action + private var commandParentData: CommandParentData = CommandParentData() + private var msoResourceIds: MsoResourceIds = EMPTY_MSO_RESOURCE_ID + protected var childJobs:List = emptyList() + private lateinit var cumulativeStatus:JobStatus + + + override fun call(): NextCommand { + var jobStatus:JobStatus = invokeCommand() + jobStatus = comulateStatusAndUpdatePropertyIfFinal(jobStatus) + + Logger.debug("command for job ${sharedData.jobUuid} invoked and finished with jobStatus $jobStatus") + if (shallStopJob(jobStatus)) { + onFinal(jobStatus) + return NextCommand(jobStatus) + } + + val (nextActionPhase, nextInternalState) = calcNextInternalState(jobStatus, internalState, actionPhase) + Logger.debug("next state for job ${sharedData.jobUuid} is $nextInternalState") + actionPhase = nextActionPhase + internalState = nextInternalState + + if (internalState==InternalState.TERMINAL) { + onFinal(jobStatus) + return NextCommand(jobStatus) + } + + jobStatus = getExternalInProgressStatus() + Logger.debug("next status for job ${sharedData.jobUuid} is $jobStatus") +// if (internalState.immediate) return call() //shortcut instead of execute another command + return NextCommand(jobStatus, this) + } + + //we want to stop in faliures, except for service witn no action, since service with no action trigger 2 phases (delete and create) + protected fun shallStopJob(jobStatus: JobStatus) = + jobStatus.isFailure && !(isServiceCommand() && getActionType()==Action.None) + + //this method is used to expose the job status after successful completion of current state + //should be override by subclass (like ServiceCommand) that need to return other default job status + protected open fun getExternalInProgressStatus() = JobStatus.RESOURCE_IN_PROGRESS + + private fun invokeCommand(): JobStatus { + return commandByInternalState.getOrDefault (internalState, ::throwIllegalState).invoke() + } + + private fun throwIllegalState():JobStatus { + throw IllegalStateException("can't find action for pashe $actionPhase and state $internalState") + } + + private fun calcNextInternalState(jobStatus: JobStatus, internalState: InternalState, actionPhase: Action): NextInternalState { + + val nextInternalState = when (actionPhase) { + Action.Delete -> calcNextStateDeletePhase(jobStatus, internalState) + Action.Create -> calcNextStateCreatePhase(jobStatus, internalState) + else -> InternalState.TERMINAL + } + + if (nextInternalState == InternalState.TERMINAL + && actionPhase == Action.Delete + && isServiceCommand()) { + // Loop over to "Create" phase + return NextInternalState(Action.Create, InternalState.INITIAL) + } + + return NextInternalState(actionPhase, nextInternalState) + + } + + //no need to refer to failed (final) states here + //This method is called only for non final states or COMPLETED + protected fun calcNextStateDeletePhase(jobStatus: JobStatus, internalState: InternalState): InternalState { + return when (internalState) { + + InternalState.CREATING_CHILDREN -> InternalState.WATCHING + + InternalState.WATCHING -> { + when { + !jobStatus.isFinal -> InternalState.WATCHING + isNeedToDeleteMyself() -> InternalState.DELETE_MYSELF + else -> InternalState.TERMINAL + } + } + + InternalState.DELETE_MYSELF -> InternalState.IN_PROGRESS + + InternalState.IN_PROGRESS -> { + if (jobStatus == Job.JobStatus.COMPLETED) InternalState.TERMINAL else InternalState.IN_PROGRESS + } + + else -> InternalState.TERMINAL + } + } + + protected fun calcNextStateCreatePhase(jobStatus: JobStatus, internalState: InternalState): InternalState { + return when (internalState) { + + InternalState.CREATE_MYSELF -> InternalState.IN_PROGRESS + + InternalState.IN_PROGRESS -> { + if (jobStatus == Job.JobStatus.COMPLETED) InternalState.CREATING_CHILDREN else InternalState.IN_PROGRESS + } + + InternalState.CREATING_CHILDREN -> InternalState.WATCHING + + InternalState.WATCHING -> { + when { + !jobStatus.isFinal -> InternalState.WATCHING + else -> InternalState.TERMINAL + } + } + + + else -> InternalState.TERMINAL + } + } + + override fun getData(): Map { + return mapOf( + ACTION_PHASE to actionPhase, + INTERNAL_STATE to internalState, + MSO_RESOURCE_ID to msoResourceIds, + CHILD_JOBS to childJobs, + CUMULATIVE_STATUS to cumulativeStatus + ) + } + + override fun init(sharedData: JobSharedData, commandData: Map): ResourceCommand { + init(sharedData) + val resourceIdsRaw:Any? = commandData[MSO_RESOURCE_ID] + commandParentData.initParentData(commandData) + msoResourceIds = + if (resourceIdsRaw != null) JACKSON_OBJECT_MAPPER.convertValue(resourceIdsRaw) + else EMPTY_MSO_RESOURCE_ID + + childJobs = JACKSON_OBJECT_MAPPER.convertValue(commandData.getOrDefault(CHILD_JOBS, emptyList())) + cumulativeStatus = getEnumFromMapOfStrings(commandData, CUMULATIVE_STATUS, JobStatus.COMPLETED_WITH_NO_ACTION) + actionPhase = getEnumFromMapOfStrings(commandData, ACTION_PHASE, Action.Delete) + internalState = calcInitialState(commandData, actionPhase) + return this + } + + private fun calcInitialState(commandData: Map, phase: Action):InternalState { + val status:InternalState = getEnumFromMapOfStrings(commandData, INTERNAL_STATE, InternalState.INITIAL) + if (status == InternalState.INITIAL) { + onInitial(phase) + return when (phase) { + Action.Delete -> InternalState.CREATING_CHILDREN + Action.Create -> if (isNeedToCreateMyself()) InternalState.CREATE_MYSELF else InternalState.CREATING_CHILDREN + else -> throw IllegalStateException("state $internalState is not supported yet") + } + } + return status + } + + //command may override it in order to do something while init state + protected open fun onInitial(phase: Action) { + //do nothing + } + + //command may override it in order to do something while final status + protected open fun onFinal(jobStatus: JobStatus) { + //do nothing + } + + protected open fun getRequest(): BaseResource { + return sharedData.request as BaseResource + } + + protected open fun getActionType(): Action { + return getRequest().action + } + + protected open fun isServiceCommand(): Boolean = false + + protected open fun isNeedToDeleteMyself(): Boolean = getActionType() == Action.Delete + + protected open fun isNeedToCreateMyself(): Boolean = getActionType() == Action.Create + + protected open fun inProgress(): Job.JobStatus { + val requestId:String = msoResourceIds.requestId; + return try { + val jobStatus = inProgressStatusService.call(getExpiryChecker(), sharedData, requestId) + handleInProgressStatus(jobStatus) + } catch (e: javax.ws.rs.ProcessingException) { + // Retry when we can't connect MSO during getStatus + Logger.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, will retry: {}", requestId, e, e) + Job.JobStatus.IN_PROGRESS; + } catch (e: InProgressStatusService.BadResponseFromMso) { + inProgressStatusService.handleFailedMsoResponse(sharedData.jobUuid, requestId, e.msoResponse) + Job.JobStatus.IN_PROGRESS + } catch (e: RuntimeException) { + Logger.error(EELFLoggerDelegate.errorLogger, "Cannot get orchestration status for {}, stopping: {}", requestId, e, e) + Job.JobStatus.STOPPED + } + } + + fun createMyself(): Job.JobStatus { + val createMyselfCommand = planCreateMyselfRestCall(commandParentData, sharedData.request, sharedData.userId) + + return executeAndHandleMsoInstanceRequest(createMyselfCommand) + } + + fun deleteMyself(): Job.JobStatus { + val deleteMyselfCommand = planDeleteMyselfRestCall(commandParentData, sharedData.request, sharedData.userId) + + return executeAndHandleMsoInstanceRequest(deleteMyselfCommand) + } + + private fun executeAndHandleMsoInstanceRequest(restCallPlan: MsoRestCallPlan): JobStatus { + val msoResponse = restMso.restCall( + restCallPlan.httpMethod, + RequestReferencesContainer::class.java, + restCallPlan.payload.orElse(null), + restCallPlan.path, + restCallPlan.userId + ) + + val msoResult = if (isServiceCommand()) { + msoResultHandlerService.handleRootResponse(sharedData.jobUuid, msoResponse) + } else { + msoResultHandlerService.handleResponse(msoResponse, restCallPlan.actionDescription) + } + + this.msoResourceIds = msoResult.msoResourceIds + return msoResult.jobStatus + } + + protected open fun getExpiryChecker(): ExpiryChecker = ExpiryChecker {false} + + protected open fun handleInProgressStatus(jobStatus: JobStatus): JobStatus { + return if (jobStatus == Job.JobStatus.PAUSE) Job.JobStatus.IN_PROGRESS else jobStatus + } + + protected open fun watchChildren():JobStatus { + return watchChildrenJobsBL.retrieveChildrenJobsStatus(childJobs) + } + + private fun comulateStatusAndUpdatePropertyIfFinal(internalStateStatus: JobStatus): JobStatus { + val status = watchChildrenJobsBL.cumulateJobStatus(internalStateStatus, cumulativeStatus) + + //we want to update cumulativeStatus only for final status + if (status.isFinal) { + cumulativeStatus = status; + } + + return status + } +} + + + diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInProgressStatusCommand.java new file mode 100644 index 00000000..9ab600aa --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInProgressStatusCommand.java @@ -0,0 +1,32 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ResourceInProgressStatusCommand extends BaseInProgressStatusCommand { + + public ResourceInProgressStatusCommand() { + } + + ResourceInProgressStatusCommand(JobSharedData sharedData, String requestId, String instanceId) { + init(sharedData, requestId, instanceId); + } + + @Override + protected ExpiryChecker getExpiryChecker() { + return x->false; + } + + @Override + protected NextCommand processJobStatus(Job.JobStatus jobStatus) { + return new NextCommand(jobStatus, this); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInstantiationCommand.java new file mode 100644 index 00000000..c86c6f1b --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceInstantiationCommand.java @@ -0,0 +1,87 @@ +package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.model.BaseResourceInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.Map; + + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public abstract class ResourceInstantiationCommand extends BaseInstantiationCommand implements JobCommand { + + + @Inject + protected RestMsoImplementation restMso; + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + private AuditService auditService; + + @Override + public ResourceInstantiationCommand init(JobSharedData sharedData, Map commandData) { + super.init(sharedData, commandData); + return this; + } + + @Override + public Map getData() { + return commandParentData.getParentData(); + } + + @Override + public NextCommand call() { + if (!shouldInstantiateMyself()) { + return new NextCommand(Job.JobStatus.COMPLETED_WITH_NO_ACTION); + } + + RequestDetailsWrapper requestDetailsWrapper = generateMSORequest( + getSharedData().getRequest(), + getSharedData().getUserId() + ); + String instantiatePath = getRequestPath(); + + RestObject msoResponse = restMso.PostForObject(requestDetailsWrapper, + instantiatePath, RequestReferencesContainer.class); + + if (msoResponse.getStatusCode() >= 200 && msoResponse.getStatusCode() < 400) { + String requestId = msoResponse.get().getRequestReferences().getRequestId(); + String instanceId = msoResponse.get().getRequestReferences().getInstanceId(); + asyncInstantiationBL.auditMsoStatus(getSharedData().getRootJobId(), getJobAuditMSOStatus(), requestId, null); + return getNextCommand(requestId, instanceId); + } + else { + auditService.setFailedAuditStatusFromMso(getSharedData().getRootJobId(), null, msoResponse.getStatusCode(), msoResponse.getRaw()); + return new NextCommand(Job.JobStatus.FAILED); + } + } + protected NextCommand getNextCommand(String requestId, String instanceId){ + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, new ResourceInProgressStatusCommand(getSharedData(), requestId, instanceId)); + } + + protected boolean shouldInstantiateMyself() { + return true; + } + + protected abstract String getRequestPath(); + protected abstract RequestDetailsWrapper generateMSORequest(JobAdapter.AsyncJobRequest request, String userId); + protected abstract String getJobAuditMSOStatus(); +} + + diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceWithChildrenInProgressCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceWithChildrenInProgressCommand.java new file mode 100644 index 00000000..53164f43 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ResourceWithChildrenInProgressCommand.java @@ -0,0 +1,65 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; + +import java.util.HashMap; +import java.util.Map; + + +public class ResourceWithChildrenInProgressCommand extends BaseInProgressStatusCommand { + + public ResourceWithChildrenInProgressCommand() { + } + + public ResourceWithChildrenInProgressCommand(JobSharedData sharedData, + String requestId, + String instanceId, + CommandParentData commandParentData) { + init(sharedData, requestId, instanceId, commandParentData); + } + + protected BaseInProgressStatusCommand init(JobSharedData sharedData, + String requestId, + String instanceId, + CommandParentData commandParentData) { + init(sharedData, requestId, instanceId); + this.commandParentData= commandParentData; + return this; + } + + + @Override + public Map getData() { + Map data = new HashMap<>(super.getData()); + data.putAll(buildDataForChild()); + return data; + } + + @Override + public BaseInProgressStatusCommand init(JobSharedData sharedData, Map commandData) { + return init( + sharedData, + (String) commandData.get("requestId"), + (String) commandData.get("instanceId"), + commandParentData.initParentData(commandData)); + } + + protected Map buildDataForChild() { + return commandParentData.getParentData(); + } + + + + @Override + protected NextCommand processJobStatus(Job.JobStatus jobStatus) { + return new NextCommand(jobStatus, this); + } + + @Override + protected ExpiryChecker getExpiryChecker() { + return x->false; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInProgressStatusCommand.java new file mode 100644 index 00000000..ac8b5546 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInProgressStatusCommand.java @@ -0,0 +1,100 @@ +package org.onap.vid.job.command; + +import org.apache.commons.collections.MapUtils; +import org.onap.vid.job.Job; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.JobType; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.properties.Features; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class ServiceInProgressStatusCommand extends BaseInProgressStatusCommand { + + public ServiceInProgressStatusCommand() { + } + + ServiceInProgressStatusCommand(JobSharedData sharedData, MsoResourceIds msoResourceIds) { + init(sharedData, msoResourceIds.getRequestId(), msoResourceIds.getInstanceId()); + } + + @Override + protected ExpiryChecker getExpiryChecker() { + return new ServiceExpiryChecker(); + } + + protected NextCommand processJobStatus(Job.JobStatus jobStatus) { + JobCommand jobCommand = this; + Job.JobStatus nextJobStatus = jobStatus; + switch (jobStatus) { + case FAILED: + asyncInstantiationBL.handleFailedInstantiation(getSharedData().getJobUuid()); + return new NextCommand(nextJobStatus, jobCommand); + case PAUSE: + nextJobStatus = Job.JobStatus.IN_PROGRESS; + break; + case COMPLETED: + ServiceInstantiation request = (ServiceInstantiation) getSharedData().getRequest(); + if (isNeedToCreateChildJobs(request)) { + List childrenJobs = getChildJobs(request); + nextJobStatus = Job.JobStatus.IN_PROGRESS; + jobCommand = new WatchingCommand(getSharedData(), childrenJobs, true); + return new NextCommand(nextJobStatus, jobCommand); + } + break; + default: // for sonar + } + asyncInstantiationBL.updateServiceInfoAndAuditStatus(getSharedData().getJobUuid(), jobStatus); + return new NextCommand(nextJobStatus, jobCommand); + } + + private List getChildJobs(ServiceInstantiation request) { + Map dataForChild = buildDataForChild(request); + + Stream vnfJobs = request.getVnfs().values().stream().map( + vnf -> jobsBrokerService.add( + jobAdapter.createChildJob(JobType.VnfInstantiation, JobStatus.CREATING , vnf, getSharedData(), dataForChild)).toString() + ); + + Stream networkJobs = request.getNetworks().values().stream().map( + network -> jobsBrokerService.add( + jobAdapter.createChildJob(JobType.NetworkInstantiation, JobStatus.CREATING , network, getSharedData(), dataForChild)).toString() + ); + + Stream instanceGroupJobs = request.getVnfGroups().values().stream().map( + instanceGroup -> jobsBrokerService.add( + jobAdapter.createChildJob(JobType.InstanceGroupInstantiation, JobStatus.CREATING , instanceGroup, getSharedData(), dataForChild)).toString() + ); + + return Stream.of(vnfJobs, networkJobs, instanceGroupJobs) + .reduce(Stream::concat) + .orElseGet(Stream::empty) + .collect(Collectors.toList()); + } + + public boolean isNeedToCreateChildJobs(ServiceInstantiation request) { + return featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF) && request.isALaCarte() && + ( + MapUtils.isNotEmpty(request.getVnfs()) || MapUtils.isNotEmpty(request.getNetworks()) || + (featureManager.isActive(Features.FLAG_1902_VNF_GROUPING) && MapUtils.isNotEmpty(request.getVnfGroups())) + ); + } + + protected Map buildDataForChild(ServiceInstantiation request) { + commandParentData.addInstanceId(CommandDataKey.SERVICE_INSTANCE_ID, this.instanceId); + commandParentData.addModelInfo(CommandDataKey.SERVICE_MODEL_INFO, request.getModelInfo()); + return commandParentData.getParentData(); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java index 958fc115..b40b7015 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java @@ -1,170 +1,106 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.job.command; -import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; -import io.joshworks.restclient.http.HttpResponse; -import org.onap.vid.aai.exceptions.InvalidAAIResponseException; +import org.apache.commons.lang3.ObjectUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.exceptions.MaxRetriesException; import org.onap.vid.job.Job; import org.onap.vid.job.JobCommand; import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.services.AuditService; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.Map; -import java.util.Objects; -import java.util.UUID; -@Component -@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) -public class ServiceInstantiationCommand implements JobCommand { - - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); +public abstract class ServiceInstantiationCommand extends BaseRootCommand implements JobCommand { private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(ServiceInstantiationCommand.class); @Inject - private AsyncInstantiationBusinessLogic asyncInstantiationBL; - - @Inject - private AuditService auditService; + protected AsyncInstantiationBusinessLogic asyncInstantiationBL; @Inject - private MsoInterface restMso; + private RestMsoImplementation restMso; - private UUID uuid; - private ServiceInstantiation serviceInstantiationRequest; - private String userId; + protected String optimisticUniqueServiceInstanceName; public ServiceInstantiationCommand() { } - public ServiceInstantiationCommand(UUID uuid, ServiceInstantiation serviceInstantiationRequest, String userId) { - init(uuid, serviceInstantiationRequest, userId); - } - - ServiceInstantiationCommand(AsyncInstantiationBusinessLogic asyncInstantiationBL, AuditService auditService, MsoInterface msoInterface, - UUID uuid, ServiceInstantiation serviceInstantiation, String userId) { - this(uuid, serviceInstantiation, userId); - this.asyncInstantiationBL = asyncInstantiationBL; - this.auditService = auditService; - this.restMso = msoInterface; - } - @Override public NextCommand call() { RequestDetailsWrapper requestDetailsWrapper ; try { - requestDetailsWrapper = asyncInstantiationBL.generateServiceInstantiationRequest( - uuid, serviceInstantiationRequest, userId - ); + requestDetailsWrapper = generateServiceInstantiationRequest(); } + //Aai return bad response while checking names uniqueness - catch (InvalidAAIResponseException exception) { - LOGGER.error("Failed to check name uniqueness in AAI. VID will try again later", exception); - //put the job in_progress so we will keep trying to check name uniqueness in AAI - //And then send the request to MSO - return new NextCommand(Job.JobStatus.IN_PROGRESS, this); + catch (ExceptionWithRequestInfo exception) { + return handleAaiNameUniquenessBadResponse(exception); } //Vid reached to max retries while trying to find unique name in AAI catch (MaxRetriesException exception) { - LOGGER.error("Failed to find unused name in AAI. Set the job to FAILED ", exception); - return handleCommandFailed(); + return handleMaxRetryInNameUniqueness(exception); } - String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationRequest); + String path = asyncInstantiationBL.getServiceInstantiationPath(getRequest()); - HttpResponse msoResponse = restMso.post(path, - requestDetailsWrapper, RequestReferencesContainer.class); + RestObject msoResponse = restMso.PostForObject(requestDetailsWrapper, + path, RequestReferencesContainer.class); + return handleRootResponse(msoResponse); - if (msoResponse.getStatus() >= 200 && msoResponse.getStatus() < 400) { - final Job.JobStatus jobStatus = Job.JobStatus.IN_PROGRESS; - final String requestId = msoResponse.getBody().getRequestReferences().getRequestId(); - final String instanceId = msoResponse.getBody().getRequestReferences().getInstanceId(); - asyncInstantiationBL.auditVidStatus(uuid, jobStatus); - setInitialRequestAuditStatusFromMso(requestId); - asyncInstantiationBL.updateServiceInfo(uuid, x-> { - x.setJobStatus(jobStatus); - x.setServiceInstanceId(instanceId); - }); - - return new NextCommand(jobStatus, new InProgressStatusCommand(uuid, requestId)); - } else { - auditService.setFailedAuditStatusFromMso(uuid,null, msoResponse.getStatus(), - Objects.toString(msoResponse.getBody())); - return handleCommandFailed(); - } + } + @Override + protected ServiceInstantiation getRequest() { + return (ServiceInstantiation) getSharedData().getRequest(); } - private void setInitialRequestAuditStatusFromMso(String requestId){ - final String initialMsoRequestStatus = "REQUESTED"; - asyncInstantiationBL.auditMsoStatus(uuid,initialMsoRequestStatus,requestId,null); + protected abstract RequestDetailsWrapper generateServiceInstantiationRequest(); + + private NextCommand handleMaxRetryInNameUniqueness(MaxRetriesException exception) { + LOGGER.error("Failed to find unused name in AAI. Set the job to FAILED ", exception); + return handleCommandFailed(); } - protected NextCommand handleCommandFailed() { - asyncInstantiationBL.handleFailedInstantiation(uuid); - return new NextCommand(Job.JobStatus.FAILED); + private NextCommand handleAaiNameUniquenessBadResponse(ExceptionWithRequestInfo exception) { + LOGGER.error("Failed to check name uniqueness in AAI. VID will try again later", exception); + //put the job in_progress so we will keep trying to check name uniqueness in AAI + //And then send the request to MSO + return new NextCommand(Job.JobStatus.IN_PROGRESS, this); } @Override - public ServiceInstantiationCommand init(UUID jobUuid, Map data) { - final Object request = data.get("request"); + public ServiceInstantiationCommand init(JobSharedData sharedData, Map commandData) { return init( - jobUuid, - OBJECT_MAPPER.convertValue(request, ServiceInstantiation.class), - (String) data.get("userId") + sharedData, + (String) commandData.get("optimisticUniqueServiceInstanceName") ); } - private ServiceInstantiationCommand init(UUID jobUuid, ServiceInstantiation serviceInstantiationRequest, String userId) { - this.uuid = jobUuid; - this.serviceInstantiationRequest = serviceInstantiationRequest; - this.userId = userId; - + protected ServiceInstantiationCommand init(JobSharedData sharedData, String optimisticUniqueServiceInstanceName) { + init(sharedData); + this.optimisticUniqueServiceInstanceName = ObjectUtils.defaultIfNull(optimisticUniqueServiceInstanceName, + (getRequest()).getInstanceName()); return this; } @Override public Map getData() { return ImmutableMap.of( - "uuid", uuid, - "request", serviceInstantiationRequest, - "userId", userId + "optimisticUniqueServiceInstanceName", optimisticUniqueServiceInstanceName ); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleInstantiationCommand.java new file mode 100644 index 00000000..a3f827e2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VfmoduleInstantiationCommand.java @@ -0,0 +1,44 @@ +package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class VfmoduleInstantiationCommand extends ResourceInstantiationCommand { + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Override + protected String getRequestPath() { + return asyncInstantiationBL.getVfmoduleInstantiationPath(commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID),commandParentData.getInstanceId(CommandDataKey.VNF_INSTANCE_ID)); + } + + @Override + protected RequestDetailsWrapper generateMSORequest(JobAdapter.AsyncJobRequest request, String userId) { + return asyncInstantiationBL.generateVfModuleInstantiationRequest( + (VfModule) getSharedData().getRequest(), + commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID), + commandParentData.getModelInfo(CommandDataKey.VNF_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.VNF_INSTANCE_ID), + commandParentData.getInstanceId(CommandDataKey.VG_INSTANCE_ID), + getSharedData().getUserId() + ); + } + + @Override + protected String getJobAuditMSOStatus() { + return "VF_MODULE_REQUESTED"; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VnfInProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/VnfInProgressStatusCommand.java new file mode 100644 index 00000000..a6a41b1a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VnfInProgressStatusCommand.java @@ -0,0 +1,87 @@ +package org.onap.vid.job.command; + +import org.apache.commons.collections.MapUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobType; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.properties.Features; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class VnfInProgressStatusCommand extends ResourceWithChildrenInProgressCommand { + private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VnfInProgressStatusCommand.class); + + public VnfInProgressStatusCommand(JobSharedData sharedData, + String requestId, + String instanceId, + CommandParentData commandParentData) { + super(sharedData, requestId, instanceId, commandParentData); + } + + public VnfInProgressStatusCommand() { + } + + @Override + protected NextCommand processJobStatus(Job.JobStatus jobStatus) { + if (jobStatus == Job.JobStatus.FAILED) { + return new NextCommand(jobStatus); + } + + Vnf request = (Vnf) getSharedData().getRequest(); + + if (isNeedToCreateChildJobs(jobStatus, request)) { + commandParentData.addInstanceId(CommandDataKey.VNF_INSTANCE_ID, instanceId); + commandParentData.addModelInfo(CommandDataKey.VNF_MODEL_INFO, request.getModelInfo()); + //create volume group of base module job + Map dataForChild = buildDataForChild(); + List vfModules = request.getVfModules().values().stream().flatMap(vfKey -> vfKey.values().stream()).collect(Collectors.toList()); + List vgBaseJobs = new ArrayList<>(); + for( VfModule vfModule : vfModules){ + try { + if(commandUtils.isVfModuleBaseModule(commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO).getModelVersionId(), vfModule.getModelInfo().getModelVersionId())) { + vgBaseJobs.add(jobsBrokerService.add( + jobAdapter.createChildJob(JobType.VolumeGroupInstantiation, Job.JobStatus.CREATING, vfModule, getSharedData(), dataForChild)).toString()); + } + } catch (AsdcCatalogException e) { + LOG.error("Failed to retrieve service definitions from SDC, for VfModule is BaseModule. Error: "+e.getMessage() , e); + return new NextCommand(Job.JobStatus.COMPLETED_WITH_ERRORS); + } + } + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, new WatchingCommandBaseModule(getSharedData(), vgBaseJobs, false, commandParentData)); + } + + //in case of JobStatus.PAUSE we leave the job itself as IN_PROGRESS, for keep tracking job progress + if (jobStatus == Job.JobStatus.PAUSE) { + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, this); + } + return new NextCommand(jobStatus, this); + } + + + protected boolean isNeedToCreateChildJobs(Job.JobStatus jobStatus, BaseResource request) { + return featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE) && + jobStatus == Job.JobStatus.COMPLETED && + MapUtils.isNotEmpty(((Vnf)request).getVfModules()); + } + + + @Override + protected ExpiryChecker getExpiryChecker() { + return x->false; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VnfInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/VnfInstantiationCommand.java new file mode 100644 index 00000000..8853cdc1 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VnfInstantiationCommand.java @@ -0,0 +1,50 @@ +package org.onap.vid.job.command; + +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.mso.model.VnfInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class VnfInstantiationCommand extends ResourceInstantiationCommand { + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Override + protected String getRequestPath() { + return asyncInstantiationBL.getVnfInstantiationPath( commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID)); + } + + @Override + protected RequestDetailsWrapper generateMSORequest(JobAdapter.AsyncJobRequest request, String userId) { + return asyncInstantiationBL.generateVnfInstantiationRequest( + (Vnf) getSharedData().getRequest(), + commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID), + getSharedData().getUserId() + ); + } + + @Override + protected String getJobAuditMSOStatus() { + return "VNF_REQUESTED"; + } + + @Override + protected NextCommand getNextCommand(String requestId, String instanceId) { + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, + new VnfInProgressStatusCommand(getSharedData(), requestId, instanceId, commandParentData)); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInProgressStatusCommand.java new file mode 100644 index 00000000..663696b3 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInProgressStatusCommand.java @@ -0,0 +1,65 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.Job; +import org.onap.vid.job.JobType; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class VolumeGroupInProgressStatusCommand extends ResourceWithChildrenInProgressCommand { + + public VolumeGroupInProgressStatusCommand( + JobSharedData sharedData, + String requestId, + String instanceId, + CommandParentData parentData) { + super(sharedData, requestId, instanceId, parentData); + } + + public VolumeGroupInProgressStatusCommand() { + } + + @Override + protected NextCommand processJobStatus(Job.JobStatus jobStatus) { + if (jobStatus == Job.JobStatus.FAILED) { + return new NextCommand(Job.JobStatus.FAILED); + } + VfModule request = (VfModule) getSharedData().getRequest(); + + if (jobStatus == Job.JobStatus.COMPLETED) { + //vf module creation + Map dataForChild = buildDataForChild(); + List vfModuleJob = Arrays.asList(jobsBrokerService.add( + jobAdapter.createChildJob(JobType.VfmoduleInstantiation, Job.JobStatus.CREATING , request, getSharedData(), dataForChild)).toString()); + + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, new WatchingCommand(getSharedData(), vfModuleJob, false)); + } + + //in case of JobStatus.PAUSE we leave the job itself as IN_PROGRESS, for keep tracking job progress + if (jobStatus == Job.JobStatus.PAUSE) { + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, this); + } + return new NextCommand(jobStatus, this); + } + + @Override + protected Map buildDataForChild() { + commandParentData.addInstanceId(CommandDataKey.VG_INSTANCE_ID, this.instanceId); + return super.buildDataForChild(); + } + + @Override + protected ExpiryChecker getExpiryChecker() { + return x->false; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInstantiationCommand.java new file mode 100644 index 00000000..b2a3da47 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/VolumeGroupInstantiationCommand.java @@ -0,0 +1,83 @@ +package org.onap.vid.job.command; + + +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.job.*; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.mso.model.VolumeGroupRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class VolumeGroupInstantiationCommand extends ResourceInstantiationCommand { + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + protected JobsBrokerService jobsBrokerService; + + @Inject + protected JobAdapter jobAdapter; + + @Override + protected String getRequestPath() { + return asyncInstantiationBL.getVolumeGroupInstantiationPath(commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID),commandParentData.getInstanceId(CommandDataKey.VNF_INSTANCE_ID)); + } + + @Override + protected RequestDetailsWrapper generateMSORequest(JobAdapter.AsyncJobRequest request, String userId) { + return asyncInstantiationBL.generateVolumeGroupInstantiationRequest( + (VfModule) getSharedData().getRequest(), + commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.SERVICE_INSTANCE_ID), + commandParentData.getModelInfo(CommandDataKey.VNF_MODEL_INFO), + commandParentData.getInstanceId(CommandDataKey.VNF_INSTANCE_ID), + getSharedData().getUserId() + ); + } + + @Override + protected NextCommand getNextCommand(String requestId, String instanceId){ + return new NextCommand( + Job.JobStatus.RESOURCE_IN_PROGRESS, + new VolumeGroupInProgressStatusCommand(getSharedData(), requestId, instanceId, commandParentData) + ); + } + + @Override + protected String getJobAuditMSOStatus() { + return "VOLUME_GROUP_REQUESTED"; + } + + @Override + public NextCommand call() { + String vgName = ((VfModule)getSharedData().getRequest()).getVolumeGroupInstanceName(); + if(StringUtils.isNotEmpty(vgName)){ + return super.call();//create volume group + }else { + //go to vf module creation + VfModule request = (VfModule) getSharedData().getRequest(); + Map dataForChild = buildDataForChild(); + List vfModuleJob = Collections.singletonList(jobsBrokerService.add( + jobAdapter.createChildJob(JobType.VfmoduleInstantiation, Job.JobStatus.CREATING, request, getSharedData(), dataForChild)).toString()); + + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, new WatchingCommand(getSharedData(), vfModuleJob, false)); + } + + } + + private Map buildDataForChild() { + return commandParentData.getParentData(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/WatchChildrenJobsBL.kt b/vid-app-common/src/main/java/org/onap/vid/job/command/WatchChildrenJobsBL.kt new file mode 100644 index 00000000..b31e7f92 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/WatchChildrenJobsBL.kt @@ -0,0 +1,61 @@ +package org.onap.vid.job.command + +import org.apache.commons.lang3.StringUtils +import org.onap.portalsdk.core.service.DataAccessService +import org.onap.vid.job.Job +import org.onap.vid.job.Job.JobStatus.* +import org.onap.vid.job.impl.JobDaoImpl +import org.onap.vid.utils.DaoUtils +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.stereotype.Service +import java.util.* +import java.util.stream.Collectors +import java.util.stream.Stream + + +@Service +class WatchChildrenJobsBL @Autowired +constructor(private val dataAccessService: DataAccessService) { + + fun retrieveChildrenJobsStatus(childrenJobsIds: List): Job.JobStatus { + val jobs = getAllChildrenJobs(childrenJobsIds) + + val jobsStatuses = childrenJobsIds.stream() + .map { jobId -> jobs[UUID.fromString(jobId)] } + .map {when { + (it == null || it.status == null) -> Job.JobStatus.FAILED + else -> it.status + }} + + return cumulateJobStatus(jobsStatuses) + + } + + fun cumulateJobStatus(childrenComulatedStatus: Job.JobStatus, fatherJobStatus: Job.JobStatus): Job.JobStatus { + return cumulateJobStatus(Stream.of(childrenComulatedStatus, fatherJobStatus)) + } + + private fun cumulateJobStatus(jobsStatuses: Stream): Job.JobStatus { + + return jobsStatuses.reduce{ a, b -> + when { + !a.isFinal || !b.isFinal -> IN_PROGRESS + a == COMPLETED_WITH_ERRORS || b == COMPLETED_WITH_ERRORS-> COMPLETED_WITH_ERRORS + a == COMPLETED && b.isFailure -> COMPLETED_WITH_ERRORS + b == COMPLETED && a.isFailure -> COMPLETED_WITH_ERRORS + a == COMPLETED || b == COMPLETED -> COMPLETED + a.isFailure || b.isFailure -> FAILED + else -> COMPLETED_WITH_NO_ACTION + } + } .orElse(COMPLETED_WITH_NO_ACTION) + } + + private fun getAllChildrenJobs(childrenJobsIds: List): Map { + val jobs:MutableList = dataAccessService.getList(JobDaoImpl::class.java, filterByJobIds(childrenJobsIds), null, DaoUtils.getPropsMap()) as MutableList + return jobs.stream().collect(Collectors.toMap( { it.uuid }, { it })) + } + + private fun filterByJobIds(childrenJobsIds: List): String { + return " WHERE JOB_ID IN('" + StringUtils.join(childrenJobsIds, "', '") + "')" + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommand.java new file mode 100644 index 00000000..8659cfe1 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommand.java @@ -0,0 +1,33 @@ +package org.onap.vid.job.command; + +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class WatchingCommand extends BaseWatchingCommand { + + public WatchingCommand() {} + + public WatchingCommand(JobSharedData sharedData, List childrenJobsIds, boolean isService) { + super(sharedData, childrenJobsIds, isService); + } + + protected NextCommand getNextCommand(Job.JobStatus cumulativeJobsStatus) { + if (cumulativeJobsStatus==Job.JobStatus.IN_PROGRESS) { + return (isService) ? new NextCommand(Job.JobStatus.IN_PROGRESS, this) + : new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, this); + } + if (isService) { + asyncInstantiationBL.updateServiceInfoAndAuditStatus(getSharedData().getJobUuid(), cumulativeJobsStatus); + } + return new NextCommand(cumulativeJobsStatus); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommandBaseModule.java b/vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommandBaseModule.java new file mode 100644 index 00000000..8012aa9f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/WatchingCommandBaseModule.java @@ -0,0 +1,93 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.job.*; +import org.onap.vid.job.command.CommandParentData.CommandDataKey; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Component +@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) +public class WatchingCommandBaseModule extends BaseWatchingCommand { + @Inject + protected JobsBrokerService jobsBrokerService; + + @Inject + protected JobAdapter jobAdapter; + private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(WatchingCommandBaseModule.class); + + public WatchingCommandBaseModule( + JobSharedData sharedData, + List childrenJobsIds, + boolean isService, + CommandParentData commandParentData) { + super(sharedData, childrenJobsIds, isService); + this.commandParentData = commandParentData; + } + + public WatchingCommandBaseModule() { + + } + + @Override + protected NextCommand getNextCommand(Job.JobStatus cumulativeJobsStatus) { + + if (cumulativeJobsStatus== Job.JobStatus.IN_PROGRESS) { + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, this); + } + + if(cumulativeJobsStatus==Job.JobStatus.FAILED || cumulativeJobsStatus==Job.JobStatus.COMPLETED_WITH_ERRORS){ + return new NextCommand(Job.JobStatus.COMPLETED_WITH_ERRORS); + } + Vnf request = (Vnf) getSharedData().getRequest(); + Map dataForChild = buildDataForChild(); + //Create non-base Volume groups job + List vfModules = request.getVfModules().values().stream().flatMap(vfKey -> vfKey.values().stream()).collect(Collectors.toList()); + List vgNonBaseJobs = new ArrayList<>(); + for( VfModule vfModule : vfModules){ + try { + if(!commandUtils.isVfModuleBaseModule(commandParentData.getModelInfo(CommandDataKey.SERVICE_MODEL_INFO).getModelVersionId(), vfModule.getModelInfo().getModelVersionId())) { + vgNonBaseJobs.add(jobsBrokerService.add( + jobAdapter.createChildJob(JobType.VolumeGroupInstantiation, Job.JobStatus.CREATING, vfModule, getSharedData(), dataForChild)).toString()); + } + } catch (AsdcCatalogException e) { + LOG.error("Failed to retrieve service definitions from SDC, for VfModule is BaseModule. Error: "+e.getMessage() , e); + return new NextCommand(Job.JobStatus.COMPLETED_WITH_ERRORS); + } + } + return new NextCommand(Job.JobStatus.RESOURCE_IN_PROGRESS, new WatchingCommand(getSharedData(), vgNonBaseJobs, false)); + } + + @Override + public WatchingCommandBaseModule init(JobSharedData sharedData, Map commandData) { + super.init(sharedData, commandData); + commandParentData.initParentData(commandData); + return this; + } + + protected Map buildDataForChild() { + return commandParentData.getParentData(); + } + + @Override + public Map getData() { + return ImmutableMap.builder() + .putAll(super.getData()) + .putAll(commandParentData.getParentData()) + .build(); + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java index 59f12f4c..1050ab93 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobAdapterImpl.java @@ -4,16 +4,11 @@ import com.google.common.collect.ImmutableMap; import org.onap.vid.job.Job; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobType; -import org.onap.vid.model.JobBulk; import org.onap.vid.model.JobModel; import org.springframework.stereotype.Component; -import javax.ws.rs.BadRequestException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.stream.Collectors; @Component public class JobAdapterImpl implements JobAdapter { @@ -28,44 +23,32 @@ public class JobAdapterImpl implements JobAdapter { } @Override - public JobBulk toModelBulk(List jobList) { - return new JobBulk(jobList.stream().map(this::toModel).collect(Collectors.toList())); - } - - @Override - public Job createJob(JobType jobType, AsyncJobRequest request, UUID templateId, String userId, Integer indexInBulk) { - JobDaoImpl job = createJob(jobType, templateId, indexInBulk, ImmutableMap.of( - "request", request, - "userId", userId)); - job.setUserId(userId); + public Job createServiceInstantiationJob(JobType jobType, AsyncJobRequest request, UUID templateId, String userId, String optimisticUniqueServiceInstanceName, Integer indexInBulk){ + JobDaoImpl job = createJob(jobType, Job.JobStatus.PENDING , userId); + job.setSharedData(new JobSharedData(job.getUuid(), userId, request)); + job.setTypeAndData(jobType, ImmutableMap.of( + "optimisticUniqueServiceInstanceName", optimisticUniqueServiceInstanceName + )); + job.setTemplateId(templateId); + job.setIndexInBulk(indexInBulk); return job; } @Override - public List createBulkOfJobs(Map bulkRequest) { - int count; - JobType jobType; - - try { - count = (Integer) bulkRequest.get("count"); - jobType = JobType.valueOf((String) bulkRequest.get("type")); - } catch (Exception exception) { - throw new BadRequestException(exception); - } - List jobList = new ArrayList<>(count + 1); - UUID templateId = UUID.randomUUID(); - for (int i = 0; i < count; i++) { - jobList.add(createJob(jobType, templateId, i, bulkRequest)); - } - return jobList; + public Job createChildJob(JobType jobType, Job.JobStatus jobStatus, AsyncJobRequest request, JobSharedData parentSharedData, Map jobData) { + JobDaoImpl job = createJob(jobType, jobStatus , parentSharedData.getUserId()); + job.setSharedData(new JobSharedData(job.getUuid(), request, parentSharedData)); + job.setTypeAndData(jobType, jobData); + return job; } - private JobDaoImpl createJob(JobType jobType, UUID templateId, Integer indexInBulk, Map data) { + protected JobDaoImpl createJob(JobType jobType, Job.JobStatus jobStatus, String userId) { JobDaoImpl job = new JobDaoImpl(); - job.setStatus(Job.JobStatus.PENDING); - job.setTypeAndData(jobType, data); - job.setTemplateId(templateId); - job.setIndexInBulk(indexInBulk); + job.setTypeAndData(jobType, null); + job.setStatus(jobStatus); + job.setUuid(UUID.randomUUID()); + job.setUserId(userId); return job; } + } diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java index 1ff1296c..b301a2fb 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobDaoImpl.java @@ -3,19 +3,31 @@ package org.onap.vid.job.impl; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.MoreObjects; +import org.hibernate.annotations.DynamicUpdate; +import org.hibernate.annotations.SelectBeforeUpdate; import org.hibernate.annotations.Type; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.job.Job; +import org.onap.vid.job.JobException; import org.onap.vid.job.JobType; import org.onap.vid.model.VidBaseEntity; import javax.persistence.*; import java.io.IOException; -import java.util.*; - +import java.util.Date; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/* + The following 2 annotations let hibernate to update only fields that actually have been changed. + DynamicUpdate tell hibernate to update only dirty fields. + SelectBeforeUpdate is needed since during update the entity is detached (get and update are in different sessions) +*/ +@DynamicUpdate() +@SelectBeforeUpdate() @Entity @Table(name = "vid_job") public class JobDaoImpl extends VidBaseEntity implements Job { @@ -23,7 +35,7 @@ public class JobDaoImpl extends VidBaseEntity implements Job { private static ObjectMapper objectMapper = new ObjectMapper(); private Job.JobStatus status; private JobType type; - private Map> data = new TreeMap<>(); + private JobData data = new JobData(); private UUID templateId; private UUID uuid; private String takenBy; @@ -83,16 +95,25 @@ public class JobDaoImpl extends VidBaseEntity implements Job { public void setDataRaw(String data) { try { - this.data = objectMapper.readValue(data, new TypeReference>>() { - }); + this.data = objectMapper.readValue(data, JobData.class); } catch (IOException e) { - throw new GenericUncheckedException(e); + throw new JobException("Error parsing job's data", uuid, e); } } @Transient public Map getData() { - return data.get(getType()); + return data.getCommandData().get(getType()); + } + + public void setSharedData(JobSharedData sharedData) { + this.data.setSharedData(sharedData); + } + + @Override + @Transient + public JobSharedData getSharedData() { + return this.data.getSharedData(); } @Override @@ -100,7 +121,7 @@ public class JobDaoImpl extends VidBaseEntity implements Job { // *add* the data to map, // then change state to given type this.type = jobType; - this.data.put(jobType, data); + this.data.getCommandData().put(jobType, data); } @Column(name = "TAKEN_BY") @@ -123,6 +144,7 @@ public class JobDaoImpl extends VidBaseEntity implements Job { this.templateId = templateId; } + @Override @Column(name="INDEX_IN_BULK") public Integer getIndexInBulk() { return indexInBulk; diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobData.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobData.java new file mode 100644 index 00000000..0b7a6b7c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobData.java @@ -0,0 +1,54 @@ +package org.onap.vid.job.impl; + +import org.onap.vid.job.JobType; + +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; + +public class JobData { + + private TreeMap> commandData; + private JobSharedData sharedData; + + public JobData() { + commandData = new TreeMap<>(); + sharedData = new JobSharedData(); + } + + public JobData(TreeMap> commandData, JobSharedData sharedData) { + this.commandData = commandData; + this.sharedData = sharedData; + } + + public TreeMap> getCommandData() { + return commandData; + } + + public void setCommandData(TreeMap> commandData) { + this.commandData = commandData; + } + + public JobSharedData getSharedData() { + return sharedData; + } + + public void setSharedData(JobSharedData sharedData) { + this.sharedData = sharedData; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof JobData)) return false; + JobData jobData = (JobData) o; + return Objects.equals(getCommandData(), jobData.getCommandData()) && + Objects.equals(getSharedData(), jobData.getSharedData()); + } + + @Override + public int hashCode() { + + return Objects.hash(getCommandData(), getSharedData()); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java index a5070fbd..59b2f250 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSchedulerInitializer.java @@ -1,12 +1,12 @@ package org.onap.vid.job.impl; import com.google.common.collect.ImmutableMap; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.job.Job; import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.command.JobCommandFactory; import org.onap.vid.properties.Features; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.SchedulerFactoryBean; @@ -46,7 +46,9 @@ public class JobSchedulerInitializer { return; } scheduleJobWorker(Job.JobStatus.PENDING, 1); + scheduleJobWorker(Job.JobStatus.CREATING, 1); scheduleJobWorker(Job.JobStatus.IN_PROGRESS, 1); + scheduleJobWorker(Job.JobStatus.RESOURCE_IN_PROGRESS, 1); } private void scheduleJobWorker(Job.JobStatus topic, int intervalInSeconds) { diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSharedData.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSharedData.java new file mode 100644 index 00000000..8f1e4573 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobSharedData.java @@ -0,0 +1,84 @@ +package org.onap.vid.job.impl; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import org.onap.vid.job.JobAdapter; + +import java.util.Objects; +import java.util.UUID; + +public class JobSharedData { + + protected UUID jobUuid; + protected String userId; + protected Class requestType; + protected UUID rootJobId; + + @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, property="class") + protected JobAdapter.AsyncJobRequest request; + + public JobSharedData() { + } + + public JobSharedData(UUID jobUuid, String userId, JobAdapter.AsyncJobRequest request) { + this.jobUuid = jobUuid; + this.userId = userId; + this.requestType = request.getClass(); + this.request = request; + this.rootJobId = jobUuid; + } + + public JobSharedData(UUID jobUuid, JobAdapter.AsyncJobRequest request, JobSharedData parentData) { + this(jobUuid, parentData.getUserId(), request); + rootJobId = parentData.getRootJobId() != null ? parentData.getRootJobId() : parentData.getJobUuid(); + } + + + public UUID getJobUuid() { + return jobUuid; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Class getRequestType() { + return requestType; + } + + public void setRequestType(Class requestType) { + this.requestType = requestType; + } + + public JobAdapter.AsyncJobRequest getRequest() { + return request; + } + + public void setRequest(JobAdapter.AsyncJobRequest request) { + this.request = request; + } + + public UUID getRootJobId() { + return rootJobId; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof JobSharedData)) return false; + JobSharedData that = (JobSharedData) o; + return Objects.equals(getJobUuid(), that.getJobUuid()) && + Objects.equals(getUserId(), that.getUserId()) && + Objects.equals(getRequestType(), that.getRequestType()) && + Objects.equals(getRootJobId(), that.getRootJobId()) && + Objects.equals(getRequest(), that.getRequest()); + } + + @Override + public int hashCode() { + return Objects.hash(getJobUuid(), getUserId(), getRequestType(), getRootJobId(), getRequest()); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java index aa94a2aa..36ec4314 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobWorker.java @@ -1,13 +1,11 @@ package org.onap.vid.job.impl; import org.apache.commons.lang3.StringUtils; -import org.onap.vid.job.Job; -import org.onap.vid.job.JobCommand; -import org.onap.vid.job.JobsBrokerService; -import org.onap.vid.job.NextCommand; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.job.*; import org.onap.vid.job.command.JobCommandFactory; import org.onap.vid.properties.Features; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.quartz.JobExecutionContext; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.stereotype.Component; @@ -52,6 +50,8 @@ public class JobWorker extends QuartzJobBean { return jobsBrokerService.pull(topic, UUID.randomUUID().toString()); } catch (Exception e) { LOGGER.error(EELFLoggerDelegate.errorLogger, "failed to pull job from queue, breaking: {}", e, e); + tryMutingJobFromException(e); + return Optional.empty(); } } @@ -72,9 +72,7 @@ public class JobWorker extends QuartzJobBean { NextCommand nextCommand = executeCommandAndGetNext(job); - Job nextJob = setNextCommandInJob(nextCommand, job); - - return nextJob; + return setNextCommandInJob(nextCommand, job); } private NextCommand executeCommandAndGetNext(Job job) { @@ -83,7 +81,7 @@ public class JobWorker extends QuartzJobBean { final JobCommand jobCommand = jobCommandFactory.toCommand(job); nextCommand = jobCommand.call(); } catch (Exception e) { - LOGGER.error(EELFLoggerDelegate.errorLogger, "error while executing job from queue: {}", e, e); + LOGGER.error("error while executing job from queue: {}", e); nextCommand = new NextCommand(FAILED); } @@ -114,6 +112,25 @@ public class JobWorker extends QuartzJobBean { return featureManager.isActive(Features.FLAG_ASYNC_INSTANTIATION); } + private void tryMutingJobFromException(Exception e) { + // If there's JobException in the stack, read job uuid from + // the exception, and mute it in DB. + final int indexOfJobException = + ExceptionUtils.indexOfThrowable(e, JobException.class); + + if (indexOfJobException >= 0) { + try { + final JobException jobException = (JobException) ExceptionUtils.getThrowableList(e).get(indexOfJobException); + LOGGER.info(EELFLoggerDelegate.debugLogger, "muting job: {} ({})", jobException.getJobUuid(), jobException.toString()); + final boolean success = jobsBrokerService.mute(jobException.getJobUuid()); + if (!success) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "failed to mute job {}", jobException.getJobUuid()); + } + } catch (Exception e1) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "failed to mute job: {}", e1, e1); + } + } + } //used by quartz to inject JobsBrokerService into the job //see JobSchedulerInitializer diff --git a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java index e286cc4a..e8747879 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/impl/JobsBrokerServiceInDatabaseImpl.java @@ -2,15 +2,15 @@ package org.onap.vid.job.impl; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.exceptions.OperationNotAllowedException; import org.onap.vid.job.Job; import org.onap.vid.job.JobsBrokerService; import org.onap.vid.properties.VidProperties; import org.onap.vid.utils.DaoUtils; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -21,6 +21,8 @@ import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.*; +import static org.onap.vid.job.Job.JobStatus.CREATING; + @Service public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { @@ -56,7 +58,6 @@ public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { @Override public UUID add(Job job) { final JobDaoImpl jobDao = castToJobDaoImpl(job); - jobDao.setUuid(UUID.randomUUID()); dataAccessService.saveDomainObject(jobDao, DaoUtils.getPropsMap()); return job.getUuid(); } @@ -102,23 +103,30 @@ public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { return Timestamp.valueOf(LocalDateTime.now().minusSeconds(pollingIntervalSeconds)); } + private String selectQueryByJobStatus(Job.JobStatus topic){ + + String intervalCondition = (topic==CREATING) ? "" : (" and MODIFIED_DATE <= '" + nowMinusInterval()+"'"); + return "" + + "select * from VID_JOB" + + " where" + + // select only non-deleted in-progress jobs + " JOB_STATUS = '" + topic + "'" + + " and TAKEN_BY is null" + + " and DELETED_AT is null" + + // give some breath, don't select jos that were recently reached + intervalCondition + + // take the oldest handled one + " order by MODIFIED_DATE ASC" + + // select only one result + " limit 1"; + } + private String sqlQueryForTopic(Job.JobStatus topic) { switch (topic) { case IN_PROGRESS: - return "" + - "select * from VID_JOB" + - " where" + - // select only non-deleted in-progress jobs - " JOB_STATUS = 'IN_PROGRESS'" + - " and TAKEN_BY is null" + - " and DELETED_AT is null" + - // give some breath, don't select jos that were recently reached - " and MODIFIED_DATE <= '" + nowMinusInterval() + - // take the oldest handled one - "' order by MODIFIED_DATE ASC" + - // select only one result - " limit 1"; - + case RESOURCE_IN_PROGRESS: + case CREATING: + return selectQueryByJobStatus(topic); case PENDING: return "" + // select only pending jobs @@ -137,9 +145,10 @@ public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { // don't take jobs from templates that already in-progress/failed "and TEMPLATE_Id not in \n" + "(select TEMPLATE_Id from vid_job where" + + " TEMPLATE_Id IS NOT NULL and("+ " (JOB_STATUS='FAILED' and DELETED_AT is null)" + // failed but not deleted " or JOB_STATUS='IN_PROGRESS'" + - " or TAKEN_BY IS NOT NULL)" + " \n " + + " or TAKEN_BY IS NOT NULL))" + " \n " + // prefer older jobs, but the earlier in each bulk "order by has_any_in_progress_job, CREATED_DATE, INDEX_IN_BULK " + // select only one result @@ -233,4 +242,32 @@ public class JobsBrokerServiceInDatabaseImpl implements JobsBrokerService { throw new OperationNotAllowedException("Service deletion failed"); } } + + @Override + public boolean mute(UUID jobId) { + if (jobId == null) { + return false; + } + + final String prefix = "DUMP"; + int updatedEntities; + + // Changing the topic (i.e. `job.status`) makes the job non-fetchable. + String hqlUpdate = "" + + "update JobDaoImpl job set" + + " job.status = concat('" + prefix + "_', job.status)," + + // empty `takenBy`, because some logics treat taken as in-progress + " takenBy = null" + + " where " + + " job.id = :id" + + // if prefix already on the topic -- no need to do it twice. + " and job.status NOT LIKE '" + prefix + "\\_%'"; + + updatedEntities = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> + session.createQuery(hqlUpdate) + .setText("id", jobId.toString()) + .executeUpdate()); + + return updatedEntities != 0; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Action.java b/vid-app-common/src/main/java/org/onap/vid/model/Action.java new file mode 100644 index 00000000..32ee01fb --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/Action.java @@ -0,0 +1,15 @@ +package org.onap.vid.model; + +public enum Action { + Create(ServiceInfo.ServiceAction.INSTANTIATE), + Delete(ServiceInfo.ServiceAction.DELETE), + None(ServiceInfo.ServiceAction.UPDATE); + + private final ServiceInfo.ServiceAction serviceAction; + Action(ServiceInfo.ServiceAction serviceAction){ + this.serviceAction = serviceAction; + } + public ServiceInfo.ServiceAction getServiceAction() { + return serviceAction; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/CR.java b/vid-app-common/src/main/java/org/onap/vid/model/CR.java index f8c046e7..d8ecd64b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/CR.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/CR.java @@ -17,7 +17,7 @@ public class CR extends Node{ private String customizationUUID; - private Map networksCollection = new HashMap(); + private Map networksCollection = new HashMap<>(); diff --git a/vid-app-common/src/main/java/org/onap/vid/model/CommandProperty.java b/vid-app-common/src/main/java/org/onap/vid/model/CommandProperty.java index 4f5ee173..e398c542 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/CommandProperty.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/CommandProperty.java @@ -20,8 +20,6 @@ package org.onap.vid.model; -import java.util.Map; - /** * The Class Command Property. */ @@ -87,7 +85,6 @@ public class CommandProperty { } public String toString () { - String result = "displayName=" + displayName + " command=" + command + " inputName" + inputName; - return result; + return "displayName=" + displayName + " command=" + command + " inputName" + inputName; } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Group.java b/vid-app-common/src/main/java/org/onap/vid/model/Group.java index 5f98341d..3da15879 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/Group.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/Group.java @@ -1,11 +1,13 @@ package org.onap.vid.model; import org.onap.vid.asdc.beans.tosca.Input; -import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.asdc.parser.ToscaParserImpl2.Constants; import java.util.Map; -public class Group { +import static org.onap.vid.asdc.parser.ToscaParserImpl2.isModuleTypeIsBaseObjectSafe; + +public class Group implements MinimalNode { /** The uuid. */ @@ -182,7 +184,11 @@ public class Group { protected static GroupProperties extractPropertiesForGroup(org.onap.vid.asdc.beans.tosca.Group group){ - String [] propertyKeys = {ToscaParserImpl2.Constants.MIN_VF_MODULE_INSTANCES, ToscaParserImpl2.Constants.MAX_VF_MODULE_INSTANCES, ToscaParserImpl2.Constants.INITIAL_COUNT}; + String [] propertyKeys = { + Constants.MIN_VF_MODULE_INSTANCES, + Constants.MAX_VF_MODULE_INSTANCES, + Constants.INITIAL_COUNT, + }; GroupProperties groupProperties = new GroupProperties(); for(String propertyKey : propertyKeys){ @@ -191,18 +197,21 @@ public class Group { setInGroupProperties(groupProperties, propertyKey, (Integer) val); } } + + groupProperties.setBaseModule(isModuleTypeIsBaseObjectSafe(group.getProperties().get(Constants.VF_MODULE_TYPE))); + return groupProperties; } private static void setInGroupProperties(GroupProperties groupProperties, String propertyKey, Integer propertyValue){ switch (propertyKey) { - case ToscaParserImpl2.Constants.MIN_VF_MODULE_INSTANCES: + case Constants.MIN_VF_MODULE_INSTANCES: groupProperties.setMinCountInstances(propertyValue); break; - case ToscaParserImpl2.Constants.MAX_VF_MODULE_INSTANCES: + case Constants.MAX_VF_MODULE_INSTANCES: groupProperties.setMaxCountInstances(propertyValue); break; - case ToscaParserImpl2.Constants.INITIAL_COUNT: + case Constants.INITIAL_COUNT: groupProperties.setInitialCount(propertyValue); break; default: diff --git a/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java b/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java index c7ca6006..d8a57e46 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/GroupProperties.java @@ -5,6 +5,7 @@ public class GroupProperties { private Integer maxCountInstances; private Integer initialCount; private String vfModuleLabel; + private boolean baseModule = false; public String getVfModuleLabel() { return vfModuleLabel; @@ -30,6 +31,14 @@ public class GroupProperties { this.maxCountInstances = maxCountInstances; } + public boolean getBaseModule() { + return baseModule; + } + + public void setBaseModule(boolean baseModule) { + this.baseModule = baseModule; + } + public Integer getInitialCount() { return initialCount; } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java b/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java index 61426799..3da41a41 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/JobAuditStatus.java @@ -1,20 +1,36 @@ package org.onap.vid.model; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.hibernate.annotations.DynamicUpdate; +import org.hibernate.annotations.SelectBeforeUpdate; import org.hibernate.annotations.Type; -import org.onap.vid.job.Job.JobStatus; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.job.Job.JobStatus; import javax.persistence.*; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.Date; +import java.util.TimeZone; import java.util.UUID; +/* + The following 2 annotations let hibernate to update only fields that actually have been changed. + DynamicUpdate tell hibernate to update only dirty fields. + SelectBeforeUpdate is needed since during update the entity is detached (get and update are in different sessions) + */ +@DynamicUpdate() +@SelectBeforeUpdate() @Entity @Table(name = "vid_job_audit_status") public class JobAuditStatus extends VidBaseEntity { + public static final int MAX_ADDITIONAL_INFO_LENGTH = 2000; static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JobAuditStatus.class); + private static final String defaultFormat = "E, dd MMM yyyy HH:mm:ss z"; public JobAuditStatus(){} @@ -32,7 +48,7 @@ public class JobAuditStatus extends VidBaseEntity { public JobAuditStatus(UUID jobId, String jobStatus, SourceStatus source, UUID requestId, String additionalInfo) { this(jobId, jobStatus, source); this.requestId = requestId; - this.additionalInfo = additionalInfo; + setAdditionalInfo(additionalInfo); } public JobAuditStatus(UUID jobId, String jobStatus, SourceStatus source, UUID requestId, String additionalInfo, Date date){ @@ -40,6 +56,37 @@ public class JobAuditStatus extends VidBaseEntity { this.created = date; } + public JobAuditStatus(String instanceName, String jobStatus, UUID requestId, String additionalInfo) { + this.instanceName = instanceName; + this.jobStatus = jobStatus; + this.requestId = requestId; + this.additionalInfo = additionalInfo; + + } + + public JobAuditStatus(String instanceName, String jobStatus, UUID requestId, String additionalInfo, String date, String instanceType) { + this(instanceName, jobStatus, requestId, additionalInfo); + this.created = dateStringToDate(date); + this.instanceType = instanceType; + } + + + private Date dateStringToDate(String dateAsString){ + if (StringUtils.isEmpty(dateAsString)) { + return null; + } + + DateFormat format = new SimpleDateFormat(defaultFormat); + format.setTimeZone(TimeZone.getTimeZone("GMT")); + Date date = null ; + try { + date = format.parse(dateAsString); + } catch (ParseException e) { + logger.error("There was an error to parse the string "+ dateAsString +" to date ", e.getMessage()); + } + return date; + } + @Override public boolean equals(Object o) { if (this == o) return true; @@ -74,6 +121,8 @@ public class JobAuditStatus extends VidBaseEntity { } private UUID jobId; + private String instanceName; + private String instanceType; private String jobStatus; private SourceStatus source; private UUID requestId; @@ -128,13 +177,31 @@ public class JobAuditStatus extends VidBaseEntity { this.requestId = requestId; } - @Column(name = "ADDITIONAL_INFO") + @Column(name = "ADDITIONAL_INFO", columnDefinition = "VARCHAR(2000)") public String getAdditionalInfo() { return additionalInfo; } public void setAdditionalInfo(String additionalInfo) { - this.additionalInfo = additionalInfo; + this.additionalInfo = StringUtils.substring(additionalInfo, 0, MAX_ADDITIONAL_INFO_LENGTH); + } + + @Transient + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + @Transient + public String getInstanceType() { + return instanceType; + } + + public void setInstanceType(String instanceType) { + this.instanceType = instanceType; } @Transient diff --git a/vid-app-common/src/main/java/org/onap/vid/model/MinimalNode.kt b/vid-app-common/src/main/java/org/onap/vid/model/MinimalNode.kt new file mode 100644 index 00000000..1b44e652 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/MinimalNode.kt @@ -0,0 +1,8 @@ +package org.onap.vid.model + +interface MinimalNode { + val invariantUuid: String + val uuid: String + val version: String + val name: String +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ModelConstants.java b/vid-app-common/src/main/java/org/onap/vid/model/ModelConstants.java index 9ceeb807..4ee473d1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/ModelConstants.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/ModelConstants.java @@ -25,20 +25,20 @@ package org.onap.vid.model; public class ModelConstants { /** The Constant GET_INPUT_TAG. */ - public final static String GET_INPUT_TAG = "get_input"; + public static final String GET_INPUT_TAG = "get_input"; public static final String ASDC_MODEL_NAMESPACE = "asdc.model.namespace"; public static final String ASDC_SVC_API_PATH = "sdc.svc.api.path"; public static final String ASDC_RESOURCE_API_PATH = "sdc.resource.api.path"; - public static final String DEFAULT_ASDC_MODEL_NAMESPACE = "org.onap."; + public static final String DEFAULT_ASDC_MODEL_NAMESPACE = "org.openecomp."; public static final String DEFAULT_ASDC_SVC_API_PATH = "sdc/v1/catalog/services"; public static final String DEFAULT_ASDC_RESOURCE_API_PATH = "sdc/v1/catalog/resources"; - public final static String VF_MODULE = "groups.VfModule"; - public final static String VNF = "resource.vf"; - public final static String NETWORK = "resource.vl"; + public static final String VF_MODULE = "groups.VfModule"; + public static final String VNF = "resource.vf"; + public static final String NETWORK = "resource.vl"; - public final static String ROLE_DELIMITER = "___"; + public static final String ROLE_DELIMITER = "___"; } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java b/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java index aae39e44..29f5e30a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NameCounter.java @@ -18,7 +18,7 @@ public class NameCounter { public NameCounter(String name) { this.name = name; - this.counter = 1; + this.counter = 0; } @Id diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NewNetwork.java b/vid-app-common/src/main/java/org/onap/vid/model/NewNetwork.java index 9f1ffd35..8e130a58 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NewNetwork.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NewNetwork.java @@ -20,8 +20,6 @@ package org.onap.vid.model; -import org.onap.vid.asdc.beans.tosca.NodeTemplate; - /** * The Class Network. */ diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NewNode.java b/vid-app-common/src/main/java/org/onap/vid/model/NewNode.java index 394f7b96..6a185555 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NewNode.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NewNode.java @@ -1,22 +1,12 @@ package org.onap.vid.model; -import java.text.DateFormat; -import java.text.SimpleDateFormat; +import org.onap.vid.asdc.beans.tosca.Input; + import java.util.HashMap; import java.util.Map; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.asdc.beans.tosca.Input; - public class NewNode { - - /** The Constant LOG. */ - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(Node.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** The uuid. */ private String uuid; @@ -47,8 +37,8 @@ public class NewNode { * Instantiates a new node. */ public NewNode() { - this.commands = new HashMap(); - this.properties = new HashMap(); + this.commands = new HashMap<>(); + this.properties = new HashMap<>(); } /** diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java b/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java index e55ba4a4..1cc6a02f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NewServiceModel.java @@ -20,27 +20,18 @@ package org.onap.vid.model; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - import org.onap.vid.asdc.beans.tosca.Group; import org.onap.vid.asdc.beans.tosca.ToscaModel; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.properties.VidProperties; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; /** * The Class ServiceModel. */ public class NewServiceModel { - - /** The Constant LOG. */ - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(NewServiceModel.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The service. */ private Service service; @@ -63,12 +54,15 @@ public class NewServiceModel { private Map configurations; + private Map fabricConfigurations; + private Map serviceProxies; private Map pnfs; private Map collectionResource; + private Map vnfGroups; /** * Instantiates a new service model. @@ -189,6 +183,14 @@ public class NewServiceModel { this.collectionResource = collectionResource; } + public Map getFabricConfigurations() { + return fabricConfigurations; + } + + public void setFabricConfigurations(Map fabricConfigurations) { + this.fabricConfigurations = fabricConfigurations; + } + /** * Extract service. * @@ -211,15 +213,14 @@ public class NewServiceModel { //THIS IS A TEMPORARY FIX, AT SOME POINT UNCOMMENT ME //service.setVersion(serviceToscaModel.getMetadata().getVersion()); service.setVersion(asdcServiceMetadata.getVersion()); - return service; } public static void extractGroups (ToscaModel serviceToscaModel,NewServiceModel serviceModel) { // Get the groups. The groups may duplicate the groups that are in the VNF model and have // additional data like the VF module customization String> - final Map vfModules = new HashMap (); - final Map volumeGroups = new HashMap (); + final Map vfModules = new HashMap<> (); + final Map volumeGroups = new HashMap<> (); String asdcModelNamespace = VidProperties.getAsdcModelNamespace(); String vfModuleTag = asdcModelNamespace + ModelConstants.VF_MODULE; @@ -243,57 +244,15 @@ public class NewServiceModel { serviceModel.setVolumeGroups (volumeGroups); } + + public Map getVnfGroups() { + return vnfGroups; + } + + public void setVnfGroups(Map vnfGroups) { + this.vnfGroups = vnfGroups; + } /** * Populate the vf modules and volume groups that we may have under the service level under each VNF. */ -// public void associateGroups() { -// String methodName = "associateGroups()"; -// LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " start"); -// // go through the vnfs, get the vnf normalized name and look for a vf module with a customization name that starts -// // with vnf + ".." -// String vnfCustomizationName = null; -// String normalizedVnfCustomizationName = null; -// String vfModuleCustomizationName = null; -// NewVNF tmpVnf = null; -// -// if ( ( getVnfs() != null ) && (!(getVnfs().isEmpty())) ) { -// for (Entry vnfComponent : getVnfs().entrySet()) { -// vnfCustomizationName = vnfComponent.getValue().getModelCustomizationName(); -// normalizedVnfCustomizationName = VNF.normalizeName(vnfCustomizationName); -// -// LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + -// " VNF customizationName=" + vnfCustomizationName + "normalized customization name=" + normalizedVnfCustomizationName); -// -// // now check to see if there is a vf module with customization name that starts with normalizedVnfCustomizationName -// -// if (( getVfModules() != null ) && (!(getVfModules().isEmpty()))) { -// for (Entry vfModuleComponent : getVfModules().entrySet()) { -// vfModuleCustomizationName = vfModuleComponent.getValue().getModelCustomizationName(); -// -// LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + -// " VF Module customizationName=" + vfModuleCustomizationName ); -// if ( vfModuleCustomizationName.startsWith(normalizedVnfCustomizationName + ".." )) { -// -// // this vf module belongs to the VNF -// tmpVnf = vnfComponent.getValue(); -// (tmpVnf.getVfModules()).put(vfModuleComponent.getKey(), vfModuleComponent.getValue()); -// -// LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + -// " Associated VF Module customizationName=" + vfModuleComponent.getKey() + " with VNF customization name=" + vnfCustomizationName); -// -// // now find if this vf module has volume groups, if so, find the volume group with the same customization name and put it under the VNF -// if ( vfModuleComponent.getValue().isVolumeGroupAllowed() ) { -// if (( getVolumeGroups() != null ) && (!(getVolumeGroups().isEmpty()))) { -// if (getVolumeGroups().containsKey((vfModuleCustomizationName))) { -// (vnfComponent.getValue().getVolumeGroups()).put(vfModuleCustomizationName, (getVolumeGroups()).get(vfModuleCustomizationName)); -// } -// } -// } -// } -// } -// } -// } -// } - -// } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/NewVNF.java b/vid-app-common/src/main/java/org/onap/vid/model/NewVNF.java index dba6bdc5..1b977a94 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/NewVNF.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/NewVNF.java @@ -1,33 +1,22 @@ package org.onap.vid.model; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.asdc.beans.tosca.NodeTemplate; - public class NewVNF extends NewNode { - - /** The Constant LOG. */ - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VNF.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The pattern used to normalize VNF names */ - final static Pattern COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); + static final Pattern COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); /** The model customization name. */ private String modelCustomizationName; /** The vf modules. */ - private Map vfModules = new HashMap(); + private Map vfModules = new HashMap<>(); /** The volume groups. */ - private Map volumeGroups = new HashMap(); + private Map volumeGroups = new HashMap<>(); /** * Instantiates a newvnf. @@ -96,28 +85,6 @@ public class NewVNF extends NewNode { * @return the normalized name */ public static String normalizeName (String originalName) { - - String normalizedName = originalName.toLowerCase(); - normalizedName = COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - String[] splitArr = null; - - try { - splitArr = normalizedName.split(" "); - } - catch (Exception ex ) { - return (normalizedName); - } - StringBuffer sb = new StringBuffer(); - if ( splitArr != null ) { - for (String splitElement : splitArr) { - sb.append(splitElement); - } - return (sb.toString()); - } - else { - return (normalizedName); - } - + return VNF.normalizeName(originalName); } - } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Node.java b/vid-app-common/src/main/java/org/onap/vid/model/Node.java index 3b7abd39..64e4cc0b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/Node.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/Node.java @@ -20,51 +20,44 @@ package org.onap.vid.model; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.asdc.beans.tosca.Input; import org.onap.vid.asdc.beans.tosca.NodeTemplate; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; /** * The Class Node. */ -public class Node { +public class Node implements MinimalNode { /** The Constant LOG. */ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(Node.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The uuid. */ private String uuid; - + /** The invariant uuid. */ private String invariantUuid; - + /** The description. */ private String description; - + /** The name. */ private String name; - + /** The version. */ private String version; - + /** The model customization uuid. */ private String customizationUuid; - + /** The inputs. */ private Map inputs = new HashMap<>(); - + /** The get_input or other constructs from node template properties. */ private Map commands; - + /** The get_input or other constructs from node template properties. */ private Map properties; @@ -74,8 +67,8 @@ public class Node { * Instantiates a new node. */ public Node() { - this.commands = new HashMap(); - this.properties = new HashMap(); + this.commands = new HashMap<>(); + this.properties = new HashMap<>(); } /** @@ -253,7 +246,6 @@ public class Node { /** * Extract node. * - * @param modelCustomizationName the model customization name * @param nodeTemplate the node template * @return the node */ @@ -272,14 +264,14 @@ public class Node { try { // nodeTemplate.getProperties() map of String->Object for (Entry entrySet : nodeTemplate.getProperties().entrySet()) { - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " node template property: " + entrySet.getKey()); + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " node template property: " + entrySet.getKey()); if ( entrySet.getValue() != null ) { readStringAndCommandsProperties(entrySet); } } } catch ( Exception e ) { - LOG.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodName + " Unable to parse node properties: e=" + + LOG.error(EELFLoggerDelegate.errorLogger, methodName + " Unable to parse node properties: e=" + e.toString()); } } @@ -287,7 +279,7 @@ public class Node { private void readStringAndCommandsProperties(Entry entrySet) { String key = entrySet.getKey(); String methodName = "readStringAndCommandsProperties"; - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " property: " + + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " property: " + key + "=" + entrySet.getValue()); Class c = entrySet.getValue().getClass(); if ( c.getName().equalsIgnoreCase(String.class.getName())) { diff --git a/vid-app-common/src/main/java/org/onap/vid/model/PortMirroringConfig.java b/vid-app-common/src/main/java/org/onap/vid/model/PortMirroringConfig.java index 393c3425..6dc11ec6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/PortMirroringConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/PortMirroringConfig.java @@ -1,22 +1,12 @@ package org.onap.vid.model; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.sdc.toscaparser.api.NodeTemplate; import org.onap.sdc.toscaparser.api.RequirementAssignments; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.List; public class PortMirroringConfig extends Node { - /** The Constant LOG. */ - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(PortMirroringConfig.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** The model customization name. */ private String modelCustomizationName; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java b/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java index 9c12a52a..c40dffec 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/RequestReferencesContainer.java @@ -2,7 +2,7 @@ package org.onap.vid.model; import com.fasterxml.jackson.annotation.*; import com.google.common.base.MoreObjects; -import org.onap.vid.domain.mso.RequestReferences; +import org.onap.vid.mso.model.RequestReferences; import java.util.HashMap; import java.util.Map; @@ -12,7 +12,7 @@ public class RequestReferencesContainer { private final RequestReferences requestReferences; @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); @JsonAnyGetter public Map getAdditionalProperties() { diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Resource.java b/vid-app-common/src/main/java/org/onap/vid/model/Resource.java deleted file mode 100644 index 184f9ee6..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/model/Resource.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.model; - -/** - * The Class Resource. - */ -public class Resource { - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ResourceGroup.kt b/vid-app-common/src/main/java/org/onap/vid/model/ResourceGroup.kt new file mode 100644 index 00000000..67a766e2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/ResourceGroup.kt @@ -0,0 +1,13 @@ +package org.onap.vid.model + +data class ResourceGroup ( + + val type: String, + override val invariantUuid: String, + override val uuid: String, + override val version: String, + override val name: String, + val modelCustomizationName: String, + val properties: Map, + val members: Map +) : MinimalNode diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Service.java b/vid-app-common/src/main/java/org/onap/vid/model/Service.java index d00f58f0..27a52e6f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/Service.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/Service.java @@ -20,6 +20,7 @@ package org.onap.vid.model; +import com.fasterxml.jackson.annotation.JsonInclude; import org.onap.vid.asdc.beans.tosca.Input; import java.util.Map; @@ -65,7 +66,9 @@ public class Service { /** The inputs. */ private Map inputs; - + + private VidNotions vidNotions; + /** * Gets the uuid. * @@ -265,4 +268,13 @@ public class Service { public void setServiceRole(String serviceRole) { this.serviceRole = serviceRole; } + + @JsonInclude(JsonInclude.Include.NON_NULL) + public VidNotions getVidNotions() { + return vidNotions; + } + + public void setVidNotions(VidNotions vidNotions) { + this.vidNotions = vidNotions; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java b/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java index 4f04adf5..7f10f8a1 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/ServiceInfo.java @@ -1,9 +1,12 @@ package org.onap.vid.model; + import com.fasterxml.jackson.annotation.JsonProperty; + import org.hibernate.annotations.DynamicUpdate; + import org.hibernate.annotations.SelectBeforeUpdate; import org.hibernate.annotations.Type; - import org.onap.vid.job.Job; import org.onap.portalsdk.core.domain.support.DomainVo; + import org.onap.vid.job.Job; import javax.persistence.*; import java.io.Serializable; @@ -12,10 +15,23 @@ import java.util.Set; import java.util.UUID; +/* + The following 2 annotations let hibernate to update only fields that actually have been changed. + DynamicUpdate tell hibernate to update only dirty fields. + SelectBeforeUpdate is needed since during update the entity is detached (get and update are in different sessions) +*/ +@DynamicUpdate() +@SelectBeforeUpdate() @Entity @Table(name = "vid_service_info") public class ServiceInfo extends DomainVo { + public enum ServiceAction { + INSTANTIATE, + DELETE, + UPDATE + } + public void setUserId(String userId) { this.userId = userId; } @@ -23,6 +39,8 @@ public class ServiceInfo extends DomainVo { private UUID jobId; private UUID templateId; private String userId; + private UUID msoRequestId; + private boolean aLaCarte; private Job.JobStatus jobStatus; private Date statusModifiedDate; private boolean hidden; @@ -39,19 +57,22 @@ public class ServiceInfo extends DomainVo { private String regionName; private String serviceType; private String subscriberName; + private String subscriberId; private String serviceInstanceId; private String serviceInstanceName; private String serviceModelId; private String serviceModelName; private String serviceModelVersion; private Date createdBulkDate; + private ServiceAction action; public ServiceInfo(){ } - public ServiceInfo(String userId, Job.JobStatus jobStatus, boolean pause, UUID jobId, UUID templateId, String owningEntityId, String owningEntityName, String project, String aicZoneId, String aicZoneName, String tenantId, String tenantName, String regionId, String regionName, String serviceType, String subscriberName, String serviceInstanceId, String serviceInstanceName, String serviceModelId, String serviceModelName, String serviceModelVersion, Date createdBulkDate) { + public ServiceInfo(String userId, Boolean aLaCarte, Job.JobStatus jobStatus, boolean pause, UUID jobId, UUID templateId, String owningEntityId, String owningEntityName, String project, String aicZoneId, String aicZoneName, String tenantId, String tenantName, String regionId, String regionName, String serviceType, String subscriberName, String subscriberId, String serviceInstanceId, String serviceInstanceName, String serviceModelId, String serviceModelName, String serviceModelVersion, Date createdBulkDate, ServiceAction action) { this.userId = userId; + this.aLaCarte = aLaCarte; this.jobStatus = jobStatus; this.jobId = jobId; this.templateId = templateId; @@ -67,12 +88,14 @@ public class ServiceInfo extends DomainVo { this.regionName = regionName; this.serviceType = serviceType; this.subscriberName = subscriberName; + this.subscriberId = subscriberId; this.serviceInstanceId = serviceInstanceId; this.serviceInstanceName = serviceInstanceName; this.serviceModelId = serviceModelId; this.serviceModelName = serviceModelName; this.serviceModelVersion = serviceModelVersion; this.createdBulkDate = createdBulkDate; + this.action = action; } @Column(name = "JOB_ID", columnDefinition = "CHAR(36)") @@ -92,6 +115,18 @@ public class ServiceInfo extends DomainVo { return userId; } + @Column(name = "MSO_REQUEST_ID", columnDefinition = "CHAR(36)") + @Type(type="org.hibernate.type.UUIDCharType") + public UUID getMsoRequestId() { + return msoRequestId; + } + + @Column(name="IS_A_LA_CARTE") + @JsonProperty("aLaCarte") + public boolean isALaCarte() { + return aLaCarte; + } + @Column(name="JOB_STATUS") @Enumerated(EnumType.STRING) public Job.JobStatus getJobStatus() { @@ -168,6 +203,11 @@ public class ServiceInfo extends DomainVo { return subscriberName; } + @Column(name="SUBSCRIBER_ID") + public String getSubscriberId() { + return subscriberId; + } + @Column(name="SERVICE_INSTANCE_ID") public String getServiceInstanceId() { return serviceInstanceId; @@ -203,6 +243,12 @@ public class ServiceInfo extends DomainVo { return deletedAt; } + @Column(name="ACTION") + @Enumerated(EnumType.STRING) + public ServiceAction getAction() { + return action; + } + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Override @@ -261,6 +307,14 @@ public class ServiceInfo extends DomainVo { this.templateId = templateId; } + public void setMsoRequestId(UUID requestId) { + this.msoRequestId = requestId; + } + + public void setALaCarte(boolean aLaCarte) { + this.aLaCarte = aLaCarte; + } + public void setJobStatus(Job.JobStatus jobStatus) { this.jobStatus = jobStatus; } @@ -321,6 +375,10 @@ public class ServiceInfo extends DomainVo { this.subscriberName = subscriberName; } + public void setSubscriberId(String subscriberId) { + this.subscriberId = subscriberId; + } + public void setServiceInstanceId(String serviceInstanceId) { this.serviceInstanceId = serviceInstanceId; } @@ -349,6 +407,7 @@ public class ServiceInfo extends DomainVo { this.deletedAt = deletedAt; } + public void setAction(ServiceAction action) { this.action = action; } @Override public boolean equals(Object o) { @@ -357,10 +416,12 @@ public class ServiceInfo extends DomainVo { ServiceInfo that = (ServiceInfo) o; return isHidden() == that.isHidden() && isPause() == that.isPause() && + isALaCarte() == that.isALaCarte() && Objects.equals(getDeletedAt(), that.getDeletedAt()) && Objects.equals(getJobId(), that.getJobId()) && Objects.equals(getTemplateId(), that.getTemplateId()) && Objects.equals(getUserId(), that.getUserId()) && + Objects.equals(getMsoRequestId(), that.getMsoRequestId()) && getJobStatus() == that.getJobStatus() && Objects.equals(getStatusModifiedDate(), that.getStatusModifiedDate()) && Objects.equals(getOwningEntityId(), that.getOwningEntityId()) && @@ -374,22 +435,24 @@ public class ServiceInfo extends DomainVo { Objects.equals(getRegionName(), that.getRegionName()) && Objects.equals(getServiceType(), that.getServiceType()) && Objects.equals(getSubscriberName(), that.getSubscriberName()) && + Objects.equals(getSubscriberId(), that.getSubscriberId()) && Objects.equals(getServiceInstanceId(), that.getServiceInstanceId()) && Objects.equals(getServiceInstanceName(), that.getServiceInstanceName()) && Objects.equals(getServiceModelId(), that.getServiceModelId()) && Objects.equals(getServiceModelName(), that.getServiceModelName()) && Objects.equals(getServiceModelVersion(), that.getServiceModelVersion()) && - Objects.equals(getCreatedBulkDate(), that.getCreatedBulkDate()); + Objects.equals(getCreatedBulkDate(), that.getCreatedBulkDate()) && + Objects.equals(getAction(), that.getAction()); } @Override public int hashCode() { - return Objects.hash(getJobId(), getTemplateId(), getUserId(), getJobStatus(), getStatusModifiedDate(), + return Objects.hash(getJobId(), getTemplateId(), getUserId(), getMsoRequestId(), isALaCarte(), getJobStatus(), getStatusModifiedDate(), isHidden(), isPause(), getDeletedAt(), getOwningEntityId(), getOwningEntityName(), getProject(), getAicZoneId(), getAicZoneName(), getTenantId(), getTenantName(), getRegionId(), - getRegionName(), getServiceType(), getSubscriberName(), getServiceInstanceId(), + getRegionName(), getServiceType(), getSubscriberName(), getSubscriberId(), getServiceInstanceId(), getServiceInstanceName(), getServiceModelId(), getServiceModelName(), - getServiceModelVersion(), getCreatedBulkDate()); + getServiceModelVersion(), getCreatedBulkDate(), getAction()); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java b/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java index 53eb18c6..d82bd55a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/ServiceModel.java @@ -21,14 +21,11 @@ package org.onap.vid.model; import org.apache.commons.collections.MapUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.asdc.beans.tosca.Group; import org.onap.vid.asdc.beans.tosca.ToscaModel; import org.onap.vid.properties.VidProperties; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -40,9 +37,7 @@ public class ServiceModel { /** The Constant LOG. */ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(ServiceModel.class); - - /** The Constant dateFormat. */ - static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + /** The service. */ private Service service; @@ -54,10 +49,12 @@ public class ServiceModel { private Map collectionResource; - /** Port Mirroring Configuration node templates */ private Map configurations; + /** Fabric Configuration node templates */ + private Map fabricConfigurations; + /** Service Proxy Nodes */ private Map serviceProxies; @@ -74,6 +71,10 @@ public class ServiceModel { /** The pnfs. */ private Map pnfs; + + /** Resource groups of VF (VNF) type. */ + private Map vnfGroups; + /** * Instantiates a new service model. */ @@ -135,6 +136,10 @@ public class ServiceModel { return serviceProxies; } + public Map getVnfGroups() { + return vnfGroups; + } + /** * Sets the service. * @@ -221,6 +226,10 @@ public class ServiceModel { */ public void setPnfs(Map pnfs) {this.pnfs = pnfs;} + public void setVnfGroups(Map vnfGroups) { + this.vnfGroups = vnfGroups; + } + public Map getCollectionResource() { return collectionResource; } @@ -229,6 +238,14 @@ public class ServiceModel { this.collectionResource = collectionResource; } + public Map getFabricConfigurations() { + return fabricConfigurations; + } + + public void setFabricConfigurations(Map fabricConfigurations) { + this.fabricConfigurations = fabricConfigurations; + } + /** * Extract service. * @@ -288,7 +305,7 @@ public class ServiceModel { */ public void associateGroups() { String methodName = "associateGroups()"; - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " start"); + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); // go through the vnfs, get the vnf normalized name and look for a vf module with a customization name that starts // with vnf + ".." String vnfCustomizationName = null; @@ -300,7 +317,7 @@ public class ServiceModel { vnfCustomizationName = vnfComponent.getValue().getModelCustomizationName(); normalizedVnfCustomizationName = VNF.normalizeName(vnfCustomizationName); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " VNF customizationName=" + vnfCustomizationName + "normalized customization name=" + normalizedVnfCustomizationName); // now check to see if there is a vf module with customization name that starts with normalizedVnfCustomizationName @@ -309,7 +326,7 @@ public class ServiceModel { for (Entry vfModuleComponent : getVfModules().entrySet()) { vfModuleCustomizationName = vfModuleComponent.getValue().getModelCustomizationName(); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " VF Module customizationName=" + vfModuleCustomizationName ); if ( vfModuleCustomizationName.startsWith(normalizedVnfCustomizationName + ".." )) { handleCustomizationName(methodName, vnfCustomizationName, vfModuleCustomizationName, vnfComponent, vfModuleComponent); @@ -328,7 +345,7 @@ public class ServiceModel { tmpVnf = vnfComponent.getValue(); (tmpVnf.getVfModules()).put(vfModuleComponent.getKey(), vfModuleComponent.getValue()); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " Associated VF Module customizationName=" + vfModuleComponent.getKey() + " with VNF customization name=" + vnfCustomizationName); // now find if this vf module has volume groups, if so, find the volume group with the same customization name and put it under the VNF diff --git a/vid-app-common/src/main/java/org/onap/vid/model/ServiceProxy.java b/vid-app-common/src/main/java/org/onap/vid/model/ServiceProxy.java index 628f5602..362031b6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/ServiceProxy.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/ServiceProxy.java @@ -1,18 +1,7 @@ package org.onap.vid.model; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - public class ServiceProxy extends Node { - /** The Constant LOG. */ - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(ServiceProxy.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - private String sourceModelUuid; private String sourceModelInvariant; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/SoftDeleteRequest.java b/vid-app-common/src/main/java/org/onap/vid/model/SoftDeleteRequest.java new file mode 100644 index 00000000..51c246be --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/SoftDeleteRequest.java @@ -0,0 +1,42 @@ +package org.onap.vid.model; + +public class SoftDeleteRequest { + + private String tenantId; + + private String lcpCloudRegionId; + + private String userId; + + public SoftDeleteRequest() {} + + public SoftDeleteRequest(String tenantId, String lcpCloudRegionId, String userId) { + this.tenantId = tenantId; + this.lcpCloudRegionId = lcpCloudRegionId; + this.userId = userId; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + public void setLcpCloudRegionId(String lcpCloudRegionId) { + this.lcpCloudRegionId = lcpCloudRegionId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/Subscriber.java b/vid-app-common/src/main/java/org/onap/vid/model/Subscriber.java index 70711b80..f2a49163 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/Subscriber.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/Subscriber.java @@ -1,7 +1,7 @@ package org.onap.vid.model; -import org.codehaus.jackson.annotate.JsonProperty; +import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Oren on 7/4/17. diff --git a/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java b/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java index a08b585b..8df9f81b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/SubscriberList.java @@ -1,7 +1,5 @@ package org.onap.vid.model; -import org.onap.portalsdk.core.web.support.UserUtils; - import java.util.List; /** diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VNF.java b/vid-app-common/src/main/java/org/onap/vid/model/VNF.java index 9da88870..76e43d28 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VNF.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/VNF.java @@ -20,42 +20,27 @@ package org.onap.vid.model; -import java.util.Map; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; +import org.onap.vid.asdc.beans.tosca.NodeTemplate; + import java.util.HashMap; -import java.util.Map.Entry; +import java.util.Map; import java.util.regex.Pattern; -import org.onap.vid.asdc.beans.tosca.NodeTemplate; -import org.onap.vid.controllers.VidController; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.asdc.beans.tosca.Group; -import org.onap.vid.asdc.beans.tosca.Input; - /** * The Class VNF. */ public class VNF extends Node { - - /** The Constant LOG. */ - private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VNF.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** The pattern used to normalize VNF names */ - final static Pattern COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); + static final Pattern COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); /** The model customization name. */ private String modelCustomizationName; /** The vf modules. */ - private Map vfModules = new HashMap(); + private Map vfModules = new HashMap<>(); /** The volume groups. */ - private Map volumeGroups = new HashMap(); + private Map volumeGroups = new HashMap<>(); private Map vfcInstanceGroups = new HashMap<>(); @@ -160,7 +145,7 @@ public class VNF extends Node { catch (Exception ex ) { return (normalizedName); } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); if ( splitArr != null ) { for (String splitElement : splitArr) { sb.append(splitElement); diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java b/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java index ea30571a..a0ea060f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/VfModule.java @@ -20,12 +20,8 @@ package org.onap.vid.model; -import org.onap.vid.asdc.beans.tosca.Group; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; +import org.onap.vid.asdc.beans.tosca.Group; /** * The Class VfModule. @@ -34,9 +30,7 @@ public class VfModule extends org.onap.vid.model.Group { /** The Constant LOG. */ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VfModule.class); - - /** The Constant dateFormat. */ - static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + public static final String VOLUME_GROUP = "volume_group"; /** The volume group allowed. */ @@ -88,7 +82,7 @@ public class VfModule extends org.onap.vid.model.Group { if (group.getProperties().get(VOLUME_GROUP) != null) { Class c = group.getProperties().get(VOLUME_GROUP).getClass(); - LOG.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " class name=" + + LOG.debug(EELFLoggerDelegate.debugLogger, methodName + " class name=" + c.getName()); if ( c.getName().equalsIgnoreCase(Boolean.class.getName()) ) { @@ -101,7 +95,7 @@ public class VfModule extends org.onap.vid.model.Group { } } catch ( Exception e ) { - LOG.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodName + " Unable to parse VF Module from group: e=" + + LOG.error(EELFLoggerDelegate.errorLogger, methodName + " Unable to parse VF Module from group: e=" + e.toString()); } return vfModule; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt b/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt new file mode 100644 index 00000000..b49af085 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/VidNotions.kt @@ -0,0 +1,34 @@ +package org.onap.vid.model + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import com.google.common.base.CaseFormat + +class VidNotions(@get:JsonInclude(JsonInclude.Include.NON_NULL) + val instantiationUI: InstantiationUI, val modelCategory: ModelCategory, val viewEditUI: InstantiationUI) { + enum class InstantiationUI { + NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS, + SERVICE_WITH_FABRIC_CONFIGURATION, + LEGACY, + SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de, + ANY_ALACARTE_NEW_UI, + MACRO_SERVICE, + SERVICE_WITH_VNF_GROUPING; + + @JsonValue + fun toLowerCamel(): String { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, this.name) + } + + } + + enum class ModelCategory { + @JsonProperty("5G Provider Network") + IS_5G_PROVIDER_NETWORK_MODEL, + @JsonProperty("5G Fabric Configuration") + IS_5G_FABRIC_CONFIGURATION_MODEL, + @JsonProperty("other") + OTHER + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AAITreeNode.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AAITreeNode.java new file mode 100644 index 00000000..e6f82296 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AAITreeNode.java @@ -0,0 +1,178 @@ +package org.onap.vid.model.aaiTree; + +import org.apache.commons.lang3.StringUtils; + +import java.util.*; + +public class AAITreeNode { + + private String type; + private int uniqueNumber; + private String orchestrationStatus; + private String provStatus; + private Boolean inMaint = null; + private String modelVersionId; + private String modelCustomizationId; + private String modelInvariantId; + private String id; + private String name; + private String modelVersion; + private String modelName; + private String modelCustomizationName; + private final List children = Collections.synchronizedList(new LinkedList<>()); + private Map additionalProperties = new HashMap<>(); + private String keyInModel; + private AAITreeNode parent; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public int getUniqueNumber() { + return uniqueNumber; + } + + public void setUniqueNumber(int uniqueNumber) { + this.uniqueNumber = uniqueNumber; + } + + public String getOrchestrationStatus() { + return orchestrationStatus; + } + + public void setOrchestrationStatus(String orchestrationStatus) { + this.orchestrationStatus = orchestrationStatus; + } + + public String getProvStatus() { + return provStatus; + } + + public void setProvStatus(String provStatus) { + this.provStatus = provStatus; + } + + public Boolean getInMaint() { + return inMaint; + } + + public void setInMaint(Boolean inMaint) { + this.inMaint = inMaint; + } + + public String getModelVersionId() { + return modelVersionId; + } + + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + public String getModelCustomizationId() { + return modelCustomizationId; + } + + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + public String getModelInvariantId() { + return modelInvariantId; + } + + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + 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 getModelCustomizationName() { + return modelCustomizationName; + } + + public void setModelCustomizationName(String modelCustomizationName) { + this.modelCustomizationName = modelCustomizationName; + } + + public List getChildren() { + return children; + } + + public Map getAdditionalProperties() { + return additionalProperties; + } + + public void setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + } + + public String getNodeKey() { + if (this.keyInModel != null) { + return this.keyInModel; + } + + return StringUtils.defaultIfEmpty(this.modelVersionId, "not provided"); + } + + public String getUniqueNodeKey() { + return getNodeKey() + ":" + String.format("%03d", this.uniqueNumber); + } + + public void setKeyInModel(String keyInModel) { + this.keyInModel = keyInModel; + } + + public String getKeyInModel() { + return keyInModel; + } + + public AAITreeNode getParent() { + return parent; + } + + public void setParent(AAITreeNode parent) { + this.parent = parent; + } + + public void addChildren(List children) { + for (AAITreeNode child : children) { + child.setParent(this); + } + + this.getChildren().addAll(children); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AbstractNode.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AbstractNode.java new file mode 100644 index 00000000..86669e92 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/AbstractNode.java @@ -0,0 +1,53 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.model.Action; +import org.onap.vid.mso.model.ModelInfo; + +public abstract class AbstractNode { + + protected final Action action; + protected String instanceName; + protected String instanceId; + protected String orchStatus; + protected String productFamilyId; + protected String lcpCloudRegionId; + protected String tenantId; + protected ModelInfo modelInfo; + + public AbstractNode() { + this.action = Action.None; + } + + public final Action getAction() { + return action; + } + + public final String getInstanceName() { + return instanceName; + } + + public final String getInstanceId() { + return instanceId; + } + + public final String getOrchStatus() { + return orchStatus; + } + + public final String getProductFamilyId() { + return productFamilyId; + } + + public final String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + public final String getTenantId() { + return tenantId; + } + + public final ModelInfo getModelInfo() { + return modelInfo; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/FailureAAITreeNode.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/FailureAAITreeNode.java new file mode 100644 index 00000000..e6234fca --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/FailureAAITreeNode.java @@ -0,0 +1,31 @@ +package org.onap.vid.model.aaiTree; + +import org.apache.commons.proxy.Invoker; +import org.apache.commons.proxy.factory.javassist.JavassistProxyFactory; +import org.jetbrains.annotations.NotNull; +import org.onap.vid.exceptions.GenericUncheckedException; + +public class FailureAAITreeNode extends AAITreeNode { + + private static final Class[] classes = {AAITreeNode.class}; + private static final JavassistProxyFactory proxyFactory = new JavassistProxyFactory(); // can proxy a class without an interface + + private FailureAAITreeNode() { + // don't instantiate this class + } + + /* + Returns a new AAITreeNode instance that throws an exception when + invoking any of its methods + */ + public static AAITreeNode of(Exception failureException) { + return (AAITreeNode) proxyFactory.createInvokerProxy(exceptionThrower(failureException), classes); + } + + @NotNull + private static Invoker exceptionThrower(Exception exception) { + return (self, thisMethod, args) -> { + throw new GenericUncheckedException("AAI node fetching failed.", exception); + }; + } +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Network.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Network.java new file mode 100644 index 00000000..959f741c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Network.java @@ -0,0 +1,20 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.aai.util.AAITreeConverter; + +import static org.onap.vid.aai.util.AAITreeConverter.NETWORK_TYPE; + +public class Network extends Node { + + public Network(AAITreeNode node) { + super(node, AAITreeConverter.ModelType.network); + } + + public static Network from(AAITreeNode node) { + Network network = new Network(node); + if (node.getAdditionalProperties().get(NETWORK_TYPE) != null) { + network.setInstanceType(node.getAdditionalProperties().get(NETWORK_TYPE).toString()); + } + return network; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Node.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Node.java new file mode 100644 index 00000000..6f0a4a05 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Node.java @@ -0,0 +1,139 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.aai.util.AAITreeConverter; +import org.onap.vid.mso.model.ModelInfo; + +public class Node extends AbstractNode { + private String instanceType; + + private String provStatus; + private Boolean inMaint; + + private String uuid; + private String originalName; + + private String legacyRegion; + private String lineOfBusiness; + private String platformName; + + private final String trackById; + + public Node(AAITreeNode aaiNode, AAITreeConverter.ModelType modelType) { + super(); + this.instanceId = aaiNode.getId(); + this.instanceName = aaiNode.getName(); + this.orchStatus = aaiNode.getOrchestrationStatus(); + this.provStatus = aaiNode.getProvStatus(); + this.inMaint = aaiNode.getInMaint(); + this.uuid = aaiNode.getModelVersionId(); + this.originalName = aaiNode.getModelCustomizationName(); + this.trackById = aaiNode.getUniqueNodeKey(); + + ModelInfo nodeModelInfo = new ModelInfo(); + nodeModelInfo.setModelType(modelType.name()); + nodeModelInfo.setModelName(aaiNode.getModelName()); + nodeModelInfo.setModelVersion(aaiNode.getModelVersion()); + nodeModelInfo.setModelVersionId(aaiNode.getModelVersionId()); + nodeModelInfo.setModelInvariantId(aaiNode.getModelInvariantId()); + nodeModelInfo.setModelCustomizationId(aaiNode.getModelCustomizationId()); + nodeModelInfo.setModelCustomizationName(aaiNode.getModelCustomizationName()); + + this.modelInfo = nodeModelInfo; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + public String getInstanceType() { + return instanceType; + } + + public void setInstanceType(String instanceType) { + this.instanceType = instanceType; + } + + public void setOrchStatus(String orchStatus) { + this.orchStatus = orchStatus; + } + + public String getProvStatus() { + return provStatus; + } + + public void setProvStatus(String provStatus) { + this.provStatus = provStatus; + } + + public Boolean getInMaint() { + return inMaint; + } + + public void setInMaint(Boolean inMaint) { + this.inMaint = inMaint; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getOriginalName() { + return originalName; + } + + public void setOriginalName(String originalName) { + this.originalName = originalName; + } + + public void setProductFamilyId(String productFamilyId) { + this.productFamilyId = productFamilyId; + } + + public void setLcpCloudRegionId(String lcpCloudRegionId) { + this.lcpCloudRegionId = lcpCloudRegionId; + } + + public String getLegacyRegion() { + return legacyRegion; + } + + public void setLegacyRegion(String legacyRegion) { + this.legacyRegion = legacyRegion; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getLineOfBusiness() { + return lineOfBusiness; + } + + public void setLineOfBusiness(String lineOfBusiness) { + this.lineOfBusiness = lineOfBusiness; + } + + public String getPlatformName() { + return platformName; + } + + public void setPlatformName(String platformName) { + this.platformName = platformName; + } + + public String getTrackById() { + return trackById; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java new file mode 100644 index 00000000..043d2ccd --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/RelatedVnf.java @@ -0,0 +1,52 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.aai.util.AAITreeConverter; + +import static org.onap.vid.aai.util.AAITreeConverter.VNF_TYPE; + +public class RelatedVnf extends Node { + + private String serviceInstanceId; + private String serviceInstanceName; + private String tenantName; + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getServiceInstanceName() { + return serviceInstanceName; + } + + public void setServiceInstanceName(String serviceInstanceName) { + this.serviceInstanceName = serviceInstanceName; + } + + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public RelatedVnf(AAITreeNode node) { + super(node, AAITreeConverter.ModelType.vnf); + } + + public static RelatedVnf from(AAITreeNode node) { + RelatedVnf vnf = new RelatedVnf(node); + vnf.setServiceInstanceId(node.getParent().getId()); + vnf.setServiceInstanceName(node.getParent().getName()); + + if (node.getAdditionalProperties().get(VNF_TYPE) != null) { + vnf.setInstanceType(node.getAdditionalProperties().get(VNF_TYPE).toString()); + } + + return vnf; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java new file mode 100644 index 00000000..6c660077 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/ServiceInstance.java @@ -0,0 +1,193 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.mso.model.ModelInfo; + +import java.util.HashMap; +import java.util.Map; + +public class ServiceInstance extends AbstractNode { + + private String globalSubscriberId; + private String subscriptionServiceType; + + private String owningEntityId; + + private String owningEntityName; + private String tenantName; + private String aicZoneId; + private String aicZoneName; + private String projectName; + + private String rollbackOnFailure; + private boolean isALaCarte; + + private Map vnfs = new HashMap<>(); + private Map networks = new HashMap<>(); + + private Map vnfGroups = new HashMap<>(); + + private int validationCounter; + private Map existingVNFCounterMap; + private Map existingNetworksCounterMap; + private Map existingVnfGroupCounterMap; + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + public void setOrchStatus(String orchStatus) { + this.orchStatus = orchStatus; + } + + public String getGlobalSubscriberId() { + return globalSubscriberId; + } + + public void setGlobalSubscriberId(String globalSubscriberId) { + this.globalSubscriberId = globalSubscriberId; + } + + public String getSubscriptionServiceType() { + return subscriptionServiceType; + } + + public void setSubscriptionServiceType(String subscriptionServiceType) { + this.subscriptionServiceType = subscriptionServiceType; + } + + public String getOwningEntityId() { + return owningEntityId; + } + + public void setOwningEntityId(String owningEntityId) { + this.owningEntityId = owningEntityId; + } + + public String getOwningEntityName() { + return owningEntityName; + } + + public void setOwningEntityName(String owningEntityName) { + this.owningEntityName = owningEntityName; + } + + public void setProductFamilyId(String productFamilyId) { + this.productFamilyId = productFamilyId; + } + + public void setLcpCloudRegionId(String lcpCloudRegionId) { + this.lcpCloudRegionId = lcpCloudRegionId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public String getAicZoneId() { + return aicZoneId; + } + + public void setAicZoneId(String aicZoneId) { + this.aicZoneId = aicZoneId; + } + + public String getAicZoneName() { + return aicZoneName; + } + + public void setAicZoneName(String aicZoneName) { + this.aicZoneName = aicZoneName; + } + + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getRollbackOnFailure() { + return rollbackOnFailure; + } + + public void setRollbackOnFailure(String rollbackOnFailure) { + this.rollbackOnFailure = rollbackOnFailure; + } + + public boolean getIsALaCarte() { + return isALaCarte; + } + + public void setIsALaCarte(boolean isALaCarte) { + this.isALaCarte = isALaCarte; + } + + public void setModelInfo(ModelInfo modelInfo) { + this.modelInfo = modelInfo; + } + + public Map getVnfs() { + return vnfs; + } + + public void setVnfs(Map vnfs) { + this.vnfs = vnfs; + } + + public Map getNetworks() { + return networks; + } + + public void setNetworks(Map networks) { + this.networks = networks; + } + + public Map getVnfGroups() { return vnfGroups; } + + public void setVnfGroups(Map vnfGroups) { this.vnfGroups = vnfGroups; } + + public int getValidationCounter() { + return validationCounter; + } + + public void setValidationCounter(int validationCounter) { + this.validationCounter = validationCounter; + } + + public Map getExistingVNFCounterMap() { + return existingVNFCounterMap; + } + + public void setExistingVNFCounterMap(Map existingVNFCounterMap) { + this.existingVNFCounterMap = existingVNFCounterMap; + } + + public Map getExistingNetworksCounterMap() { + return existingNetworksCounterMap; + } + + public void setExistingNetworksCounterMap(Map existingNetworksCounterMap) { + this.existingNetworksCounterMap = existingNetworksCounterMap; + } + + public Map getExistingVnfGroupCounterMap() { + return existingVnfGroupCounterMap; + } + + public void setExistingVnfGroupCounterMap(Map existingVnfGroupCounterMap) { + this.existingVnfGroupCounterMap = existingVnfGroupCounterMap; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VfModule.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VfModule.java new file mode 100644 index 00000000..14a43e79 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VfModule.java @@ -0,0 +1,41 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.aai.util.AAITreeConverter; + +import static org.onap.vid.aai.util.AAITreeConverter.IS_BASE_VF_MODULE; + +public class VfModule extends Node { + + private boolean isBase; + private String volumeGroupName; + + public VfModule(AAITreeNode node) { + super(node, AAITreeConverter.ModelType.vfModule); + } + + public boolean getIsBase() { + return isBase; + } + + public void setIsBase(boolean isBase) { + this.isBase = isBase; + } + + public String getVolumeGroupName() { + return volumeGroupName; + } + + public void setVolumeGroupName(String volumeGroupName) { + this.volumeGroupName = volumeGroupName; + } + + public static VfModule from(AAITreeNode node) { + VfModule vfModule = new VfModule(node); + + if (node.getAdditionalProperties().get(IS_BASE_VF_MODULE) != null) { + vfModule.setIsBase(Boolean.valueOf(node.getAdditionalProperties().get(IS_BASE_VF_MODULE).toString())); + } + + return vfModule; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Vnf.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Vnf.java new file mode 100644 index 00000000..a3280f4e --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/Vnf.java @@ -0,0 +1,54 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.aai.util.AAITreeConverter; +import org.onap.vid.services.AAITreeNodeBuilder; + +import java.util.HashMap; +import java.util.Map; + +import static org.onap.vid.aai.util.AAITreeConverter.VNF_TYPE; + +public class Vnf extends Node { + + private Map> vfModules = new HashMap<>(); + private Map networks = new HashMap<>(); + + public Vnf(AAITreeNode node) { + super(node, AAITreeConverter.ModelType.vnf); + } + + public Map> getVfModules() { + return vfModules; + } + + public void setVfModules(Map> vfModules) { + this.vfModules = vfModules; + } + + public Map getNetworks() { + return networks; + } + + public void setNetworks(Map networks) { + this.networks = networks; + } + + public static Vnf from(AAITreeNode node) { + Vnf vnf = new Vnf(node); + if (node.getAdditionalProperties().get(VNF_TYPE) != null) { + vnf.setInstanceType(node.getAdditionalProperties().get(VNF_TYPE).toString()); + } + + node.getChildren().forEach(child -> { + if (child.getType().equals(AAITreeNodeBuilder.VF_MODULE)) { + vnf.getVfModules().putIfAbsent(child.getNodeKey(), new HashMap<>()); + vnf.getVfModules().get(child.getNodeKey()) + .put(child.getUniqueNodeKey(), VfModule.from(child)); + } else if (child.getType().equals(AAITreeNodeBuilder.NETWORK)) { + vnf.getNetworks().put(child.getUniqueNodeKey(), Network.from(child)); + } + }); + + return vnf; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VnfGroup.java b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VnfGroup.java new file mode 100644 index 00000000..00e7ed8d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/aaiTree/VnfGroup.java @@ -0,0 +1,52 @@ +package org.onap.vid.model.aaiTree; + +import org.onap.vid.aai.util.AAITreeConverter; + + +public class VnfGroup extends Node { + + public static final String INSTANCE_GROUP_TYPE = "instance-group-type"; + public static final String INSTANCE_GROUP_ROLE = "instance-group-role"; + public static final String INSTANCE_GROUP_FUNCTION = "instance-group-function"; + + private String instanceGroupRole; + private String instanceGroupFunction; + + + public VnfGroup(AAITreeNode node) { + super(node, AAITreeConverter.ModelType.instanceGroup); + } + + public static VnfGroup from(AAITreeNode node) { + VnfGroup vnfGroup = new VnfGroup(node); + if (node.getAdditionalProperties().get(INSTANCE_GROUP_TYPE) != null) { + vnfGroup.setInstanceType(node.getAdditionalProperties().get(INSTANCE_GROUP_TYPE).toString()); + } + if (node.getAdditionalProperties().get(INSTANCE_GROUP_FUNCTION) != null) { + vnfGroup.setInstanceGroupFunction(node.getAdditionalProperties().get(INSTANCE_GROUP_FUNCTION).toString()); + } + if (node.getAdditionalProperties().get(INSTANCE_GROUP_ROLE) != null) { + vnfGroup.setInstanceGroupRole(node.getAdditionalProperties().get(INSTANCE_GROUP_ROLE).toString()); + } + + return vnfGroup; + } + + public String getInstanceGroupRole() { + return instanceGroupRole; + } + + public void setInstanceGroupRole(String instanceGroupRole) { + this.instanceGroupRole = instanceGroupRole; + } + + public String getInstanceGroupFunction() { + return instanceGroupFunction; + } + + public void setInstanceGroupFunction(String instanceGroupFunction) { + this.instanceGroupFunction = instanceGroupFunction; + } + + +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java b/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java index da8c912e..5f5a0def 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/probes/ExternalComponentStatus.java @@ -1,7 +1,7 @@ package org.onap.vid.model.probes; public class ExternalComponentStatus { - public enum Component {AAI, MSO} + public enum Component {AAI, MSO, SDC, SCHEDULER} private final Component component; private final boolean available; private final StatusMetadata metadata; diff --git a/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java b/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java index e80d563b..08bed397 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/probes/HttpRequestMetadata.java @@ -1,12 +1,20 @@ package org.onap.vid.model.probes; +import com.google.common.base.MoreObjects; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.ResponseWithRequestInfo; +import org.onap.vid.mso.RestObjectWithRequestInfo; +import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; + public class HttpRequestMetadata extends StatusMetadata { private final HttpMethod httpMethod; private final int httpCode; private final String url; - private final String rawData; + private String rawData = ""; public HttpRequestMetadata(HttpMethod httpMethod, int httpCode, String url, String rawData, String description, long duration) { super(description, duration); @@ -16,6 +24,43 @@ public class HttpRequestMetadata extends StatusMetadata { this.rawData = rawData; } + public HttpRequestMetadata(ResponseWithRequestInfo response, String description, long duration) { + this(response, description, duration, true); + } + + public HttpRequestMetadata(RestObjectWithRequestInfo response, String description, long duration) { + super(description, duration); + this.httpMethod = response.getHttpMethod(); + this.url = response.getRequestedUrl(); + this.httpCode = response.getHttpCode(); + this.rawData = response.getRawData(); + } + + public HttpRequestMetadata(ResponseWithRequestInfo response, String description, long duration, boolean readRawData) { + super(description, duration); + this.httpMethod = response.getRequestHttpMethod(); + this.url = response.getRequestUrl(); + this.httpCode = response.getResponse().getStatus(); + if (readRawData) { + try { + this.rawData = response.getResponse().readEntity(String.class); + } catch (Exception e) { + //Nothing to do here + } + } + } + + public HttpRequestMetadata(ExceptionWithRequestInfo exception, long duration) { + this(exception.getHttpMethod(), + defaultIfNull(exception.getHttpCode(), 0), + exception.getRequestedUrl(), + exception.getRawData(), + Logging.exceptionToDescription(exception.getCause()), + duration); + } + + + public HttpMethod getHttpMethod() { return httpMethod; } @@ -29,6 +74,18 @@ public class HttpRequestMetadata extends StatusMetadata { } public String getRawData() { - return rawData; + return StringUtils.substring(rawData, 0, 500); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(this) + .add("httpMethod", httpMethod) + .add("httpCode", httpCode) + .add("url", url) + .add("duration", duration) + .add("description", description) + .add("rawData", rawData) + .toString(); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/BaseResource.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/BaseResource.java new file mode 100644 index 00000000..653c7347 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/BaseResource.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.model.serviceInstantiation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.StringUtils; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.model.Action; +import org.onap.vid.mso.model.ModelInfo; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +public abstract class BaseResource implements JobAdapter.AsyncJobRequest { + + protected final String instanceId; + protected ModelInfo modelInfo; + + protected String instanceName; + + protected final Action action; + + protected String lcpCloudRegionId; + + protected String tenantId; + + protected List> instanceParams; + + protected boolean rollbackOnFailure; + + private static final Map actionStingToEnumMap = ImmutableMap.of( + "Delete", Action.Delete, + "Create", Action.Create, + "None", Action.None, + "Update_Delete", Action.Delete, + "None_Delete", Action.Delete + ); + + + protected BaseResource(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("action") String action, + @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("legacyRegion") String legacyRegion, + @JsonProperty("tenantId") String tenantId, + @JsonProperty("instanceParams") List> instanceParams, + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure, + @JsonProperty("instanceId") String instanceId) { + this.modelInfo = modelInfo; + this.modelInfo.setModelType(getModelType()); + this.rollbackOnFailure = rollbackOnFailure; + this.instanceName = StringUtils.defaultString(instanceName, "");; + this.action = actionStringToEnum(action); + this.lcpCloudRegionId = StringUtils.isNotEmpty(legacyRegion) ? legacyRegion : lcpCloudRegionId; + this.tenantId = tenantId; + this.instanceParams = instanceParams; + this.instanceId = instanceId; + } + + private Action actionStringToEnum(String actionAsString) { + return actionStingToEnumMap.get(actionAsString); + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public String getInstanceName() { + return instanceName; + } + + public Action getAction() { + return action; + } + + public String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + public String getTenantId() { + return tenantId; + } + + public List> getInstanceParams() { + return instanceParams == null ? Collections.emptyList() : instanceParams; + } + + public boolean isRollbackOnFailure() { return rollbackOnFailure; } + + public String getInstanceId() { + return instanceId; + } + + protected abstract String getModelType(); +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/InstanceGroup.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/InstanceGroup.java new file mode 100644 index 00000000..6155480c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/InstanceGroup.java @@ -0,0 +1,22 @@ +package org.onap.vid.model.serviceInstantiation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.mso.model.ModelInfo; + +public class InstanceGroup extends BaseResource implements JobAdapter.AsyncJobRequest { + + public InstanceGroup(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("action") String action, + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure, + @JsonProperty("instanceId") String instanceId) { + + super(modelInfo, instanceName, action, null, null, null, null, rollbackOnFailure, instanceId); + } + + @Override + protected String getModelType() { + return "instanceGroup"; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Network.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Network.java new file mode 100644 index 00000000..0e0c7e13 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Network.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.model.serviceInstantiation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.mso.model.ModelInfo; + +import java.util.List; +import java.util.Map; + +public class Network extends BaseResource implements JobAdapter.AsyncJobRequest { + + private final String productFamilyId; + + private final String platformName; + + private final String lineOfBusiness; + + public Network(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("productFamilyId") String productFamilyId, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("action") String action, + @JsonProperty("platformName") String platformName, + @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("legacyRegion") String legacyRegion, + @JsonProperty("tenantId") String tenantId, + @JsonProperty("instanceParams") List> instanceParams, + @JsonProperty("lineOfBusinessName") String lineOfBusiness, + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure, + @JsonProperty("instanceId") String instanceId) { + + super(modelInfo, instanceName, action, lcpCloudRegionId, legacyRegion, tenantId, instanceParams, rollbackOnFailure, instanceId); + this.productFamilyId = productFamilyId; + this.platformName = platformName; + this.lineOfBusiness = lineOfBusiness; + } + + public String getProductFamilyId() { + return productFamilyId; + } + + public String getPlatformName() { + return platformName; + } + + public String getLineOfBusiness() { + return lineOfBusiness; + } + + @Override + protected String getModelType() { + return "network"; + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java index 1d2e69d5..3cb1e949 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/ServiceInstantiation.java @@ -1,16 +1,14 @@ package org.onap.vid.model.serviceInstantiation; import com.fasterxml.jackson.annotation.JsonProperty; -import org.onap.vid.domain.mso.ModelInfo; import org.onap.vid.job.JobAdapter; +import org.onap.vid.mso.model.ModelInfo; import java.util.Collections; import java.util.List; import java.util.Map; -public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { - - private final ModelInfo modelInfo; +public class ServiceInstantiation extends BaseResource implements JobAdapter.AsyncJobRequest { private final String owningEntityId; @@ -24,16 +22,8 @@ public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { private final String productFamilyId; - private final String instanceName; - - private final Boolean isUserProvidedNaming; - private final String subscriptionServiceType; - private final String lcpCloudRegionId; - - private final String tenantId; - private final String tenantName; private final String aicZoneId; @@ -42,13 +32,17 @@ public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { private final Map vnfs; - private final List> instanceParams; + private final Map networks; + + private final Map vnfGroups; private final boolean isPause; private final int bulkSize; - private final boolean rollbackOnFailure; + private final String testApi; + + private final boolean isALaCarte; public ServiceInstantiation(@JsonProperty("modelInfo") ModelInfo modelInfo, @JsonProperty("owningEntityId") String owningEntityId, @@ -58,45 +52,43 @@ public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { @JsonProperty("subscriberName") String subscriberName, @JsonProperty("productFamilyId") String productFamilyId, @JsonProperty("instanceName") String instanceName, - @JsonProperty("isUserProvidedNaming") Boolean isUserProvidedNaming, @JsonProperty("subscriptionServiceType") String subscriptionServiceType, @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("legacyRegion") String legacyRegion, @JsonProperty("tenantId") String tenantId, @JsonProperty("tenantName") String tenantName, @JsonProperty("aicZoneId") String aicZoneId, @JsonProperty("aicZoneName") String aicZoneName, @JsonProperty("vnfs") Map vnfs, + @JsonProperty("networks") Map networks, + @JsonProperty("vnfGroups") Map vnfGroups, @JsonProperty("instanceParams") List> instanceParams, @JsonProperty("pause") boolean isPause, @JsonProperty("bulkSize") int bulkSize, - @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure, + @JsonProperty("isALaCarte") boolean isALaCarte, + @JsonProperty("testApi") String testApi, + @JsonProperty("instanceId") String instanceId, + @JsonProperty("action") String action ) { - - this.modelInfo = modelInfo; - this.modelInfo.setModelType("service"); + super(modelInfo, instanceName, action, lcpCloudRegionId, legacyRegion, tenantId, instanceParams, rollbackOnFailure, instanceId); this.owningEntityId = owningEntityId; this.owningEntityName = owningEntityName; this.projectName = projectName; this.globalSubscriberId = globalSubscriberId; this.subscriberName = subscriberName; this.productFamilyId = productFamilyId; - this.instanceName = instanceName; - this.isUserProvidedNaming = isUserProvidedNaming; this.subscriptionServiceType = subscriptionServiceType; - this.lcpCloudRegionId = lcpCloudRegionId; - this.tenantId = tenantId; this.tenantName = tenantName; this.aicZoneId = aicZoneId; this.aicZoneName = aicZoneName; this.vnfs = vnfs; - this.instanceParams = instanceParams; + this.networks = networks; + this.vnfGroups = vnfGroups; this.isPause = isPause; this.bulkSize = bulkSize; - this.rollbackOnFailure = rollbackOnFailure; - } - - public ModelInfo getModelInfo() { - return modelInfo; + this.isALaCarte = isALaCarte; + this.testApi = isALaCarte ? testApi : null; } public String getOwningEntityId() { @@ -123,25 +115,10 @@ public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { return productFamilyId; } - public String getInstanceName() { - return instanceName; - } - - @JsonProperty("isUserProvidedNaming") - public Boolean isUserProvidedNaming() { return isUserProvidedNaming; } - public String getSubscriptionServiceType() { return subscriptionServiceType; } - public String getLcpCloudRegionId() { - return lcpCloudRegionId; - } - - public String getTenantId() { - return tenantId; - } - public String getTenantName() { return tenantName; } @@ -155,11 +132,15 @@ public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { } public Map getVnfs() { - return vnfs; + return vnfs == null ? Collections.emptyMap() : vnfs; + } + + public Map getNetworks() { + return networks == null ? Collections.emptyMap() : networks; } - public List> getInstanceParams() { - return instanceParams == null ? Collections.emptyList() : instanceParams; + public Map getVnfGroups() { + return vnfGroups == null ? Collections.emptyMap() : vnfGroups; } public boolean isPause() { @@ -168,7 +149,18 @@ public class ServiceInstantiation implements JobAdapter.AsyncJobRequest { public int getBulkSize() { return bulkSize; } - public boolean isRollbackOnFailure() { - return rollbackOnFailure; + @Override + protected String getModelType() { + return "service"; + } + + @JsonProperty("isALaCarte") + public boolean isALaCarte() { + return isALaCarte; } + + public String getTestApi() { + return this.testApi; + } + } \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java index f63fb336..b930ba4d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/VfModule.java @@ -22,10 +22,9 @@ package org.onap.vid.model.serviceInstantiation; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.StringUtils; -import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.mso.model.ModelInfo; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -34,42 +33,47 @@ import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; /** * The Class VfModule. */ -public class VfModule { +@JsonInclude(NON_NULL) +public class VfModule extends BaseResource implements JobAdapter.AsyncJobRequest { - - - private final ModelInfo modelInfo; - - @JsonInclude(NON_NULL) private final String instanceName; - - private final List> instanceParams; @JsonInclude(NON_NULL) private final String volumeGroupInstanceName; - - public VfModule(@JsonProperty("modelInfo") ModelInfo modelInfo, - @JsonProperty("instanceName") String instanceName, - @JsonProperty(value = "volumeGroupName") String volumeGroupInstanceName, - @JsonProperty("instanceParams") List> instanceParams) { - this.modelInfo = modelInfo; - this.modelInfo.setModelType("vfModule"); - this.instanceName = instanceName; - this.instanceParams = instanceParams; + private boolean usePreload; + private Map supplementaryParams; + + public VfModule( @JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("volumeGroupName") String volumeGroupInstanceName, + @JsonProperty("action") String action, + @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("legacyRegion") String legacyRegion, + @JsonProperty("tenantId") String tenantId, + @JsonProperty("instanceParams") List> instanceParams, + @JsonProperty("supplementaryFileContent") Map supplementaryParams, + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure, + @JsonProperty("sdncPreLoad") boolean usePreload, + @JsonProperty("instanceId") String instanceId) { + super(modelInfo, instanceName, action, lcpCloudRegionId, legacyRegion, tenantId, instanceParams, rollbackOnFailure, instanceId); this.volumeGroupInstanceName = volumeGroupInstanceName; + this.usePreload = usePreload; + this.supplementaryParams = supplementaryParams; } - public ModelInfo getModelInfo() { - return modelInfo; + public String getVolumeGroupInstanceName() { + return volumeGroupInstanceName; } - public String getInstanceName() { - return instanceName; + public boolean isUsePreload() { + return usePreload; } - public String getVolumeGroupInstanceName() { - return volumeGroupInstanceName; + public Map getSupplementaryParams() { + return supplementaryParams; } - public List> getInstanceParams() { - return instanceParams == null ? Collections.emptyList() : instanceParams; + @Override + protected String getModelType() { + return "vfModule"; } + } \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java index 621754d1..3856e889 100644 --- a/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java +++ b/vid-app-common/src/main/java/org/onap/vid/model/serviceInstantiation/Vnf.java @@ -22,99 +22,64 @@ package org.onap.vid.model.serviceInstantiation; import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang3.StringUtils; -import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.mso.model.ModelInfo; -import java.util.Collections; import java.util.List; import java.util.Map; /** * The Class VNF. */ -public class Vnf { - private final ModelInfo modelInfo; +public class Vnf extends BaseResource implements JobAdapter.AsyncJobRequest { private final String productFamilyId; - private final String instanceName; - private final String platformName; - private final String lcpCloudRegionId; - - private final String tenantId; - - private final Boolean isUserProvidedNaming; - - private final List> instanceParams; - private final String lineOfBusiness; - private final Map> vfModules; public Vnf(@JsonProperty("modelInfo") ModelInfo modelInfo, - @JsonProperty("productFamilyId") String productFamilyId, - @JsonProperty("instanceName") String instanceName, - @JsonProperty("isUserProvidedNaming") Boolean isUserProvidedNaming, - @JsonProperty("platformName") String platformName, - @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, - @JsonProperty("tenantId") String tenantId, - @JsonProperty("instanceParams") List> instanceParams, - @JsonProperty("lineOfBusinessName") String lineOfBusiness, - @JsonProperty("vfModules") Map> vfModules) { - this.modelInfo = modelInfo; - this.modelInfo.setModelType("vnf"); + @JsonProperty("productFamilyId") String productFamilyId, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("action") String action, + @JsonProperty("platformName") String platformName, + @JsonProperty("lcpCloudRegionId") String lcpCloudRegionId, + @JsonProperty("legacyRegion") String legacyRegion, + @JsonProperty("tenantId") String tenantId, + @JsonProperty("instanceParams") List> instanceParams, + @JsonProperty("lineOfBusinessName") String lineOfBusiness, + @JsonProperty("rollbackOnFailure") boolean rollbackOnFailure, + @JsonProperty("instanceId") String instanceId, + @JsonProperty("vfModules") Map> vfModules) { + + super(modelInfo, instanceName, action, lcpCloudRegionId, legacyRegion, tenantId, instanceParams, rollbackOnFailure, instanceId); this.productFamilyId = productFamilyId; - this.instanceName = instanceName; - this.isUserProvidedNaming = isUserProvidedNaming; this.platformName = platformName; - this.lcpCloudRegionId = lcpCloudRegionId; - this.tenantId = tenantId; - this.instanceParams = instanceParams; - this.vfModules = vfModules; this.lineOfBusiness = lineOfBusiness; - } - - public ModelInfo getModelInfo() { - return modelInfo; + this.vfModules = vfModules; } public String getProductFamilyId() { return productFamilyId; } - public String getInstanceName() { - return instanceName; - } - - @JsonProperty("isUserProvidedNaming") - public Boolean isUserProvidedNaming() { - return isUserProvidedNaming; - } - public String getPlatformName() { return platformName; } - public String getLcpCloudRegionId() { - return lcpCloudRegionId; - } - - public String getTenantId() { - return tenantId; - } - - public List> getInstanceParams() { - return instanceParams == null ? Collections.emptyList() : instanceParams; + public String getLineOfBusiness() { + return lineOfBusiness; } public Map> getVfModules() { return vfModules; } - public String getLineOfBusiness() { - return lineOfBusiness; + @Override + protected String getModelType() { + return "vnf"; } } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java index 0ecb9257..ef45d5ce 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogic.java @@ -1,7 +1,8 @@ package org.onap.vid.mso; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.controllers.OperationalEnvironmentController; +import org.onap.vid.controller.OperationalEnvironmentController; +import org.onap.vid.model.SoftDeleteRequest; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; @@ -17,9 +18,9 @@ public interface MsoBusinessLogic { MsoResponseWrapper createSvcInstance(RequestDetails msoRequest); MsoResponseWrapper createE2eSvcInstance(Object msoRequest); - + MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String serviceInstanceId); - + MsoResponseWrapper createVnf(RequestDetails requestDetails, String serviceInstanceId); MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String serviceInstanceId); @@ -102,4 +103,15 @@ public interface MsoBusinessLogic { RequestDetailsWrapper generateInPlaceMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails); RequestDetailsWrapper generateConfigMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails); + + String getActivateFabricConfigurationPath(String serviceInstanceId); + + String getDeactivateAndCloudDeletePath(String serviceInstanceId, String vnfInstanceId, String vfModuleInstanceId); + + RequestDetails buildRequestDetailsForSoftDelete(SoftDeleteRequest softDeleteRequest); + + MsoResponseWrapper2 deactivateAndCloudDelete(String serviceInstanceId, String vnfInstanceId, String vfModuleInstanceId, RequestDetails requestDetails); + + MsoResponseWrapper2 activateFabricConfiguration(String serviceInstanceId, RequestDetails requestDetails); + } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java index a6226e00..7fe79b39 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java @@ -26,24 +26,22 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.controllers.OperationalEnvironmentController; -import org.onap.vid.domain.mso.RequestInfo; +import org.onap.vid.controller.OperationalEnvironmentController; import org.onap.vid.exceptions.GenericUncheckedException; -import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; -import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.SoftDeleteRequest; +import org.onap.vid.mso.model.*; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; import org.onap.vid.mso.rest.*; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.togglz.core.manager.FeatureManager; import javax.ws.rs.BadRequestException; import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -53,7 +51,7 @@ import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.StringUtils.upperCase; import static org.onap.vid.changeManagement.ChangeManagementRequest.MsoChangeManagementRequest; -import static org.onap.vid.controllers.MsoController.*; +import static org.onap.vid.controller.MsoController.*; import static org.onap.vid.mso.MsoProperties.*; import static org.onap.vid.properties.Features.FLAG_UNASSIGN_SERVICE; import static org.onap.vid.utils.Logging.debugRequestDetails; @@ -68,16 +66,14 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { .map(requestType -> requestType.toString().toUpperCase()) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); private static final String RESOURCE_TYPE = "resourceType"; - /** - * The Constant dateFormat. - */ - private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); private static final Pattern SOFTWARE_VERSION_PATTERN = Pattern.compile("^[A-Za-z0-9.\\-]+$"); private static final Pattern NUMBER_PATTERN = Pattern.compile("^[0-9]+$"); private static final String ACTIVATE = "/activate"; private static final String DEACTIVATE = "/deactivate"; private static final String ENABLE_PORT = "/enablePort"; private static final String DISABLE_PORT = "/disablePort"; + private static final String ACTIVATE_FABRIC_CONFIGURATION = "/activateFabricConfiguration"; + private static final String DEACTIVATE_AND_CLOUD_DELETE = "/deactivateAndCloudDelete"; private static final String RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT = "operationalEnvironment"; private static final String SOURCE_OPERATIONAL_ENVIRONMENT = "VID"; private static final ObjectMapper objectMapper = new ObjectMapper(); @@ -130,8 +126,8 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - return msoClientInterface.createVnf(requestDetails, vnf_endpoint); + String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + return msoClientInterface.createVnf(requestDetails, vnfEndpoint); } @Override @@ -150,10 +146,10 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - vnf_endpoint = vnf_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnfEndpoint = vnfEndpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); - return msoClientInterface.createVolumeGroupInstance(requestDetails, vnf_endpoint); + return msoClientInterface.createVolumeGroupInstance(requestDetails, vnfEndpoint); } @Override @@ -232,10 +228,10 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { logInvocationInDebug("deleteVnf"); String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - vnf_endpoint = vnf_endpoint + '/' + vnfInstanceId; + String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnfEndpoint = vnfEndpoint + '/' + vnfInstanceId; - return msoClientInterface.deleteVnf(requestDetails, vnf_endpoint); + return msoClientInterface.deleteVnf(requestDetails, vnfEndpoint); } @Override @@ -255,8 +251,8 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - String vnf_endpoint = svc_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); - String delete_volume_group_endpoint = vnf_endpoint + "/" + volumeGroupId; + String vnfEndpoint = svc_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + String delete_volume_group_endpoint = vnfEndpoint + "/" + volumeGroupId; return msoClientInterface.deleteVolumeGroupInstance(requestDetails, delete_volume_group_endpoint); } @@ -341,7 +337,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { RestObject restObjStr = new RestObject<>(); String str = new String(); restObjStr.set(str); - MsoResponseWrapper msoResponseWrapper = msoClientInterface.getOrchestrationRequestsForDashboard(str, "", orchestrationReqPath, restObjStr); + MsoResponseWrapper msoResponseWrapper = msoClientInterface.getOrchestrationRequest(str, "", orchestrationReqPath, restObjStr, true); return deserializeOrchestrationRequestsJson(msoResponseWrapper.getEntity()); } @@ -447,9 +443,9 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { String endpoint; endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - vnf_endpoint = vnf_endpoint + '/' + vnfInstanceId; - return msoClientInterface.updateVnf(requestDetails, vnf_endpoint); + String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnfEndpoint = vnfEndpoint + '/' + vnfInstanceId; + return msoClientInterface.updateVnf(requestDetails, vnfEndpoint); } @Override @@ -457,10 +453,10 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { logInvocationInDebug("replaceVnf"); String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - vnf_endpoint = vnf_endpoint.replace(VNF_INSTANCE_ID, vnfInstanceId); - vnf_endpoint = vnf_endpoint.replace(REQUEST_TYPE, MsoChangeManagementRequest.REPLACE); - return msoClientInterface.replaceVnf(requestDetails, vnf_endpoint); + String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnfEndpoint = vnfEndpoint.replace(VNF_INSTANCE_ID, vnfInstanceId); + vnfEndpoint = vnfEndpoint.replace(REQUEST_TYPE, MsoChangeManagementRequest.REPLACE); + return msoClientInterface.replaceVnf(requestDetails, vnfEndpoint); } public RequestDetailsWrapper generateInPlaceMsoRequest(org.onap.vid.changeManagement.RequestDetails requestDetails) { @@ -485,28 +481,83 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { return requestDetailsWrapper; } + @Override + public String getActivateFabricConfigurationPath(String serviceInstanceId) { + String path = validateEndpointPath(MsoProperties.MSO_REST_API_SERVICE_INSTANCE_CREATE); + path += "/" + serviceInstanceId + ACTIVATE_FABRIC_CONFIGURATION; + + return path; + } + + @Override + public String getDeactivateAndCloudDeletePath(String serviceInstanceId, String vnfInstanceId, String vfModuleInstanceId) { + String path = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + path = path.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + path = path.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + path += "/" + vfModuleInstanceId + DEACTIVATE_AND_CLOUD_DELETE; + + return path; + } + + @Override + public RequestDetails buildRequestDetailsForSoftDelete(SoftDeleteRequest softDeleteRequest) { + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSource("VID"); + requestInfo.setRequestorId(softDeleteRequest.getUserId()); + requestDetails.setRequestInfo(requestInfo); + + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setTenantId(softDeleteRequest.getTenantId()); + cloudConfiguration.setLcpCloudRegionId(softDeleteRequest.getLcpCloudRegionId()); + requestDetails.setCloudConfiguration(cloudConfiguration); + + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType("vfModule"); + requestDetails.setModelInfo(modelInfo); + + RequestParameters requestParameters = new RequestParameters(); + requestParameters.setTestApi("GR_API"); + requestDetails.setRequestParameters(requestParameters); + + return requestDetails; + } + + @Override + public MsoResponseWrapper2 deactivateAndCloudDelete(String serviceInstanceId, String vnfInstanceId, String vfModuleInstanceId, RequestDetails requestDetails) { + String path = getDeactivateAndCloudDeletePath(serviceInstanceId, vnfInstanceId, vfModuleInstanceId); + return new MsoResponseWrapper2<>(msoClientInterface.post(path, new RequestDetailsWrapper<>(requestDetails), RequestReferencesContainer.class)); + } + + @Override + public MsoResponseWrapper2 activateFabricConfiguration(String serviceInstanceId, RequestDetails requestDetails) { + String path = getActivateFabricConfigurationPath(serviceInstanceId); + return new MsoResponseWrapper2<>(msoClientInterface.post(path, new RequestDetailsWrapper<>(requestDetails), RequestReferencesContainer.class)); + } + + @Override public MsoResponseWrapperInterface updateVnfSoftware(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { logInvocationInDebug("updateVnfSoftware"); - String vnf_endpoint = getChangeManagementEndpoint(serviceInstanceId, vnfInstanceId, MsoChangeManagementRequest.SOFTWARE_UPDATE); //workflow name in mso is different than workflow name in vid UI + String vnfEndpoint = getChangeManagementEndpoint(serviceInstanceId, vnfInstanceId, MsoChangeManagementRequest.SOFTWARE_UPDATE); //workflow name in mso is different than workflow name in vid UI RequestDetailsWrapper finalRequestDetails = generateInPlaceMsoRequest(requestDetails); - return msoClientInterface.changeManagementUpdate(finalRequestDetails, vnf_endpoint); + return msoClientInterface.changeManagementUpdate(finalRequestDetails, vnfEndpoint); } @Override public MsoResponseWrapperInterface updateVnfConfig(org.onap.vid.changeManagement.RequestDetails requestDetails, String serviceInstanceId, String vnfInstanceId) { logInvocationInDebug("updateVnfConfig"); RequestDetailsWrapper finalRequestDetails = generateConfigMsoRequest(requestDetails); - String vnf_endpoint = getChangeManagementEndpoint(serviceInstanceId, vnfInstanceId, MsoChangeManagementRequest.CONFIG_UPDATE); - return msoClientInterface.changeManagementUpdate(finalRequestDetails, vnf_endpoint); + String vnfEndpoint = getChangeManagementEndpoint(serviceInstanceId, vnfInstanceId, MsoChangeManagementRequest.CONFIG_UPDATE); + return msoClientInterface.changeManagementUpdate(finalRequestDetails, vnfEndpoint); } private String getChangeManagementEndpoint(String serviceInstanceId, String vnfInstanceId, String vnfRequestType) { String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); - vnf_endpoint = vnf_endpoint.replace(VNF_INSTANCE_ID, vnfInstanceId); - vnf_endpoint = vnf_endpoint.replace(REQUEST_TYPE, vnfRequestType); - return vnf_endpoint; + String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + vnfEndpoint = vnfEndpoint.replace(VNF_INSTANCE_ID, vnfInstanceId); + vnfEndpoint = vnfEndpoint.replace(REQUEST_TYPE, vnfRequestType); + return vnfEndpoint; } private Map getChangeManagementPayload(RequestDetails requestDetails, String message) { @@ -598,8 +649,8 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { return MsoUtil.wrapResponse(restObjStr); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString()); throw e; } } @@ -632,13 +683,13 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { requestInfo.setRequestorId(details.getUserId()); requestDetails.setRequestInfo(requestInfo); - org.onap.vid.domain.mso.RelatedInstance relatedInstance = new org.onap.vid.domain.mso.RelatedInstance(); + RelatedInstance relatedInstance = new RelatedInstance(); relatedInstance.setAdditionalProperty(RESOURCE_TYPE, RESOURCE_TYPE_OPERATIONAL_ENVIRONMENT); relatedInstance.setInstanceId(details.getRelatedInstanceId()); relatedInstance.setInstanceName(details.getRelatedInstanceName()); requestDetails.setAdditionalProperty("relatedInstanceList", Collections.singletonList(ImmutableMap.of("relatedInstance", relatedInstance))); - org.onap.vid.domain.mso.RequestParameters requestParameters = new org.onap.vid.domain.mso.RequestParameters(); + RequestParameters requestParameters = new RequestParameters(); requestParameters.setUserParams(null); requestParameters.setAdditionalProperty("operationalEnvironmentType", "VNF"); requestParameters.setAdditionalProperty("workloadContext", details.getWorkloadContext()); @@ -669,7 +720,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { requestInfo.setRequestorId(details.getUserId()); requestDetails.setRequestInfo(requestInfo); - org.onap.vid.domain.mso.RequestParameters requestParameters = new org.onap.vid.domain.mso.RequestParameters(); + RequestParameters requestParameters = new RequestParameters(); requestParameters.setUserParams(null); requestParameters.setAdditionalProperty("operationalEnvironmentType", "VNF"); requestDetails.setRequestParameters(requestParameters); @@ -760,12 +811,12 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } private void logInvocationInDebug(String methodName) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); } private void logException(String methodName, Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString()); } enum RequestType { @@ -781,6 +832,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { SCALE_OUT("scaleOut"), UNKNOWN("unknown"), NOT_PROVIDED("not provided"); + private final String value; private static final Map CONSTANTS = new HashMap<>(); static { @@ -789,8 +841,6 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { } } - private final String value; - RequestType(String value) { this.value = value; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java index 7c8ab89c..41400f97 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java @@ -20,15 +20,10 @@ */ package org.onap.vid.mso; -import com.fasterxml.jackson.core.JsonProcessingException; import io.joshworks.restclient.http.HttpResponse; -import io.joshworks.restclient.http.mapper.ObjectMapper; -import org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.mso.rest.RequestDetails; -import java.io.IOException; - /** * Created by pickjonathan on 21/06/2017. */ @@ -43,7 +38,7 @@ public interface MsoInterface { * @throws Exception */ MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint); - + //For VoLTE E2E services MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint); MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint); @@ -90,19 +85,19 @@ public interface MsoInterface { MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint); - MsoResponseWrapper getOrchestrationRequest(String endpoint); + MsoResponseWrapper getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject, boolean warpException); - MsoResponseWrapper getOrchestrationRequestsForDashboard(String t , String sourceId , String endpoint , RestObject restObject); + MsoResponseWrapper getOrchestrationRequest(String endpoint); MsoResponseWrapper getManualTasksByRequestId(String t , String sourceId , String endpoint , RestObject restObject); MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject); - MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint); + MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnfEndpoint); - MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnf_endpoint); + MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String vnfEndpoint); - MsoResponseWrapper deleteConfiguration(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String pmc_endpoint); + MsoResponseWrapper deleteConfiguration(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String pmcEndpoint); MsoResponseWrapper setConfigurationActiveStatus(RequestDetails requestDetails, String endpoint); @@ -120,29 +115,5 @@ public interface MsoInterface { HttpResponse post(String path, RequestDetailsWrapper requestDetailsWrapper, Class responseClass); - - static ObjectMapper objectMapper() { - return new ObjectMapper() { - CustomJacksonJaxBJsonProvider mapper = new CustomJacksonJaxBJsonProvider(); - - @Override - public T readValue(String s, Class aClass) { - try { - return mapper.getMapper().readValue(s, aClass); - } catch (IOException e) { - throw new MsoException(e); - } - } - - @Override - public String writeValue(Object o) { - try { - return mapper.getMapper().writeValueAsString(o); - } catch (JsonProcessingException e) { - throw new MsoException(e); - } - } - }; - } } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java index 1d71e9c7..1039a29d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoProperties.java @@ -20,12 +20,8 @@ package org.onap.vid.mso; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - /** * The Class MsoProperties. */ @@ -71,7 +67,7 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_REST_API_SVC_INSTANCE. */ public static final String MSO_REST_API_E2E_SVC_INSTANCE = "mso.restapi.svc.e2einstance"; // /e2eServiceInstances/v3 - + /** The Constant MSO_REST_API_SVC_INSTANCE. */ public static final String MSO_REST_API_SVC_INSTANCE = "mso.restapi.svc.instance"; // /serviceInstances/v2 @@ -79,13 +75,13 @@ public class MsoProperties extends SystemProperties { public static final String MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE = "mso.restapi.svc.instance.deleteAndUnassign"; /** The Constant MSO_REST_API_VNF_INSTANCE. */ - public static final String MSO_REST_API_VNF_INSTANCE = "mso.restapi.vnf.instance"; // /serviceInstances/v2/{service_instance_id}/vnfs + public static final String MSO_REST_API_VNF_INSTANCE = "mso.restapi.vnf.instance"; /** The Constant MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE. */ - public static final String MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE = "mso.restapi.vnf.changemanagement.instance"; // /serviceInstances/v2/{service_instance_id}/vnfs/{request_type} + public static final String MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE = "mso.restapi.vnf.changemanagement.instance"; /** The Constant MSO_REST_API_NETWORK_INSTANCE. */ - public static final String MSO_REST_API_NETWORK_INSTANCE = "mso.restapi.network.instance"; // /serviceInstances/v2/{serviceInstanceId}/networks + public static final String MSO_REST_API_NETWORK_INSTANCE = "mso.restapi.network.instance"; /** The Constant MSO_REST_API_GET_ORC_REQ. */ public static final String MSO_REST_API_GET_ORC_REQ = "mso.restapi.get.orc.req"; @@ -102,11 +98,14 @@ public class MsoProperties extends SystemProperties { public static final String MSO_REST_API_VF_MODULE_SCALE_OUT = "mso.restapi.vf.module.scaleout"; /** The Constant MSO_REST_API_VOLUME_GROUP_INSTANCE. */ - public static final String MSO_REST_API_VOLUME_GROUP_INSTANCE = "mso.restapi.volume.group.instance"; //serviceInstances/v2/{serviceInstanceId}/volumeGroups + public static final String MSO_REST_API_VOLUME_GROUP_INSTANCE = "mso.restapi.volume.group.instance"; + + /** The Constant MSO_REST_API_VOLUME_GROUP_INSTANCE. */ + public static final String MSO_REST_API_INSTANCE_GROUP = "mso.restapi.instance.group"; /** The Constant MSO_REST_API_CONFIGURATION_INSTANCE. */ - public static final String MSO_REST_API_CONFIGURATIONS = "mso.restapi.configurations"; //serviceInstances/v5/{serviceInstanceId}/configurations - public static final String MSO_REST_API_CONFIGURATION_INSTANCE = "mso.restapi.configuration.instance"; //serviceInstances/v5/{serviceInstanceId}/configurations/{configurationId} + public static final String MSO_REST_API_CONFIGURATIONS = "mso.restapi.configurations"; + public static final String MSO_REST_API_CONFIGURATION_INSTANCE = "mso.restapi.configuration.instance"; /** The Constant MSO_REST_API_OPERATIONAL_ENVIRONMENT */ public static final String MSO_REST_API_OPERATIONAL_ENVIRONMENT_ACTIVATE = "mso.restapi.operationalEnvironment.activate"; @@ -118,10 +117,9 @@ public class MsoProperties extends SystemProperties { /** The Constant MSO_REST_API_CLOUD_RESOURCES_REQUEST_STATUS */ public static final String MSO_REST_API_CLOUD_RESOURCES_REQUEST_STATUS = "mso.restapi.operationalEnvironment.cloudResourcesRequests.status"; - /** The logger. */ - public EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoProperties.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + /** The Constant MSO_REST_API_SERVICE_INSTANCE_CREATE */ + public static final String MSO_REST_API_SERVICE_INSTANCE_CREATE = "mso.restapi.serviceInstanceCreate"; + /** The Constant MSO_REST_API_SERVICE_INSTANCE_ASSIGN */ + public static final String MSO_REST_API_SERVICE_INSTANCE_ASSIGN = "mso.restapi.serviceInstanceAssign"; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper.java index b890114b..5a35e109 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper.java @@ -20,6 +20,7 @@ package org.onap.vid.mso; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @@ -111,8 +112,7 @@ public class MsoResponseWrapper implements MsoResponseWrapperInterface { * * @return the response */ - @org.codehaus.jackson.annotate.JsonIgnore - @com.fasterxml.jackson.annotation.JsonIgnore + @JsonIgnore public String getResponse () { StringBuilder b = new StringBuilder ("{ \"status\": "); diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java index 2372e7fb..fff14ebc 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java @@ -20,6 +20,7 @@ */ package org.onap.vid.mso; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonProcessingException; @@ -38,7 +39,7 @@ The serialized "entity" field may be either String or nested object. */ public class MsoResponseWrapper2 implements MsoResponseWrapperInterface { - final static ObjectMapper objectMapper = new ObjectMapper(); + static final ObjectMapper objectMapper = new ObjectMapper(); private final int status; private final T entity; @@ -69,8 +70,7 @@ public class MsoResponseWrapper2 implements MsoResponseWrapperInterface { } @Override - @org.codehaus.jackson.annotate.JsonIgnore - @com.fasterxml.jackson.annotation.JsonIgnore + @JsonIgnore public String getResponse() { try { return objectMapper.writeValueAsString(this); diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapperInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapperInterface.java index ad251bde..e293398f 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapperInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapperInterface.java @@ -1,5 +1,6 @@ package org.onap.vid.mso; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public interface MsoResponseWrapperInterface { @@ -9,7 +10,6 @@ public interface MsoResponseWrapperInterface { @JsonProperty("status") int getStatus(); - @org.codehaus.jackson.annotate.JsonIgnore - @com.fasterxml.jackson.annotation.JsonIgnore + @JsonIgnore String getResponse(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java index 722a1c4c..999188ff 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java @@ -3,14 +3,13 @@ * VID * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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. @@ -28,9 +27,6 @@ import org.apache.commons.lang3.ObjectUtils; import org.glassfish.jersey.client.ClientResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import java.text.DateFormat; -import java.text.SimpleDateFormat; - import static org.onap.vid.utils.Logging.getMethodName; /** @@ -40,10 +36,7 @@ public class MsoUtil { /** The logger. */ private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoUtil.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - + /** * Wrap response. * @@ -67,12 +60,13 @@ public class MsoUtil { * @return the mso response wrapper */ public static MsoResponseWrapper wrapResponse (ClientResponse cres) { - String resp_str = ""; + String respStr = ""; + int statuscode = 0; if ( cres != null ) { - resp_str = cres.readEntity(String.class); + respStr = cres.readEntity(String.class); + statuscode = cres.getStatus(); } - int statuscode = cres.getStatus(); - MsoResponseWrapper w = MsoUtil.wrapResponse ( resp_str, statuscode ); + MsoResponseWrapper w = MsoUtil.wrapResponse ( respStr, statuscode ); return (w); } @@ -83,16 +77,16 @@ public class MsoUtil { * @return the mso response wrapper */ public static MsoResponseWrapper wrapResponse (RestObject rs) { - String resp_str = null; + String respStr = null; int status = 0; if ( rs != null ) { - resp_str = rs.get() != null ? rs.get() : rs.getRaw(); + respStr = rs.get() != null ? rs.get() : rs.getRaw(); status = rs.getStatusCode(); } - MsoResponseWrapper w = MsoUtil.wrapResponse ( resp_str, status ); + MsoResponseWrapper w = MsoUtil.wrapResponse ( respStr, status ); return (w); - } - + } + public static MsoResponseWrapper wrapResponse (HttpResponse rs) { MsoResponseWrapper w = new MsoResponseWrapper(); w.setStatus (rs.getStatus()); @@ -111,19 +105,17 @@ public class MsoUtil { * @throws JsonProcessingException the json processing exception */ public static String convertPojoToString ( T t ) { - - String methodName = "convertPojoToString"; ObjectMapper mapper = new ObjectMapper(); - String r_json_str = ""; + String rJsonStr = ""; if ( t != null ) { try { - r_json_str = mapper.writeValueAsString(t); + rJsonStr = mapper.writeValueAsString(t); } catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { logger.debug(EELFLoggerDelegate.debugLogger,getMethodName() + " Unable to parse object of type " + t.getClass().getName() + " as json", j); } } - return (r_json_str); + return (rJsonStr); } /** diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java index 0494facd..31836f66 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java @@ -3,15 +3,17 @@ package org.onap.vid.mso; import com.att.eelf.configuration.EELFLogger; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpException; import org.eclipse.jetty.util.security.Password; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.util.HttpClientMode; import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.client.HttpBasicClient; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.mso.rest.RestInterface; import org.onap.vid.utils.Logging; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; @@ -21,53 +23,44 @@ import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Collections; -import java.util.Date; -import java.util.UUID; +import java.util.Optional; import static org.onap.vid.utils.Logging.*; /** * Created by pickjonathan on 26/06/2017. */ -public class RestMsoImplementation implements RestInterface { - - public static final String START_LOG = " start"; - public static final String APPLICATION_JSON = "application/json"; - public static final String WITH_STATUS = " with status="; - public static final String URL_LOG = ", url="; - public static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e="; - public static final String WITH_URL_LOG = " with url="; - public static final String EXCEPTION_LOG = ", Exception: "; - public static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!"; - public static final String REST_API_POST_WAS_SUCCESSFUL_LOG = " REST api POST was successful!"; +public abstract class RestMsoImplementation implements RestInterface { + /** * The logger. */ - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class); + protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMsoImplementation.class); private final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("mso"); - /** - * The Constant dateFormat. - */ - static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - /** The client. */ private Client client = null; @Autowired - HttpsAuthClient httpsAuthClient; - + protected HttpsAuthClient httpsAuthClient; + + private static final String START_LOG = " start"; + private static final String APPLICATION_JSON = "application/json"; + private static final String WITH_STATUS = " with status="; + private static final String URL_LOG = ", url="; + private static final String NO_RESPONSE_ENTITY_LOG = " No response entity, this is probably ok, e="; + private static final String WITH_URL_LOG = " with url="; + private static final String EXCEPTION_LOG = ", Exception: "; + private static final String REST_API_SUCCESSFULL_LOG = " REST api was successfull!"; + private static final String REST_MSG_TEMPLATE = "start {}->{}({}, {}, {})"; /** The common headers. */ /** * Instantiates a new mso rest interface. */ @SuppressWarnings("Duplicates") - @Override - public MultivaluedHashMap initMsoClient() + protected MultivaluedHashMap initMsoClient() { final String methodname = "initRestClient()"; @@ -83,15 +76,11 @@ public class RestMsoImplementation implements RestInterface { MultivaluedHashMap commonHeaders = new MultivaluedHashMap(); commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc))); - //Pass calling application identifier to SO - commonHeaders.put("X-FromAppId", Collections.singletonList(SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME))); - try { - commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(Logging.extractOrGenerateRequestId())); - } - catch (IllegalStateException e){ - //in async jobs we don't have any HttpServletRequest - commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(UUID.randomUUID().toString())); - } + commonHeaders.put("X-ONAP-PartnerName", Collections.singletonList("VID")); + + String requestIdValue = Logging.extractOrGenerateRequestId(); + commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue)); + commonHeaders.put(ONAP_REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue)); boolean useSsl = true; @@ -108,54 +97,65 @@ public class RestMsoImplementation implements RestInterface { client = HttpBasicClient.getClient(); } } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodname + " Unable to get the SSL client"); + logger.info(EELFLoggerDelegate.errorLogger,methodname + " Unable to get the SSL client"); } } return commonHeaders; } - public void Get (T t, String sourceId, String path, RestObject restObject ) { + public RestObjectWithRequestInfo Get(T t, String path, RestObject restObject, boolean warpException) { String methodName = "Get"; logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_LOG); - String url=""; - restObject.set(t); + String url = null; + String rawData = null; + Integer status = null; - url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; + try { + restObject.set(t); + url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - MultivaluedHashMap commonHeaders = initMsoClient(); - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); - final Response cres = client.target(url) - .request() - .accept(APPLICATION_JSON) - .headers(commonHeaders) - .get(); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); - int status = cres.getStatus(); - restObject.setStatusCode (status); + MultivaluedHashMap commonHeaders = initMsoClient(); + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + final Response cres = client.target(url) + .request() + .accept(APPLICATION_JSON) + .headers(commonHeaders) + .get(); + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); - if (status == 200 || status == 202) { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + REST_API_SUCCESSFULL_LOG); + cres.bufferEntity(); + status = cres.getStatus(); + rawData = cres.readEntity(String.class); - } else { - throw new GenericUncheckedException(methodName + WITH_STATUS + status + ", url= " + url ); - } + restObject.setStatusCode(status); - logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); + if (status == 200 || status == 202) { + t = (T) cres.readEntity(t.getClass()); + restObject.set(t); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG); - return; + } else { + throw new GenericUncheckedException(new HttpException(methodName + WITH_STATUS + status + " (200 or 202 expected), url= " + url)); + } + + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " received status=" + status); + + return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData); + } catch (RuntimeException e) { + throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e) : e; + } } - public RestObject GetForObject(String sourceID, String path, Class clazz) { + @Override + public RestObject GetForObject(String path, Class clazz) { final String methodName = getMethodName(); - logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {}, {})", getMethodCallerName(), methodName, sourceID, path, clazz); + logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz); String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " sending request to url= " + url); MultivaluedHashMap commonHeaders = initMsoClient(); Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); @@ -169,9 +169,9 @@ public class RestMsoImplementation implements RestInterface { int status = cres.getStatus(); if (status == 200 || status == 202) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + REST_API_SUCCESSFULL_LOG); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG); } else { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +status+ URL_LOG +url); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url); } logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); @@ -180,13 +180,13 @@ public class RestMsoImplementation implements RestInterface { } @Override - public void Delete(T t, Object r, String sourceID, String path, RestObject restObject) { + public void Delete(T t, Object r, String path, RestObject restObject) { String methodName = "Delete"; String url=""; - Response cres = null; + Response cres; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + START_LOG); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG); try { MultivaluedHashMap commonHeaders = initMsoClient(); @@ -206,16 +206,16 @@ public class RestMsoImplementation implements RestInterface { if (status == 404) { // resource not found String msg = "Resource does not exist...: " + cres.getStatus(); - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg); } else if (status == 200 || status == 204){ - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted"); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + "Resource " + url + " deleted"); } else if (status == 202) { - String msg = "Delete in progress: " + status; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + String msg = "Delete in progress: " + status; + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg); } else { String msg = "Deleting Resource failed: " + status; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg); } try { @@ -223,37 +223,40 @@ public class RestMsoImplementation implements RestInterface { restObject.set(t); } catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + NO_RESPONSE_ENTITY_LOG + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG + e.getMessage()); } } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); throw e; } } - public RestObject PostForObject(Object requestDetails, String sourceID, String path, Class clazz) { - logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {}, {}, {})", getMethodCallerName(), getMethodName(), requestDetails, sourceID, path, clazz); - RestObject restObject = new RestObject<>(); - Post(clazz, requestDetails, path, restObject); - return restObject; + public RestObject PostForObject(Object requestDetails, String path, Class clazz) { + logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz); + return restCall(HttpMethod.POST, clazz, requestDetails, path); + } + + public RestObject DeleteForObject(Object requestDetails, String path, Class clazz) { + logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz); + return restCall(HttpMethod.DELETE, clazz, requestDetails, path); } @Override - public void Post(T t, Object r, String sourceID, String path, RestObject restObject) { - logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {}, {}, {})", getMethodCallerName(), getMethodName(), t.getClass(), r, sourceID, path); - Post(t.getClass(), r, path, restObject); + public void Post(String t, Object r, String path, RestObject restObject) { + logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), t.getClass(), r, path); + restObject.copyFrom(restCall(HttpMethod.POST, String.class, r, path)); } public Invocation.Builder prepareClient(String path, String methodName) { MultivaluedHashMap commonHeaders = initMsoClient(); String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + " sending request to url= " + url); // Change the content length return client.target(url) .request() @@ -261,49 +264,44 @@ public class RestMsoImplementation implements RestInterface { .headers(commonHeaders); } + public RestObject restCall(HttpMethod httpMethod, Class tClass, Object payload, String path) { + return restCall(httpMethod, tClass, payload, path, Optional.empty()); + } - public void Post(Class tClass, Object requestDetails, String path, RestObject restObject) { - String methodName = "Post"; + /* + user id is needed to be pass as X-RequestorID in new MSO flows like Delete instanceGroup + */ + public RestObject restCall(HttpMethod httpMethod, Class tClass, Object payload, String path, Optional userId) { + String methodName = httpMethod.name(); String url=""; try { MultivaluedHashMap commonHeaders = initMsoClient(); + userId.ifPresent(id->commonHeaders.put("X-RequestorID", Collections.singletonList(id))); url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - Logging.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, requestDetails); + Logging.logRequest(outgoingRequestsLogger, httpMethod, url, payload); // Change the content length - final Response cres = client.target(url) + final Invocation.Builder restBuilder = client.target(url) .request() .accept(APPLICATION_JSON) - .headers(commonHeaders) - .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres); - final RestObject cresToRestObject = cresToRestObject(cres, tClass); - restObject.set(cresToRestObject.get()); - restObject.setStatusCode(cresToRestObject.getStatusCode()); - restObject.setRaw(cresToRestObject.getRaw()); - - int status = cres.getStatus(); - restObject.setStatusCode (status); + .headers(commonHeaders); - if ( status >= 200 && status <= 299 ) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); - - } else { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +status+ URL_LOG +url); - } + Invocation restInvocation = payload==null ? + restBuilder.build(httpMethod.name()) : + restBuilder.build(httpMethod.name(), Entity.entity(payload, MediaType.APPLICATION_JSON)); + final Response cres = restInvocation.invoke(); - } catch (Exception e) - { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); + Logging.logResponse(outgoingRequestsLogger, httpMethod, url, cres); + return cresToRestObject(cres, tClass); + } + catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); throw e; - } - logger.debug(EELFLoggerDelegate.debugLogger, "end {}() => ({}){}", getMethodName(), tClass, restObject); } private RestObject cresToRestObject(Response cres, Class tClass) { @@ -319,10 +317,10 @@ public class RestMsoImplementation implements RestInterface { } catch ( Exception e ) { try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e=" + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e=" + e.getMessage() + ", Entity=" + rawEntity); } catch (Exception e2) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + NO_RESPONSE_ENTITY_LOG + e.getMessage()); } } @@ -335,12 +333,12 @@ public class RestMsoImplementation implements RestInterface { } @Override - public void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject restObject) { + public void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String path, RestObject restObject) { String methodName = "Put"; String url=""; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + START_LOG); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG); try { @@ -354,7 +352,6 @@ public class RestMsoImplementation implements RestInterface { .accept(APPLICATION_JSON) .headers(commonHeaders) //.header("content-length", 201) - //.header("X-FromAppId", sourceID) .put(Entity.entity(r, MediaType.APPLICATION_JSON)); Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres); @@ -364,7 +361,7 @@ public class RestMsoImplementation implements RestInterface { restObject.set(t); } catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + NO_RESPONSE_ENTITY_LOG + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG + e.getMessage()); } @@ -372,16 +369,16 @@ public class RestMsoImplementation implements RestInterface { restObject.setStatusCode (status); if ( status >= 200 && status <= 299 ) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + REST_API_POST_WAS_SUCCESSFUL_LOG); + logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + REST_API_SUCCESSFULL_LOG); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + REST_API_SUCCESSFULL_LOG); } else { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +status+ URL_LOG +url); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url); } } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); throw e; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/RestObject.java b/vid-app-common/src/main/java/org/onap/vid/mso/RestObject.java index e5024518..7ebecba5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/RestObject.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/RestObject.java @@ -25,9 +25,6 @@ import com.google.common.base.MoreObjects; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import javax.ws.rs.core.Response; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import static org.onap.vid.utils.Logging.getMethodCallerName; @@ -38,9 +35,7 @@ import static org.onap.vid.utils.Logging.getMethodCallerName; */ public class RestObject { - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - final static ObjectMapper objectMapper = new ObjectMapper(); + static final ObjectMapper objectMapper = new ObjectMapper(); /** * Generic version of the RestObject class. @@ -58,6 +53,12 @@ public class RestObject { public RestObject() { } + public void copyFrom(RestObject src) { + set(src.get()); + setRaw(src.getRaw()); + setStatusCode(src.getStatusCode()); + } + public RestObject(Response cres, Class tClass, EELFLoggerDelegate logger) { String rawEntity = null; @@ -70,10 +71,10 @@ public class RestObject { catch ( Exception e ) { try { this.setRaw(rawEntity); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e=" + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " Error reading response entity as " + tClass + ": , e=" + e.getMessage() + ", Entity=" + rawEntity); } catch (Exception e2) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + getMethodCallerName() + " No response entity, this is probably ok, e=" + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + getMethodCallerName() + " No response entity, this is probably ok, e=" + e.getMessage()); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/RestObjectWithRequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/mso/RestObjectWithRequestInfo.java new file mode 100644 index 00000000..98cc808c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/RestObjectWithRequestInfo.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.mso; + +import org.springframework.http.HttpMethod; + +public class RestObjectWithRequestInfo { + + private final RestObject restObject; + private final String requestedUrl; + private final int httpCode; + private final String rawData; + private final HttpMethod httpMethod; + + public RestObjectWithRequestInfo(HttpMethod httpMethod, String requestedUrl, RestObject restObject, int httpCode, String rawData) { + this.restObject = restObject; + this.requestedUrl = requestedUrl; + this.httpCode = httpCode; + this.rawData = rawData; + this.httpMethod = httpMethod; + } + + public RestObject getRestObject() { + return restObject; + } + + public String getRequestedUrl() { + return requestedUrl; + } + + public int getHttpCode() { + return httpCode; + } + + public String getRawData() { + return rawData; + } + + public HttpMethod getHttpMethod() { + return httpMethod; + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/BaseResourceInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/BaseResourceInstantiationRequestDetails.java new file mode 100644 index 00000000..9ade2abc --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/BaseResourceInstantiationRequestDetails.java @@ -0,0 +1,142 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import java.util.List; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; + +@JsonInclude(NON_NULL) +public class BaseResourceInstantiationRequestDetails { + + @JsonProperty("modelInfo") + protected ModelInfo modelInfo; + + @JsonProperty("cloudConfiguration") + protected CloudConfiguration cloudConfiguration; + + @JsonProperty("requestInfo") + protected RequestInfo requestInfo; + + @JsonProperty("platform") + protected Platform platform; + + @JsonProperty("lineOfBusiness") + protected LineOfBusiness lineOfBusiness; + + @JsonProperty("relatedInstanceList") + protected List relatedInstanceList; + + @JsonProperty("requestParameters") + protected RequestParameters requestParameters; + + public BaseResourceInstantiationRequestDetails(@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "platform", required = true) Platform platform, + @JsonProperty(value = "lineOfBusiness", required = true) LineOfBusiness lineOfBusiness, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) RequestParameters requestParameters) + { + this.modelInfo = modelInfo; + this.cloudConfiguration = cloudConfiguration; + this.requestInfo = requestInfo; + this.platform = platform; + this.lineOfBusiness = lineOfBusiness; + this.relatedInstanceList = relatedInstanceList; + this.requestParameters = requestParameters; + } + + public BaseResourceInstantiationRequestDetails(@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) RequestParameters requestParameters) + { + this.modelInfo = modelInfo; + this.cloudConfiguration = cloudConfiguration; + this.requestInfo = requestInfo; + this.relatedInstanceList = relatedInstanceList; + this.requestParameters = requestParameters; + } + + public static class RequestInfo { + + @JsonInclude(NON_NULL) public final String instanceName; + @JsonInclude(NON_NULL) public final String productFamilyId; + public final String source; + public final boolean suppressRollback; + public final String requestorId; + + public RequestInfo(String instanceName, String productFamilyId, String source, boolean rollbackOnFailure, String requestorId) { + this.instanceName = instanceName; + this.productFamilyId = productFamilyId; + this.source = source; + this.requestorId = requestorId; + // in the FE we are asking for "RollbackOnFailure" but to MSO we are passing the negative value "suppressRollback" + this.suppressRollback = !rollbackOnFailure; + } + } + + public static class Project{ + public final String projectName; + + public Project(String projectName) { + this.projectName = projectName; + } + } + + public static class Platform{ + public final String platformName; + + public Platform(String platformName) { + this.platformName = platformName; + } + } + + public static class LineOfBusiness{ + public final String lineOfBusinessName; + + public LineOfBusiness(String lineOfBusiness) { + this.lineOfBusinessName = lineOfBusiness; + } + } + + @JsonTypeName("relatedInstance") + @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) + public static class RelatedInstance{ + public ModelInfo modelInfo; + @JsonInclude(NON_NULL) public String instanceId; //TODO ask Eylon - is this needed, and if yes, for other fields as well? + @JsonInclude(NON_NULL) public String instanceName; + + public RelatedInstance (@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty (value = "instanceId", required = true) String instanceId){ + this.modelInfo = modelInfo; + this.instanceId = instanceId; + } + + public RelatedInstance (@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty (value = "instanceId", required = true) String instanceId, + @JsonProperty (value = "instanceName", required = true) String instanceName){ + this.modelInfo = modelInfo; + this.instanceId = instanceId; + this.instanceName = instanceName; + } + } + + public static class RequestParameters { + public final List userParams; + + public RequestParameters(List userParams) { + this.userParams = userParams; + } + + public List getUserParams() { + return userParams; + } + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/CloudConfiguration.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/CloudConfiguration.java new file mode 100644 index 00000000..8286ec2b --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/CloudConfiguration.java @@ -0,0 +1,173 @@ + +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + + +/** + * fields communicating the cloud configuration in a standard way + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "nodeLocation", + "lcpCloudRegionId", + "tenantId", + "cloudOwner" +}) +public class CloudConfiguration { + + /** + * Location identifier for the node + * + */ + @JsonProperty("nodeLocation") + private String nodeLocation; + /** + * LCP Node Location identifier + * + */ + @JsonProperty("lcpCloudRegionId") + private String lcpCloudRegionId; + /** + * Openstack tenant id + * + */ + @JsonProperty("tenantId") + private String tenantId; + /** + * the cloud owner + * + */ + @JsonProperty("cloudOwner") + private String cloudOwner; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * Location identifier for the node + * + * @return + * The nodeLocation + */ + @JsonProperty("nodeLocation") + public String getNodeLocation() { + return nodeLocation; + } + + /** + * Location identifier for the node + * + * @param nodeLocation + * The nodeLocation + */ + @JsonProperty("nodeLocation") + public void setNodeLocation(String nodeLocation) { + this.nodeLocation = nodeLocation; + } + + /** + * LCP Node Location identifier + * + * @return + * The lcpCloudRegionId + */ + @JsonProperty("lcpCloudRegionId") + public String getLcpCloudRegionId() { + return lcpCloudRegionId; + } + + /** + * LCP Node Location identifier + * + * @param lcpCloudRegionId + * The lcpCloudRegionId + */ + @JsonProperty("lcpCloudRegionId") + public void setLcpCloudRegionId(String lcpCloudRegionId) { + this.lcpCloudRegionId = lcpCloudRegionId; + } + + /** + * Openstack tenant id + * + * @return + * The tenantId + */ + @JsonProperty("tenantId") + public String getTenantId() { + return tenantId; + } + + /** + * Openstack tenant id + * + * @param tenantId + * The tenantId + */ + @JsonProperty("tenantId") + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + /** + * the cloud owner + * + * @return + * The cloudOwner + */ + @JsonProperty("cloudOwner") + public String getCloudOwner() { + return cloudOwner; + } + + /** + * the cloud owner + * + * @param cloudOwner + * The cloudOwner + */ + @JsonProperty("cloudOwner") + public void setCloudOwner(String cloudOwner) { + this.cloudOwner = cloudOwner; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(nodeLocation).append(lcpCloudRegionId).append(tenantId).append(cloudOwner).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof CloudConfiguration)) { + return false; + } + CloudConfiguration rhs = ((CloudConfiguration) other); + return new EqualsBuilder().append(nodeLocation, rhs.nodeLocation).append(lcpCloudRegionId, rhs.lcpCloudRegionId).append(tenantId, rhs.tenantId).append(cloudOwner, rhs.cloudOwner).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/InstanceGroupInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/InstanceGroupInstantiationRequestDetails.java new file mode 100644 index 00000000..26013412 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/InstanceGroupInstantiationRequestDetails.java @@ -0,0 +1,48 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/* Based on this model: + +//{ +// "requestDetails": { +// "modelInfo": { +// "modelType": "instanceGroup", +// "modelVersionId": "ddcbbf3d-f2c1-4ca0-8852-76a807285efc" +// }, +// "requestInfo": { +// "source": "VID", +// "requestorId": "az2016" +// }, +// "relatedInstanceList": [ +// { +// "relatedInstance": { +// "instanceId": "{the relate-to/parent serviceInstanceId}", +// "modelInfo": { +// "modelType": "service", +// "modelVersionId": "b3b7e7d3-ecb9-4a91-8f6d-e60d236e8e77", +// } +// } +// } +// ], +// "requestParameters": { +// "userParams": [] +// } +// } +//} + + */ + +public class InstanceGroupInstantiationRequestDetails extends BaseResourceInstantiationRequestDetails { + + public InstanceGroupInstantiationRequestDetails(@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) RequestParameters requestParameters) + { + super(modelInfo, null, requestInfo, null, null, relatedInstanceList, requestParameters); + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/ModelInfo.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/ModelInfo.java new file mode 100644 index 00000000..091a241d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/ModelInfo.java @@ -0,0 +1,279 @@ + +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + + +/** + * fields describing the SDC entity being operated on by the request + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "modelCustomizationName", + "modelCustomizationId", + "modelInvariantId", + "modelVersionId", + "modelName", + "modelNameVersionId", + "modelType", + "modelVersion" +}) +public class ModelInfo { + + /** + * reference to the customized set of parameters associated with a model in a given service context + * + */ + @JsonProperty("modelCustomizationName") + private String modelCustomizationName; + /** + * reference to the customized set of parameters associated with a model in a given service context + * + */ + @JsonProperty("modelCustomizationId") + private String modelCustomizationId; + /** + * Invariant UUID for the model name, irrespective of the version, as defined in SDC--authoritative + * + */ + @JsonProperty("modelInvariantId") + private String modelInvariantId; + /** + * Version id for version + * + */ + @JsonProperty("modelVersionId") + private String modelVersionId; + /** + * name of the model as defined in SDC--not authoritative + * + */ + @JsonProperty("modelName") + private String modelName; + /** + * UUID for the model name and version combination as defined in SDC--authoritative + * + */ + @JsonProperty("modelNameVersionId") + private String modelNameVersionId; + /** + * short description of the entity being operated on + * (Required) + * + */ + @JsonProperty("modelType") + private String modelType; + /** + * the version of the model as defined in SDC--not authoritative + * + */ + @JsonProperty("modelVersion") + private String modelVersion; + + /** + * reference to the customized set of parameters associated with a model in a given service context + * + * @return + * The modelCustomizationName + */ + @JsonProperty("modelCustomizationName") + public String getModelCustomizationName() { + return modelCustomizationName; + } + + /** + * reference to the customized set of parameters associated with a model in a given service context + * + * @param modelCustomizationName + * The modelCustomizationName + */ + @JsonProperty("modelCustomizationName") + public void setModelCustomizationName(String modelCustomizationName) { + this.modelCustomizationName = modelCustomizationName; + } + + /** + * reference to the customized set of parameters associated with a model in a given service context + * + * @return + * The modelCustomizationId + */ + @JsonProperty("modelCustomizationId") + public String getModelCustomizationId() { + return modelCustomizationId; + } + + /** + * reference to the customized set of parameters associated with a model in a given service context + * + * @param modelCustomizationId + * The modelCustomizationId + */ + @JsonProperty("modelCustomizationId") + public void setModelCustomizationId(String modelCustomizationId) { + this.modelCustomizationId = modelCustomizationId; + } + + /** + * Invariant UUID for the model name, irrespective of the version, as defined in SDC--authoritative + * + * @return + * The modelInvariantId + */ + @JsonProperty("modelInvariantId") + public String getModelInvariantId() { + return modelInvariantId; + } + + /** + * Invariant UUID for the model name, irrespective of the version, as defined in SDC--authoritative + * + * @param modelInvariantId + * The modelInvariantId + */ + @JsonProperty("modelInvariantId") + public void setModelInvariantId(String modelInvariantId) { + this.modelInvariantId = modelInvariantId; + } + + /** + * Version id for version + * + * @return + * The modelVersionId + */ + @JsonProperty("modelVersionId") + public String getModelVersionId() { + return modelVersionId; + } + + /** + * Version id for version + * + * @param modelVersionId + * The modelVersionId + */ + @JsonProperty("modelVersionId") + public void setModelVersionId(String modelVersionId) { + this.modelVersionId = modelVersionId; + } + + /** + * name of the model as defined in SDC--not authoritative + * + * @return + * The modelName + */ + @JsonProperty("modelName") + public String getModelName() { + return modelName; + } + + /** + * name of the model as defined in SDC--not authoritative + * + * @param modelName + * The modelName + */ + @JsonProperty("modelName") + public void setModelName(String modelName) { + this.modelName = modelName; + } + + /** + * UUID for the model name and version combination as defined in SDC--authoritative + * + * @return + * The modelNameVersionId + */ + @JsonProperty("modelNameVersionId") + public String getModelNameVersionId() { + return modelNameVersionId; + } + + /** + * UUID for the model name and version combination as defined in SDC--authoritative + * + * @param modelNameVersionId + * The modelNameVersionId + */ + @JsonProperty("modelNameVersionId") + public void setModelNameVersionId(String modelNameVersionId) { + this.modelNameVersionId = modelNameVersionId; + } + + /** + * short description of the entity being operated on + * (Required) + * + * @return + * The modelType + */ + @JsonProperty("modelType") + public String getModelType() { + return modelType; + } + + /** + * short description of the entity being operated on + * (Required) + * + * @param modelType + * The modelType + */ + @JsonProperty("modelType") + public void setModelType(String modelType) { + this.modelType = modelType; + } + + /** + * the version of the model as defined in SDC--not authoritative + * + * @return + * The modelVersion + */ + @JsonProperty("modelVersion") + public String getModelVersion() { + return modelVersion; + } + + /** + * the version of the model as defined in SDC--not authoritative + * + * @param modelVersion + * The modelVersion + */ + @JsonProperty("modelVersion") + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(modelCustomizationName).append(modelCustomizationId).append(modelInvariantId).append(modelVersionId).append(modelName).append(modelNameVersionId).append(modelType).append(modelVersion).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof ModelInfo)) { + return false; + } + ModelInfo rhs = ((ModelInfo) other); + return new EqualsBuilder().append(modelCustomizationName, rhs.modelCustomizationName).append(modelCustomizationId, rhs.modelCustomizationId).append(modelInvariantId, rhs.modelInvariantId).append(modelVersionId, rhs.modelVersionId).append(modelName, rhs.modelName).append(modelNameVersionId, rhs.modelNameVersionId).append(modelType, rhs.modelType).append(modelVersion, rhs.modelVersion).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/NetworkInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/NetworkInstantiationRequestDetails.java new file mode 100644 index 00000000..d8539f6a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/NetworkInstantiationRequestDetails.java @@ -0,0 +1,86 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/* Based on this model: + + +// { +// "requestDetails": { +// "modelInfo": { +// “modelType”: “network”, +// “modelInvariantId”: “ff5256d1-5a33-55df-13ab-12abad84e7ff”, +// “modelVersionId”: “fe042c22-ba82-43c6-b2f6-8f1fc4164091”, +// “modelName”: “vSAMP12”, +// "modelVersion": "1.0", +// “modelCustomizationName”: “vSAMP12 1”, +// “modelCustomizationId”: “a7f1d08e-b02d-11e6-80f5-76304dec7eb7” +// }, +// “cloudConfiguration”: { +// “lcpCloudRegionId”: “mdt1”, +// “tenantId”: “88a6ca3ee0394ade9403f075db23167e” +// }, +// "requestInfo": { +// “instanceName”: “MSOTEST103a”, +// “productFamilyId”: “a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb”, +// “source”: “VID”, +// “suppressRollback”: false, +// “requestorId”: “az2016” +// }, +// "platform": { +// "platformName": "{some platformName}" +// }, +// "lineOfBusiness": { +// "lineOfBusinessName": "{some string}" +// }, +// "relatedInstanceList": [ +// { +// “relatedInstance”: { +// “instanceId”: “{serviceInstanceId}”, +// “modelInfo”: { +// “modelType”: “service”, +// “modelInvariantId”: “ff3514e3-5a33-55df-13ab-12abad84e7ff”, +// “modelVersionId”: “fe6985cd-ea33-3346-ac12-ab121484a3fe”, +// “modelName”: “{parent service model name}”, +// "modelVersion": "1.0" +// } +// } +// }, +// { +// “relatedInstance”: { +// “instanceId”: “{instanceGroupId}”, +// “modelInfo”: { +// “modelType”: “networkCollection”, +// “modelInvariantId”: “9ea660dc-155f-44d3-b45c-cc7648b4f31c”, +// “modelVersionId”: “bb07aad1-ce2d-40c1-85cb-5392f76bb1ef”, +// “modelName”: “{network collection model name}”, +// "modelVersion": "1.0" +// } +// } +// } + +// ], +// “requestParameters”: { +// “userParams”: [] +// } +// } +// } + + */ + +public class NetworkInstantiationRequestDetails extends BaseResourceInstantiationRequestDetails { + + public NetworkInstantiationRequestDetails(@JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "platform", required = true) Platform platform, + @JsonProperty(value = "lineOfBusiness", required = true) LineOfBusiness lineOfBusiness, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) RequestParameters requestParameters) + { + super(modelInfo, cloudConfiguration, requestInfo, platform, lineOfBusiness, relatedInstanceList, requestParameters); + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfo.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfo.java index a5a10a77..bca643a6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfo.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfo.java @@ -1,8 +1,7 @@ package org.onap.vid.mso.model; -import org.onap.vid.controllers.OperationalEnvironmentController; - import com.google.common.base.MoreObjects; +import org.onap.vid.controller.OperationalEnvironmentController; public class OperationalEnvironmentActivateInfo extends OperationalEnvironmentController.OperationalEnvironmentActivateBody { private final String userId; diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestInfo.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestInfo.java new file mode 100644 index 00000000..1290361a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestInfo.java @@ -0,0 +1,376 @@ + +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + + +/** + * fields providing general context information for the request + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "billingAccountNumber", + "callbackUrl", + "correlator", + "instanceName", + "orderNumber", + "orderVersion", + "productFamilyId", + "source", + "suppressRollback", + "responseValue", + "requestorId" +}) +public class RequestInfo { + + /** + * billing account associated with the model being operated on + * + */ + @JsonProperty("billingAccountNumber") + private String billingAccountNumber; + /** + * client URL to use for asynchronous responses + * + */ + @JsonProperty("callbackUrl") + private String callbackUrl; + /** + * Optional correlationId for async callback requests + * + */ + @JsonProperty("correlator") + private String correlator; + /** + * Client provided name for the instance being operated on by the operation (note: not guaranteed to be unique) + * + */ + @JsonProperty("instanceName") + private String instanceName; + /** + * reference to an order + * + */ + @JsonProperty("orderNumber") + private String orderNumber; + /** + * order version number + * + */ + @JsonProperty("orderVersion") + private Double orderVersion; + /** + * UUID for the product family associated with the model being operated on + * + */ + @JsonProperty("productFamilyId") + private String productFamilyId; + /** + * source of the request--not authoritative--actual source revealed via authentication + * + */ + @JsonProperty("source") + private String source; + /** + * true or false boolean indicating whether rollbacks should be suppressed on failures + * + */ + @JsonProperty("suppressRollback") + private Boolean suppressRollback; + /** + * Is the user selected value based on the validResponses list provided to complete the manual task + * + */ + @JsonProperty("responseValue") + private String responseValue; + /** + * The id of the person who initiated the completion request + * + */ + @JsonProperty("requestorId") + private String requestorId; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * billing account associated with the model being operated on + * + * @return + * The billingAccountNumber + */ + @JsonProperty("billingAccountNumber") + public String getBillingAccountNumber() { + return billingAccountNumber; + } + + /** + * billing account associated with the model being operated on + * + * @param billingAccountNumber + * The billingAccountNumber + */ + @JsonProperty("billingAccountNumber") + public void setBillingAccountNumber(String billingAccountNumber) { + this.billingAccountNumber = billingAccountNumber; + } + + /** + * client URL to use for asynchronous responses + * + * @return + * The callbackUrl + */ + @JsonProperty("callbackUrl") + public String getCallbackUrl() { + return callbackUrl; + } + + /** + * client URL to use for asynchronous responses + * + * @param callbackUrl + * The callbackUrl + */ + @JsonProperty("callbackUrl") + public void setCallbackUrl(String callbackUrl) { + this.callbackUrl = callbackUrl; + } + + /** + * Optional correlationId for async callback requests + * + * @return + * The correlator + */ + @JsonProperty("correlator") + public String getCorrelator() { + return correlator; + } + + /** + * Optional correlationId for async callback requests + * + * @param correlator + * The correlator + */ + @JsonProperty("correlator") + public void setCorrelator(String correlator) { + this.correlator = correlator; + } + + /** + * Client provided name for the instance being operated on by the operation (note: not guaranteed to be unique) + * + * @return + * The instanceName + */ + @JsonProperty("instanceName") + public String getInstanceName() { + return instanceName; + } + + /** + * Client provided name for the instance being operated on by the operation (note: not guaranteed to be unique) + * + * @param instanceName + * The instanceName + */ + @JsonProperty("instanceName") + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + /** + * reference to an order + * + * @return + * The orderNumber + */ + @JsonProperty("orderNumber") + public String getOrderNumber() { + return orderNumber; + } + + /** + * reference to an order + * + * @param orderNumber + * The orderNumber + */ + @JsonProperty("orderNumber") + public void setOrderNumber(String orderNumber) { + this.orderNumber = orderNumber; + } + + /** + * order version number + * + * @return + * The orderVersion + */ + @JsonProperty("orderVersion") + public Double getOrderVersion() { + return orderVersion; + } + + /** + * order version number + * + * @param orderVersion + * The orderVersion + */ + @JsonProperty("orderVersion") + public void setOrderVersion(Double orderVersion) { + this.orderVersion = orderVersion; + } + + /** + * UUID for the product family associated with the model being operated on + * + * @return + * The productFamilyId + */ + @JsonProperty("productFamilyId") + public String getProductFamilyId() { + return productFamilyId; + } + + /** + * UUID for the product family associated with the model being operated on + * + * @param productFamilyId + * The productFamilyId + */ + @JsonProperty("productFamilyId") + public void setProductFamilyId(String productFamilyId) { + this.productFamilyId = productFamilyId; + } + + /** + * source of the request--not authoritative--actual source revealed via authentication + * + * @return + * The source + */ + @JsonProperty("source") + public String getSource() { + return source; + } + + /** + * source of the request--not authoritative--actual source revealed via authentication + * + * @param source + * The source + */ + @JsonProperty("source") + public void setSource(String source) { + this.source = source; + } + + /** + * true or false boolean indicating whether rollbacks should be suppressed on failures + * + * @return + * The suppressRollback + */ + @JsonProperty("suppressRollback") + public Boolean getSuppressRollback() { + return suppressRollback; + } + + /** + * true or false boolean indicating whether rollbacks should be suppressed on failures + * + * @param suppressRollback + * The suppressRollback + */ + @JsonProperty("suppressRollback") + public void setSuppressRollback(Boolean suppressRollback) { + this.suppressRollback = suppressRollback; + } + + /** + * Is the user selected value based on the validResponses list provided to complete the manual task + * + * @return + * The responseValue + */ + @JsonProperty("responseValue") + public String getResponseValue() { + return responseValue; + } + + /** + * Is the user selected value based on the validResponses list provided to complete the manual task + * + * @param responseValue + * The responseValue + */ + @JsonProperty("responseValue") + public void setResponseValue(String responseValue) { + this.responseValue = responseValue; + } + + /** + * The id of the person who initiated the completion request + * + * @return + * The requestorId + */ + @JsonProperty("requestorId") + public String getRequestorId() { + return requestorId; + } + + /** + * The id of the person who initiated the completion request + * + * @param requestorId + * The requestorId + */ + @JsonProperty("requestorId") + public void setRequestorId(String requestorId) { + this.requestorId = requestorId; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(billingAccountNumber).append(callbackUrl).append(correlator).append(instanceName).append(orderNumber).append(orderVersion).append(productFamilyId).append(source).append(suppressRollback).append(responseValue).append(requestorId).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof RequestInfo)) { + return false; + } + RequestInfo rhs = ((RequestInfo) other); + return new EqualsBuilder().append(billingAccountNumber, rhs.billingAccountNumber).append(callbackUrl, rhs.callbackUrl).append(correlator, rhs.correlator).append(instanceName, rhs.instanceName).append(orderNumber, rhs.orderNumber).append(orderVersion, rhs.orderVersion).append(productFamilyId, rhs.productFamilyId).append(source, rhs.source).append(suppressRollback, rhs.suppressRollback).append(responseValue, rhs.responseValue).append(requestorId, rhs.requestorId).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestParameters.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestParameters.java new file mode 100644 index 00000000..65e35125 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestParameters.java @@ -0,0 +1,123 @@ + +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "subscriptionServiceType", + "testApi", + "userParams" +}) +public class RequestParameters { + + @JsonProperty("subscriptionServiceType") + private String subscriptionServiceType; + @JsonProperty("testApi") + private String testApi; + @JsonProperty("userParams") + private List userParams = new ArrayList<>(); + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * + * @return + * The subscriptionServiceType + */ + @JsonProperty("subscriptionServiceType") + public String getSubscriptionServiceType() { + return subscriptionServiceType; + } + + /** + * + * @param subscriptionServiceType + * The subscriptionServiceType + */ + @JsonProperty("subscriptionServiceType") + public void setSubscriptionServiceType(String subscriptionServiceType) { + this.subscriptionServiceType = subscriptionServiceType; + } + + /** + * + * @return + * The testApi + */ + @JsonProperty("testApi") + public String getTestApi() { + return testApi; + } + + /** + * + * @param testApi + * The testApi + */ + @JsonProperty("testApi") + public void setTestApi(String testApi) { + this.testApi = testApi; + } + + /** + * + * @return + * The userParams + */ + @JsonProperty("userParams") + public List getUserParams() { + return userParams; + } + + /** + * + * @param userParams + * The userParams + */ + @JsonProperty("userParams") + public void setUserParams(List userParams) { + this.userParams = userParams; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(subscriptionServiceType).append(testApi).append(userParams).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof RequestParameters)) { + return false; + } + RequestParameters rhs = ((RequestParameters) other); + return new EqualsBuilder().append(subscriptionServiceType, rhs.subscriptionServiceType).append(testApi, rhs.testApi).append(userParams, rhs.userParams).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestReferences.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestReferences.java new file mode 100644 index 00000000..9c044e11 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/RequestReferences.java @@ -0,0 +1,121 @@ + +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + + +/** + * provides the instanceId and requestId associated with the request + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "instanceId", + "requestId" +}) +public class RequestReferences { + + /** + * UUID for the service instance + * (Required) + * + */ + @JsonProperty("instanceId") + private String instanceId; + /** + * UUID for the request + * (Required) + * + */ + @JsonProperty("requestId") + private String requestId; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * UUID for the service instance + * (Required) + * + * @return + * The instanceId + */ + @JsonProperty("instanceId") + public String getInstanceId() { + return instanceId; + } + + /** + * UUID for the service instance + * (Required) + * + * @param instanceId + * The instanceId + */ + @JsonProperty("instanceId") + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + /** + * UUID for the request + * (Required) + * + * @return + * The requestId + */ + @JsonProperty("requestId") + public String getRequestId() { + return requestId; + } + + /** + * UUID for the request + * (Required) + * + * @param requestId + * The requestId + */ + @JsonProperty("requestId") + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(instanceId).append(requestId).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof RequestReferences)) { + return false; + } + RequestReferences rhs = ((RequestReferences) other); + return new EqualsBuilder().append(instanceId, rhs.instanceId).append(requestId, rhs.requestId).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceDeletionRequestDetails.kt b/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceDeletionRequestDetails.kt new file mode 100644 index 00000000..c41db086 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceDeletionRequestDetails.kt @@ -0,0 +1,15 @@ +package org.onap.vid.mso.model + +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL +import com.fasterxml.jackson.annotation.JsonProperty + +class ServiceDeletionRequestDetails(val modelInfo: ModelInfo, + val requestInfo: RequestInfo, + val requestParameters: RequestParameters) { + + class RequestInfo(val source: String, val requestorId: String) + + class RequestParameters(@JsonInclude(NON_NULL) @get:JsonProperty("aLaCarte") val aLaCarte: Boolean?, + @JsonInclude(NON_NULL) val testApi: String?) +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java index 1a54b74c..c6d89e31 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/ServiceInstantiationRequestDetails.java @@ -2,12 +2,7 @@ package org.onap.vid.mso.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeName; -import org.onap.vid.domain.mso.CloudConfiguration; -import org.onap.vid.domain.mso.ModelInfo; -import org.onap.vid.domain.mso.SubscriberInfo; -import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.mso.rest.SubscriberInfo; import java.util.List; import java.util.Map; @@ -62,7 +57,7 @@ public class ServiceInstantiationRequestDetails { public static class RequestInfo { @JsonInclude(NON_NULL) public final String instanceName; - public final String productFamilyId; + @JsonInclude(NON_NULL) public final String productFamilyId; public final String source; public final boolean suppressRollback; public final String requestorId; @@ -86,33 +81,68 @@ public class ServiceInstantiationRequestDetails { } public static class RequestParameters { - + @JsonInclude(NON_NULL) public final String testApi; public final String subscriptionServiceType; public final boolean aLaCarte; - public final List userParams; + public final List userParams; - public RequestParameters(String subscriptionServiceType, boolean aLaCarte, List userParams) { + public RequestParameters(String subscriptionServiceType, boolean aLaCarte, List userParams) { + this(subscriptionServiceType, aLaCarte, userParams, null); + } + + public RequestParameters(String subscriptionServiceType, boolean aLaCarte, List userParams, String testApi) { this.subscriptionServiceType = subscriptionServiceType; this.aLaCarte = aLaCarte; this.userParams = userParams; + this.testApi = testApi; } } - @JsonTypeName("service") - @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) - public static class ServiceInstantiationService{ - public ModelInfo modelInfo = new ModelInfo(); - @JsonInclude(NON_NULL) public String instanceName; - public List> instanceParams; - public ServiceInstantiationVnfList resources; - - public ServiceInstantiationService (ModelInfo modelInfo, String instanceName, List> instanceParams, ServiceInstantiationVnfList vnfs){ - this.modelInfo.setModelType(modelInfo.getModelType()); - this.modelInfo.setModelName(modelInfo.getModelName()); - this.modelInfo.setModelVersionId(modelInfo.getModelVersionId()); - this.instanceName = instanceName; - this.instanceParams = instanceParams; - this.resources = vnfs; + public static class UserParamNameAndValue implements UserParamTypes { + private final String name; + private final String value; + + public UserParamNameAndValue(String name, String value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public String getValue() { + return value; + } + } + + public static class ServiceInstantiationService implements UserParamTypes { + private final ServiceInstantiationServiceInner serviceInstantiationServiceInner; + + public ServiceInstantiationService(ModelInfo modelInfo, String instanceName, List> instanceParams, ServiceInstantiationVnfList vnfs) { + serviceInstantiationServiceInner = new ServiceInstantiationServiceInner(modelInfo, instanceName, instanceParams, vnfs); + } + + @JsonProperty("service") + public ServiceInstantiationServiceInner getServiceInstantiationServiceInner() { + return serviceInstantiationServiceInner; + } + + private static class ServiceInstantiationServiceInner implements UserParamTypes { + public ModelInfo modelInfo = new ModelInfo(); + @JsonInclude(NON_NULL) + public String instanceName; + public List> instanceParams; + public ServiceInstantiationVnfList resources; + + public ServiceInstantiationServiceInner(ModelInfo modelInfo, String instanceName, List> instanceParams, ServiceInstantiationVnfList vnfs) { + this.modelInfo.setModelType(modelInfo.getModelType()); + this.modelInfo.setModelName(modelInfo.getModelName()); + this.modelInfo.setModelVersionId(modelInfo.getModelVersionId()); + this.instanceName = instanceName; + this.instanceParams = instanceParams; + this.resources = vnfs; + } } } @@ -131,10 +161,10 @@ public class ServiceInstantiationRequestDetails { public final LineOfBusiness lineOfBusiness; public final String productFamilyId; public final List> instanceParams; - @JsonInclude(NON_EMPTY) public final List vfModules; + @JsonInclude(NON_EMPTY) public final List vfModules; @JsonInclude(NON_NULL) public final String instanceName; - public ServiceInstantiationVnf(ModelInfo modelInfo, CloudConfiguration cloudConfiguration, String platform, String lineOfBusiness, String productFamilyId, List> instanceParams, List vfModules, String instanceName) { + public ServiceInstantiationVnf(ModelInfo modelInfo, CloudConfiguration cloudConfiguration, String platform, String lineOfBusiness, String productFamilyId, List> instanceParams, List vfModules, String instanceName) { this.modelInfo = modelInfo; this.cloudConfiguration = cloudConfiguration; this.platform = new Platform(platform); diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/UserParam.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/UserParam.java new file mode 100644 index 00000000..b6c9131e --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/UserParam.java @@ -0,0 +1,98 @@ + +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "name", + "value" +}) +public class UserParam { + + @JsonProperty("name") + private String name; + @JsonProperty("value") + private String value; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * + * @return + * The name + */ + @JsonProperty("name") + public String getName() { + return name; + } + + /** + * + * @param name + * The name + */ + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + /** + * + * @return + * The value + */ + @JsonProperty("value") + public String getValue() { + return value; + } + + /** + * + * @param value + * The value + */ + @JsonProperty("value") + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(name).append(value).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof UserParam)) { + return false; + } + UserParam rhs = ((UserParam) other); + return new EqualsBuilder().append(name, rhs.name).append(value, rhs.value).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/UserParamTypes.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/UserParamTypes.java new file mode 100644 index 00000000..8e5a88d2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/UserParamTypes.java @@ -0,0 +1,4 @@ +package org.onap.vid.mso.model; + +public interface UserParamTypes { +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleInstantiationRequestDetails.java new file mode 100644 index 00000000..9a3a0c85 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleInstantiationRequestDetails.java @@ -0,0 +1,111 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/* Based on this model: + +{ + "requestDetails": { + "modelInfo": { + “modelType”: “vfModule”, + “modelInvariantId”: “ff5256d2-5a33-55df-13ab-12abad84e7ff”, + “modelVersionId”: “fe6478e5-ea33-3346-ac12-ab121484a3fe”, + “modelCustomizationId”: “856f9806-b01a-11e6-80f5-76304dec7eb7”, + “modelName”: “vSAMP12..base..module-0”, + "modelVersion": "1" + }, + “cloudConfiguration”: { + “lcpCloudRegionId”: “mdt1”, + “tenantId”: “88a6ca3ee0394ade9403f075db23167e” + }, + "requestInfo": { + “instanceName”: “MSOTEST103a-vSAMP12_base_module-0”, + “source”: “VID”, + “suppressRollback”: true, + “requestorId”: “az2016” + }, + "relatedInstanceList": [ + { + // This related instance captures the volumeGroup to attach + “relatedInstance”: { + “instanceId”: “17ef4658-bd1f-4ef0-9ca0-ea76e2bf122c”, + “instanceName”: “MSOTESTVOL103a-vSAMP12_base_module-0_vol”, + “modelInfo”: { + “modelType”: “volumeGroup” + } + } + }, + { + “relatedInstance”: { + “instanceId”: “{serviceInstanceId}”, + “modelInfo”: { + “modelType”: “service”, + “modelInvariantId”: “ff3514e3-5a33-55df-13ab-12abad84e7ff”, + “modelVersionId”: “fe6985cd-ea33-3346-ac12-ab121484a3fe”, + “modelName”: “{parent service model name}”, + "modelVersion": "1.0" + } + } + }, + { + “relatedInstance”: { + “instanceId”: “{vnfInstanceId}”, + "modelInfo": { + “modelType”: “vnf”, + “modelInvariantId”: “ff5256d1-5a33-55df-13ab-12abad84e7ff”, + “modelVersionId”: “fe6478e4-ea33-3346-ac12-ab121484a3fe”, + “modelName”: “vSAMP12”, + "modelVersion": "1.0", + “modelCustomizationName”: “vSAMP12 1”, + “modelCustomizationId”: “a7f1d08e-b02d-11e6-80f5-76304dec7eb7” + } + } + } + ], + “requestParameters”: { + “usePreload”: true, + “userParams”: [] + } + } +} + + + */ + +public class VfModuleInstantiationRequestDetails extends BaseResourceInstantiationRequestDetails { + + public VfModuleInstantiationRequestDetails( + @JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) RequestParametersVfModule requestParameters) + { + super(modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters); + } + + public static class RequestParametersVfModule extends BaseResourceInstantiationRequestDetails.RequestParameters { + private final boolean usePreload; + + public RequestParametersVfModule(List userParams, boolean usePreload) { + super(userParams); + this.usePreload = usePreload; + } + + public boolean isUsePreload() { + return usePreload; + } + } + + public static class UserParamMap extends HashMap implements UserParamTypes, Map { + + public UserParamMap() { + super(); + } + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleMacro.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleMacro.java new file mode 100644 index 00000000..1bb8a37c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/VfModuleMacro.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; + +public class VfModuleMacro { + + private final ModelInfo modelInfo; + + @JsonInclude(NON_NULL) + private final String instanceName; + + private final List> instanceParams; + + @JsonInclude(NON_NULL) + private final String volumeGroupInstanceName; + + public VfModuleMacro(@JsonProperty("modelInfo") ModelInfo modelInfo, + @JsonProperty("instanceName") String instanceName, + @JsonProperty("volumeGroupName") String volumeGroupInstanceName, + @JsonProperty("instanceParams") List> instanceParams) { + this.modelInfo = modelInfo; + this.modelInfo.setModelType("vfModule"); + this.instanceName = instanceName; + this.instanceParams = instanceParams; + this.volumeGroupInstanceName = volumeGroupInstanceName; + } + + public ModelInfo getModelInfo() { + return modelInfo; + } + + public String getInstanceName() { + return instanceName; + } + + public String getVolumeGroupInstanceName() { + return volumeGroupInstanceName; + } + + public List> getInstanceParams() { + return instanceParams == null ? Collections.emptyList() : instanceParams; + } +} + + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/VnfInstantiationRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/VnfInstantiationRequestDetails.java new file mode 100644 index 00000000..4a60c1a5 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/VnfInstantiationRequestDetails.java @@ -0,0 +1,87 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/* Based on this model: + + +// { +// "requestDetails": { +// "modelInfo": { +// “modelType”: “vnf”, +// “modelInvariantId”: “ff5256d1-5a33-55df-13ab-12abad84e7ff”, +// “modelVersionId”: “fe042c22-ba82-43c6-b2f6-8f1fc4164091”, +// “modelName”: “vSAMP12”, +// "modelVersion": "1.0", +// “modelCustomizationName”: “vSAMP12 1”, +// “modelCustomizationId”: “a7f1d08e-b02d-11e6-80f5-76304dec7eb7” +// }, +// “cloudConfiguration”: { +// “lcpCloudRegionId”: “mdt1”, +// “tenantId”: “88a6ca3ee0394ade9403f075db23167e” +// }, +// "requestInfo": { +// “instanceName”: “MSOTEST103a”, +// “productFamilyId”: “a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb”, +// “source”: “VID”, +// “suppressRollback”: false, +// “requestorId”: “az2016” +// }, +// "platform": { +// "platformName": "{some platformName}" +// }, +// "lineOfBusiness": { +// "lineOfBusinessName": "{some string}" +// }, +// "relatedInstanceList": [ +// { +// “relatedInstance”: { +// “instanceId”: “{serviceInstanceId}”, +// “modelInfo”: { +// “modelType”: “service”, +// “modelInvariantId”: “ff3514e3-5a33-55df-13ab-12abad84e7ff”, +// “modelVersionId”: “fe6985cd-ea33-3346-ac12-ab121484a3fe”, +// “modelName”: “{parent service model name}”, +// "modelVersion": "1.0" +// } +// } +// }, +// { +// “relatedInstance”: { +// “instanceId”: “{instanceGroupId}”, +// “modelInfo”: { +// “modelType”: “networkCollection”, +// “modelInvariantId”: “9ea660dc-155f-44d3-b45c-cc7648b4f31c”, +// “modelVersionId”: “bb07aad1-ce2d-40c1-85cb-5392f76bb1ef”, +// “modelName”: “{network collection model name}”, +// "modelVersion": "1.0" +// } +// } +// } + +// ], +// “requestParameters”: { +// “userParams”: [] +// } +// } +// } + + */ + +public class VnfInstantiationRequestDetails extends BaseResourceInstantiationRequestDetails { + + public VnfInstantiationRequestDetails( + @JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "platform", required = true) Platform platform, + @JsonProperty(value = "lineOfBusiness", required = true) LineOfBusiness lineOfBusiness, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) RequestParameters requestParameters) + { + super(modelInfo, cloudConfiguration, requestInfo, platform, lineOfBusiness, relatedInstanceList, requestParameters); + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java new file mode 100644 index 00000000..d60c9975 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/model/VolumeGroupRequestDetails.java @@ -0,0 +1,18 @@ +package org.onap.vid.mso.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class VolumeGroupRequestDetails extends BaseResourceInstantiationRequestDetails { + + public VolumeGroupRequestDetails( + @JsonProperty(value = "modelInfo", required = true) ModelInfo modelInfo, + @JsonProperty(value = "cloudConfiguration", required = true) CloudConfiguration cloudConfiguration, + @JsonProperty(value = "requestInfo", required = true) RequestInfo requestInfo, + @JsonProperty(value = "relatedInstanceList", required = true) List relatedInstanceList, + @JsonProperty(value = "requestParameters", required = true) VfModuleInstantiationRequestDetails.RequestParametersVfModule requestParameters) + { + super(modelInfo, cloudConfiguration, requestInfo, relatedInstanceList, requestParameters); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java index 4c3dca26..7d844fee 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatus.java @@ -23,7 +23,6 @@ package org.onap.vid.mso.rest; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; -import org.onap.vid.domain.mso.RequestStatus; /** * Represent response for: GET orchestrationRequests @@ -53,16 +52,29 @@ public class AsyncRequestStatus { } public String requestId; + public String requestScope; /** * The instance ids. */ public InstanceReferences instanceReferences; + + /** + * The request details. + */ + public RequestDetails requestDetails; + /** * The request status. */ public RequestStatus requestStatus; + + /** + * The time of start. + */ + public String startTime; + } @JsonIgnoreProperties(ignoreUnknown = true) @@ -71,5 +83,18 @@ public class AsyncRequestStatus { public String serviceInstanceId; } + @JsonIgnoreProperties(ignoreUnknown = true) + public static class RequestDetails { + + public RequestInfo requestInfo; + } + + @JsonIgnoreProperties(ignoreUnknown = true) + public static class RequestInfo { + + public String instanceName; + } + + } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatusList.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatusList.java new file mode 100644 index 00000000..04ced39f --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/AsyncRequestStatusList.java @@ -0,0 +1,17 @@ +package org.onap.vid.mso.rest; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +public class AsyncRequestStatusList { + AsyncRequestStatusList(@JsonProperty("requestList") List requestList) { + this.requestList = requestList; + } + + public List getRequestList() { + return requestList; + } + + private final List requestList; +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/InstanceIds.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/InstanceIds.java new file mode 100644 index 00000000..5e1c5ce8 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/InstanceIds.java @@ -0,0 +1,202 @@ + +package org.onap.vid.mso.rest; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + + +/** + * instanceIds that may be associated with a particular request + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "networkInstanceId", + "serviceInstanceId", + "vfModuleInstanceId", + "vnfInstanceId", + "volumeGroupInstanceId" +}) +public class InstanceIds { + + /** + * UUID for the network instance (if any) + * + */ + @JsonProperty("networkInstanceId") + private String networkInstanceId; + /** + * UUID for the service instance + * + */ + @JsonProperty("serviceInstanceId") + private String serviceInstanceId; + /** + * UUID for the vfModule instance (if any) + * + */ + @JsonProperty("vfModuleInstanceId") + private String vfModuleInstanceId; + /** + * UUID for the vnf instance (if any) + * + */ + @JsonProperty("vnfInstanceId") + private String vnfInstanceId; + /** + * UUID for the volume group instance (if any) + * + */ + @JsonProperty("volumeGroupInstanceId") + private String volumeGroupInstanceId; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * UUID for the network instance (if any) + * + * @return + * The networkInstanceId + */ + @JsonProperty("networkInstanceId") + public String getNetworkInstanceId() { + return networkInstanceId; + } + + /** + * UUID for the network instance (if any) + * + * @param networkInstanceId + * The networkInstanceId + */ + @JsonProperty("networkInstanceId") + public void setNetworkInstanceId(String networkInstanceId) { + this.networkInstanceId = networkInstanceId; + } + + /** + * UUID for the service instance + * + * @return + * The serviceInstanceId + */ + @JsonProperty("serviceInstanceId") + public String getServiceInstanceId() { + return serviceInstanceId; + } + + /** + * UUID for the service instance + * + * @param serviceInstanceId + * The serviceInstanceId + */ + @JsonProperty("serviceInstanceId") + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + /** + * UUID for the vfModule instance (if any) + * + * @return + * The vfModuleInstanceId + */ + @JsonProperty("vfModuleInstanceId") + public String getVfModuleInstanceId() { + return vfModuleInstanceId; + } + + /** + * UUID for the vfModule instance (if any) + * + * @param vfModuleInstanceId + * The vfModuleInstanceId + */ + @JsonProperty("vfModuleInstanceId") + public void setVfModuleInstanceId(String vfModuleInstanceId) { + this.vfModuleInstanceId = vfModuleInstanceId; + } + + /** + * UUID for the vnf instance (if any) + * + * @return + * The vnfInstanceId + */ + @JsonProperty("vnfInstanceId") + public String getVnfInstanceId() { + return vnfInstanceId; + } + + /** + * UUID for the vnf instance (if any) + * + * @param vnfInstanceId + * The vnfInstanceId + */ + @JsonProperty("vnfInstanceId") + public void setVnfInstanceId(String vnfInstanceId) { + this.vnfInstanceId = vnfInstanceId; + } + + /** + * UUID for the volume group instance (if any) + * + * @return + * The volumeGroupInstanceId + */ + @JsonProperty("volumeGroupInstanceId") + public String getVolumeGroupInstanceId() { + return volumeGroupInstanceId; + } + + /** + * UUID for the volume group instance (if any) + * + * @param volumeGroupInstanceId + * The volumeGroupInstanceId + */ + @JsonProperty("volumeGroupInstanceId") + public void setVolumeGroupInstanceId(String volumeGroupInstanceId) { + this.volumeGroupInstanceId = volumeGroupInstanceId; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(networkInstanceId).append(serviceInstanceId).append(vfModuleInstanceId).append(vnfInstanceId).append(volumeGroupInstanceId).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof InstanceIds)) { + return false; + } + InstanceIds rhs = ((InstanceIds) other); + return new EqualsBuilder().append(networkInstanceId, rhs.networkInstanceId).append(serviceInstanceId, rhs.serviceInstanceId).append(vfModuleInstanceId, rhs.vfModuleInstanceId).append(vnfInstanceId, rhs.vnfInstanceId).append(volumeGroupInstanceId, rhs.volumeGroupInstanceId).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java index 37600f7b..2ff33765 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java @@ -22,10 +22,6 @@ package org.onap.vid.mso.rest; import com.google.common.collect.ImmutableMap; import io.joshworks.restclient.http.HttpResponse; -import java.util.HashMap; -import java.util.Map; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; import org.apache.commons.codec.binary.Base64; import org.eclipse.jetty.util.security.Password; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -35,17 +31,21 @@ import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.*; +import org.onap.vid.utils.Logging; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import org.onap.vid.utils.Logging; +import java.util.HashMap; +import java.util.Map; /** * Created by pickjonathan on 21/06/2017. */ -public class MsoRestClientNew implements MsoInterface { +public class MsoRestClientNew extends RestMsoImplementation implements MsoInterface { /** * The Constant dateFormat. @@ -70,7 +70,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createSvcInstance "; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetails, path); @@ -79,7 +79,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint) { String methodName = "createE2eSvcInstance "; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetails, path); @@ -89,7 +89,7 @@ public class MsoRestClientNew implements MsoInterface { public MsoResponseWrapper createVnf(RequestDetails requestDetails, String endpoint) { String methodName = "createVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetails, path); @@ -99,7 +99,7 @@ public class MsoRestClientNew implements MsoInterface { public MsoResponseWrapper createNwInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createNwInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetails, path); @@ -108,7 +108,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createVolumeGroupInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetails, path); @@ -117,7 +117,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createVfModuleInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetails, path); @@ -126,7 +126,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper scaleOutVFModuleInstance(RequestDetailsWrapper requestDetailsWrapper, String endpoint) { String methodName = "scaleOutVFModuleInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetailsWrapper, path); } @@ -134,7 +134,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper createConfigurationInstance(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String endpoint) { String methodName = "createConfigurationInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return createInstance(requestDetailsWrapper, path); @@ -143,7 +143,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint) { String methodName = "deleteE2eSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return deleteInstance(requestDetails, path); } @@ -151,7 +151,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return deleteInstance(requestDetails, path); } @@ -159,15 +159,17 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper unassignSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "unassignSvcInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - HttpResponse response = client.post(endpoint, commonHeaders, requestDetails, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); + String path = baseUrl + endpoint; + + HttpResponse response = client.post(path, commonHeaders, requestDetails, String.class); return MsoUtil.wrapResponse(response); } @Override public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return deleteInstance(requestDetails, path); @@ -176,7 +178,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVfModule"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return deleteInstance(requestDetails, path); @@ -185,7 +187,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVolumeGroupInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return deleteInstance(requestDetails, path); @@ -194,59 +196,50 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteNwInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return deleteInstance(requestDetails, path); } @Override - public MsoResponseWrapper getOrchestrationRequest(String endpoint) { + public MsoResponseWrapper getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject, boolean warpException) { String path = baseUrl + endpoint; HttpResponse response = client.get(path, commonHeaders, new HashMap<>(), String.class); return MsoUtil.wrapResponse(response); } - public MsoResponseWrapper getManualTasks(String endpoint) { + @Override + public MsoResponseWrapper getOrchestrationRequest(String endpoint) { String path = baseUrl + endpoint; HttpResponse response = client.get(path, commonHeaders, new HashMap<>(), String.class); return MsoUtil.wrapResponse(response); } - public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String path, RestObject restObject) { - String methodName = "getOrchestrationRequestsForDashboard"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); - - try { - MsoResponseWrapper w = getOrchestrationRequest(path); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); - - return w; + public MsoResponseWrapper getManualTasks(String endpoint) { + String path = baseUrl + endpoint; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - throw e; - } + HttpResponse response = client.get(path, commonHeaders, new HashMap<>(), String.class); + return MsoUtil.wrapResponse(response); } public MsoResponseWrapper getManualTasksByRequestId(String t, String sourceId, String endpoint, RestObject restObject) { String methodName = "getManualTasksByRequestId"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(methodName + START); try { String path = baseUrl + endpoint; MsoResponseWrapper w =getManualTasks(path); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " w=" + w.getResponse()); return w; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -254,19 +247,19 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper completeManualTask(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) { String methodName = "completeManualTask"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Complete "); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " calling Complete "); try { String path = baseUrl + endpoint; HttpResponse response = client.post(path, commonHeaders, requestDetails, String.class); MsoResponseWrapper w = MsoUtil.wrapResponse(response); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " w=" + w.getResponse()); return w; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -274,7 +267,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) { String methodName = "replaceVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; return replaceInstance(requestDetails, path); } @@ -283,7 +276,7 @@ public class MsoRestClientNew implements MsoInterface { public MsoResponseWrapper deleteConfiguration(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String pmc_endpoint) { String methodName = "deleteConfiguration"; logger.debug(EELFLoggerDelegate.debugLogger, - dateFormat.format(new Date()) + "<== " + methodName + START); + methodName + START); String path = baseUrl + pmc_endpoint; return deleteInstance(requestDetailsWrapper, path); @@ -292,7 +285,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper setConfigurationActiveStatus(RequestDetails request, String endpoint) { String methodName = "setConfigurationActiveStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { String path = baseUrl + endpoint; @@ -302,8 +295,8 @@ public class MsoRestClientNew implements MsoInterface { HttpResponse response = client.post(path, commonHeaders, request, String.class); return MsoUtil.wrapResponse(response); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -311,7 +304,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails request, String endpoint) { String methodName = "setPortOnConfigurationStatus"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { String path = baseUrl + endpoint; @@ -320,8 +313,8 @@ public class MsoRestClientNew implements MsoInterface { HttpResponse response = client.post(path, commonHeaders, request, String.class); return MsoUtil.wrapResponse(response); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -335,28 +328,29 @@ public class MsoRestClientNew implements MsoInterface { public MsoResponseWrapper replaceInstance(org.onap.vid.changeManagement.RequestDetails request, String path) { String methodName = "replaceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Replace VNF, path =[" + path + "]"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " calling Replace VNF, path =[" + path + "]"); + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); + requestDetailsWrapper.requestDetails = new MsoRequestDetails(request); - HttpResponse response = client.post(path, commonHeaders, request, String.class); + HttpResponse response = client.post(path, commonHeaders, requestDetailsWrapper, String.class); MsoResponseWrapper msoResponseWrapperObject = MsoUtil.wrapResponse(response); int status = msoResponseWrapperObject.getStatus(); if (status == 202) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + + logger.debug(EELFLoggerDelegate.debugLogger, methodName + ",post succeeded, msoResponseWrapperObject response:" + msoResponseWrapperObject.getResponse()); } else { - logger.error(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + + logger.error(EELFLoggerDelegate.debugLogger, methodName + ": post failed, msoResponseWrapperObject status" + status + ", response:" + msoResponseWrapperObject.getResponse()); - // TODO } return msoResponseWrapperObject; } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } @@ -365,7 +359,7 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) { String methodName = "updateVnf"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); String path = baseUrl + endpoint; RequestDetailsWrapper wrapper = new RequestDetailsWrapper(); @@ -375,20 +369,22 @@ public class MsoRestClientNew implements MsoInterface { public MsoResponseWrapper updateInstance(org.onap.vid.changeManagement.RequestDetails request, String path) { String methodName = "updateInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " calling Delete, path =[" + path + "]"); - HttpResponse response = client.post(path, commonHeaders, request, String.class); + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); + requestDetailsWrapper.requestDetails = new MsoRequestDetails(request); + HttpResponse response = client.put(path, commonHeaders, requestDetailsWrapper, String.class); MsoResponseWrapper w = MsoUtil.wrapResponse(response); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " w=" + w.getResponse()); return w; } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } @@ -396,16 +392,16 @@ public class MsoRestClientNew implements MsoInterface { public void setServiceInstanceStatus(RequestDetails requestDetails, String t, String sourceId, String endpoint, RestObject restObject) { String methodName = "activateServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start "); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start "); try { String path = baseUrl + endpoint; HttpResponse response = client.post(path, commonHeaders, requestDetails, String.class); MsoResponseWrapper w = MsoUtil.wrapResponse(response); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w =" + w.getResponse()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " w =" + w.getResponse()); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -413,16 +409,16 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String endpoint) { String methodName = "removeRelationshipFromServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Remove relationship from service instance, path =[" + endpoint + "]"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " calling Remove relationship from service instance, path =[" + endpoint + "]"); String path = baseUrl + endpoint; HttpResponse response = client.post(path, commonHeaders, requestDetails, String.class); return MsoUtil.wrapResponse(response); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -430,43 +426,45 @@ public class MsoRestClientNew implements MsoInterface { @Override public MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath) { String methodName = "addRelationshipToServiceInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Add relationship to service instance, path =[" + addRelationshipsPath + "]"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " calling Add relationship to service instance, path =[" + addRelationshipsPath + "]"); String path = baseUrl + addRelationshipsPath; HttpResponse response = client.post(path, commonHeaders, requestDetails, String.class); return MsoUtil.wrapResponse(response); } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.info(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @Override - public HttpResponse get(String path, Class responseClass) { + public HttpResponse get(String endpoint, Class responseClass) { + String path = baseUrl + endpoint; return client.get(path, commonHeaders, new HashMap<>(), responseClass); } @Override - public HttpResponse post(String path, RequestDetailsWrapper requestDetailsWrapper, - Class responseClass) { + public HttpResponse post(String endpoint, RequestDetailsWrapper requestDetailsWrapper, Class responseClass) { + String path = baseUrl + endpoint; + return client.post(path, commonHeaders, requestDetailsWrapper, responseClass); } - private MsoResponseWrapper createInstance(Object request, String endpoint) { + private MsoResponseWrapper createInstance(Object request, String path) { String methodName = "createInstance"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(methodName + START); try { - HttpResponse response = client.post(endpoint, commonHeaders, request, String.class); + HttpResponse response = client.post(path, commonHeaders, request, String.class); return MsoUtil.wrapResponse(response); } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } } @@ -481,20 +479,20 @@ public class MsoRestClientNew implements MsoInterface { */ private MsoResponseWrapper deleteInstance(Object request, String path) { String methodName = "deleteInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " calling Delete, path =[" + path + "]"); HttpResponse response = client.delete(path, commonHeaders, request, String.class); MsoResponseWrapper w = MsoUtil.wrapResponse(response); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + " w=" + w.getResponse()); return w; } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.error(EELFLoggerDelegate.errorLogger, "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "." + methodName + e.toString()); throw e; } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstance.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstance.java index 3fd4cd4d..2f64e3a5 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstance.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedInstance.java @@ -20,40 +20,92 @@ package org.onap.vid.mso.rest; -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.*; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; +import org.onap.vid.mso.model.ModelInfo; + +import java.util.HashMap; +import java.util.Map; /** * modelInfo and optional instanceId and instanceName for a model related to the modelInfo being operated on. */ @JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "instanceName", "instanceId", "modelInfo" }) -public class RelatedInstance extends org.onap.vid.domain.mso.RelatedInstance{ +public class RelatedInstance { + + /** + * optional name for the instance Id of the related model + * + */ + @JsonProperty("instanceName") + private String instanceName; + /** + * instance Id for the related model + * + */ + @JsonProperty("instanceId") + private String instanceId; /** The model info. */ @JsonProperty("modelInfo") - private org.onap.vid.domain.mso.ModelInfo modelInfo; + private ModelInfo modelInfo; /** The additional properties. */ @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); + + /** + * optional name for the instance Id of the related model + * + * @return + * The instanceName + */ + @JsonProperty("instanceName") + public String getInstanceName() { + return instanceName; + } + + /** + * optional name for the instance Id of the related model + * + * @param instanceName + * The instanceName + */ + @JsonProperty("instanceName") + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + /** + * instance Id for the related model + * + * @return + * The instanceId + */ + @JsonProperty("instanceId") + public String getInstanceId() { + return instanceId; + } + + /** + * instance Id for the related model + * + * @param instanceId + * The instanceId + */ + @JsonProperty("instanceId") + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } /** * (Required). @@ -61,7 +113,7 @@ public class RelatedInstance extends org.onap.vid.domain.mso.RelatedInstance{ * @return The modelInfo */ @JsonProperty("modelInfo") - public org.onap.vid.domain.mso.ModelInfo getModelInfo() { + public ModelInfo getModelInfo() { return modelInfo; } @@ -71,7 +123,7 @@ public class RelatedInstance extends org.onap.vid.domain.mso.RelatedInstance{ * @param modelInfo The modelInfo */ @JsonProperty("modelInfo") - public void setModelInfo(org.onap.vid.domain.mso.ModelInfo modelInfo) { + public void setModelInfo(ModelInfo modelInfo) { this.modelInfo = modelInfo; } @@ -115,7 +167,7 @@ public class RelatedInstance extends org.onap.vid.domain.mso.RelatedInstance{ if (other == this) { return true; } - if ((other instanceof RelatedInstance) == false) { + if (!(other instanceof RelatedInstance)) { return false; } RelatedInstance rhs = ((RelatedInstance) other); diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedModel.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedModel.java deleted file mode 100644 index 36487c59..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RelatedModel.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.mso.rest; - -import java.util.HashMap; -import java.util.Map; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; - - -/** - * modelInfo and optional instance id for a model related to the modelInfo being operated on. - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "instanceId", - "modelInfo" -}) -public class RelatedModel extends org.onap.vid.domain.mso.RelatedModel { - - /** (Required). */ - @JsonProperty("modelInfo") - private org.onap.vid.domain.mso.ModelInfo modelInfo; - -// /** The related model object instance list. */ -// @JsonProperty("instanceId") -// private org.onap.vid.domain.mso.InstanceIds instanceId; - - /** The additional properties. */ - @JsonIgnore - private Map additionalProperties = new HashMap(); - - /** - * (Required). - * - * @return The modelInfo - */ - @JsonProperty("modelInfo") - public org.onap.vid.domain.mso.ModelInfo getModelInfo() { - return modelInfo; - } - - /** - * (Required). - * - * @param modelInfo The modelInfo - */ - @JsonProperty("modelInfo") - public void setModelInfo(org.onap.vid.domain.mso.ModelInfo modelInfo) { - this.modelInfo = modelInfo; - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.RelatedModel#toString() - */ - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.RelatedModel#getAdditionalProperties() - */ - @JsonAnyGetter - public Map getAdditionalProperties() { - return this.additionalProperties; - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.RelatedModel#setAdditionalProperty(java.lang.String, java.lang.Object) - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.RelatedModel#hashCode() - */ - @Override - public int hashCode() { - return new HashCodeBuilder().append(getInstanceId()).append(modelInfo).append(additionalProperties).toHashCode(); - } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.RelatedModel#equals(java.lang.Object) - */ - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof RelatedModel) == false) { - return false; - } - RelatedModel rhs = ((RelatedModel) other); - return new EqualsBuilder().append(getInstanceId(), rhs.getInstanceId()).append(modelInfo, rhs.modelInfo).append(additionalProperties, rhs.additionalProperties).isEquals(); - } - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/Request.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/Request.java index ee1652e7..91739937 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/Request.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/Request.java @@ -20,44 +20,89 @@ package org.onap.vid.mso.rest; -//import java.util.HashMap; -//import java.util.Map; -//import javax.annotation.Generated; - -import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.onap.vid.domain.mso.InstanceIds; -import org.onap.vid.domain.mso.RequestStatus; -//import com.fasterxml.jackson.annotation.JsonAnyGetter; -//import com.fasterxml.jackson.annotation.JsonAnySetter; -//import com.fasterxml.jackson.annotation.JsonCreator; -//import com.fasterxml.jackson.annotation.JsonIgnore; -//import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -//import com.fasterxml.jackson.annotation.JsonPropertyOrder; -//import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.*; import org.apache.commons.lang.builder.EqualsBuilder; -//import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; + +import java.util.HashMap; +import java.util.Map; /** * request structure. */ -public class Request extends org.onap.vid.domain.mso.Request { +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "finishTime", + "instanceIds", + "requestDetails", + "requestId", + "requestScope", + "requestStatus", + "requestType", + "startTime" +}) +public class Request { /** The instance ids. */ + @JsonProperty("instanceIds") private InstanceIds instanceIds; /** The request details. */ + @JsonProperty("requestDetails") private RequestDetails requestDetails; /** The request status. */ + @JsonProperty("requestStatus") private RequestStatus requestStatus; - - + + /** + * Date and time the request was finished in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT + * + */ + @JsonProperty("finishTime") + private String finishTime; + + /** + * UUID for the request generated by the instantiation service + * (Required) + * + */ + @JsonProperty("requestId") + private String requestId; + + /** + * short description of the entity being operated on + * (Required) + * + */ + @JsonProperty("requestScope") + private String requestScope; + + /** + * short description of the action being performed on the requestScope + * (Required) + * + */ + @JsonProperty("requestType") + private String requestType; + + /** + * Date and time the request was created in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT + * (Required) + * + */ + @JsonProperty("startTime") + private String startTime; + + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /* (non-Javadoc) - * @see org.onap.vid.domain.mso.Request#getInstanceIds() + * @see org.openecomp.vid.domain.mso.Request#getInstanceIds() */ @JsonProperty("instanceIds") public InstanceIds getInstanceIds() { @@ -115,32 +160,154 @@ public class Request extends org.onap.vid.domain.mso.Request { this.requestStatus = requestStatus; } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.Request#toString() + /** + * Date and time the request was finished in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT + * + * @return + * The finishTime + */ + @JsonProperty("finishTime") + public String getFinishTime() { + return finishTime; + } + + /** + * Date and time the request was finished in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT + * + * @param finishTime + * The finishTime + */ + @JsonProperty("finishTime") + public void setFinishTime(String finishTime) { + this.finishTime = finishTime; + } + + /** + * UUID for the request generated by the instantiation service + * (Required) + * + * @return + * The requestId + */ + @JsonProperty("requestId") + public String getRequestId() { + return requestId; + } + + /** + * UUID for the request generated by the instantiation service + * (Required) + * + * @param requestId + * The requestId */ + @JsonProperty("requestId") + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + /** + * short description of the entity being operated on + * (Required) + * + * @return + * The requestScope + */ + @JsonProperty("requestScope") + public String getRequestScope() { + return requestScope; + } + + /** + * short description of the entity being operated on + * (Required) + * + * @param requestScope + * The requestScope + */ + @JsonProperty("requestScope") + public void setRequestScope(String requestScope) { + this.requestScope = requestScope; + } + + /** + * short description of the action being performed on the requestScope + * (Required) + * + * @return + * The requestType + */ + @JsonProperty("requestType") + public String getRequestType() { + return requestType; + } + + /** + * short description of the action being performed on the requestScope + * (Required) + * + * @param requestType + * The requestType + */ + @JsonProperty("requestType") + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + /** + * Date and time the request was created in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT + * (Required) + * + * @return + * The startTime + */ + @JsonProperty("startTime") + public String getStartTime() { + return startTime; + } + + /** + * Date and time the request was created in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT + * (Required) + * + * @param startTime + * The startTime + */ + @JsonProperty("startTime") + public void setStartTime(String startTime) { + this.startTime = startTime; + } + @Override public String toString() { return ToStringBuilder.reflectionToString(this); } - - /* (non-Javadoc) - * @see org.onap.vid.domain.mso.Request#equals(java.lang.Object) - */ + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37).append(getFinishTime()).append(getInstanceIds()).append(getRequestDetails()).append(getRequestId()).append(getRequestScope()).append(getRequestStatus()).append(getRequestType()).append(getStartTime()).append(getAdditionalProperties()).toHashCode(); + } + @Override public boolean equals(Object other) { if (other == this) { return true; } - if ((other instanceof Request) == false) { + if (!(other instanceof Request)) { return false; } Request rhs = ((Request) other); return new EqualsBuilder().append(getFinishTime(), rhs.getFinishTime()).append(getInstanceIds(), rhs.getInstanceIds()).append(getRequestDetails(), rhs.getRequestDetails()).append(getRequestId(), rhs.getRequestId()).append(getRequestScope(), rhs.getRequestScope()).append(getRequestStatus(), rhs.getRequestStatus()).append(getRequestType(), rhs.getRequestType()).append(getStartTime(), rhs.getStartTime()).append(getAdditionalProperties(), rhs.getAdditionalProperties()).isEquals(); } - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37).append(getFinishTime()).append(getInstanceIds()).append(getRequestDetails()).append(getRequestId()).append(getRequestScope()).append(getRequestStatus()).append(getRequestType()).append(getStartTime()).append(getAdditionalProperties()).toHashCode(); - } } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java index 2b159f81..da6d46da 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestDetails.java @@ -20,20 +20,15 @@ package org.onap.vid.mso.rest; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.*; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; -import org.onap.vid.domain.mso.CloudConfiguration; -import org.onap.vid.domain.mso.ModelInfo; -import org.onap.vid.domain.mso.RequestInfo; -import org.onap.vid.domain.mso.RequestParameters; -import org.onap.vid.domain.mso.SubscriberInfo; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.mso.model.RequestInfo; +import org.onap.vid.mso.model.RequestParameters; import java.util.HashMap; import java.util.List; @@ -86,7 +81,7 @@ public class RequestDetails{ /** The additional properties. */ @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); /** * Gets the cloud configuration. @@ -269,4 +264,26 @@ public class RequestDetails{ public void setRequestParameters(RequestParameters requestParameters) { this.requestParameters = requestParameters; } + + public T extractValueByPathUsingAdditionalProperties (List keys, Class clazz) { + Object result = getAdditionalProperties(); + for (String key : keys) { + if (result instanceof Map) { + result = ((Map) result).get(key); + } + + else { + throw new NotFoundException("failed to find key: "+key+" in path: "+String.join("\\", keys)); + } + } + if (clazz.isInstance(result)) { + return clazz.cast(result); + } + + throw new NotFoundException( + String.format("failed to extract value from path:%s because %s is not of type %s", + String.join("\\", keys), String.valueOf(result) , clazz)); + } + + } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestList.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestList.java index 8f8272c0..00289da6 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestList.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestList.java @@ -20,30 +20,19 @@ package org.onap.vid.mso.rest; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.Generated; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -//import com.fasterxml.jackson.annotation.JsonInclude; -//import com.fasterxml.jackson.annotation.JsonProperty; -//import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.*; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; import java.util.List; +import java.util.Map; /** * List of relatedModel structures that are related to a modelInfo being operated on. */ @JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "finishTime", "instanceIds", @@ -62,7 +51,7 @@ public class RequestList { /** The additional properties. */ @JsonIgnore - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap<>(); /** * (Required). @@ -127,7 +116,7 @@ public class RequestList { if (other == this) { return true; } - if ((other instanceof RequestList) == false) { + if (!(other instanceof RequestList)) { return false; } RequestList rhs = ((RequestList) other); diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestStatus.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestStatus.java new file mode 100644 index 00000000..f9c89045 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RequestStatus.java @@ -0,0 +1,208 @@ + +package org.onap.vid.mso.rest; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + + +/** + * fields describing the status of a request + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "percentProgress", + "requestState", + "statusMessage", + "timestamp", + "wasRolledBack" +}) +public class RequestStatus { + + /** + * percentage complete estimate from 0 to 100 + * + */ + @JsonProperty("percentProgress") + private Double percentProgress; + /** + * short description of the instantiation state + * (Required) + * + */ + @JsonProperty("requestState") + private String requestState; + /** + * additional descriptive information about the status + * + */ + @JsonProperty("statusMessage") + private String statusMessage; + /** + * GMT Datetime the requestStatus was created e.g.: Wed, 15 Oct 2014 13:01:52 GMT + * (Required) + * + */ + @JsonProperty("timestamp") + private String timestamp; + /** + * true or false boolean indicating whether the request was rolled back + * + */ + @JsonProperty("wasRolledBack") + private Boolean wasRolledBack; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * percentage complete estimate from 0 to 100 + * + * @return + * The percentProgress + */ + @JsonProperty("percentProgress") + public Double getPercentProgress() { + return percentProgress; + } + + /** + * percentage complete estimate from 0 to 100 + * + * @param percentProgress + * The percentProgress + */ + @JsonProperty("percentProgress") + public void setPercentProgress(Double percentProgress) { + this.percentProgress = percentProgress; + } + + /** + * short description of the instantiation state + * (Required) + * + * @return + * The requestState + */ + @JsonProperty("requestState") + public String getRequestState() { + return requestState; + } + + /** + * short description of the instantiation state + * (Required) + * + * @param requestState + * The requestState + */ + @JsonProperty("requestState") + public void setRequestState(String requestState) { + this.requestState = requestState; + } + + /** + * additional descriptive information about the status + * + * @return + * The statusMessage + */ + @JsonProperty("statusMessage") + public String getStatusMessage() { + return statusMessage; + } + + /** + * additional descriptive information about the status + * + * @param statusMessage + * The statusMessage + */ + @JsonProperty("statusMessage") + public void setStatusMessage(String statusMessage) { + this.statusMessage = statusMessage; + } + + /** + * GMT Datetime the requestStatus was created e.g.: Wed, 15 Oct 2014 13:01:52 GMT + * (Required) + * + * @return + * The timestamp + */ + @JsonProperty("timestamp") + public String getTimestamp() { + return timestamp; + } + + /** + * GMT Datetime the requestStatus was created e.g.: Wed, 15 Oct 2014 13:01:52 GMT + * (Required) + * + * @param timestamp + * The timestamp + */ + @JsonProperty("timestamp") + public void setTimestamp(String timestamp) { + this.timestamp = timestamp; + } + + /** + * true or false boolean indicating whether the request was rolled back + * + * @return + * The wasRolledBack + */ + @JsonProperty("wasRolledBack") + public Boolean getWasRolledBack() { + return wasRolledBack; + } + + /** + * true or false boolean indicating whether the request was rolled back + * + * @param wasRolledBack + * The wasRolledBack + */ + @JsonProperty("wasRolledBack") + public void setWasRolledBack(Boolean wasRolledBack) { + this.wasRolledBack = wasRolledBack; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(percentProgress).append(requestState).append(statusMessage).append(timestamp).append(wasRolledBack).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof RequestStatus)) { + return false; + } + RequestStatus rhs = ((RequestStatus) other); + return new EqualsBuilder().append(percentProgress, rhs.percentProgress).append(requestState, rhs.requestState).append(statusMessage, rhs.statusMessage).append(timestamp, rhs.timestamp).append(wasRolledBack, rhs.wasRolledBack).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java index feb3f3c1..ec117cf0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java @@ -1,30 +1,25 @@ package org.onap.vid.mso.rest; +import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.mso.RestObject; - -import javax.ws.rs.core.MultivaluedHashMap; +import org.onap.vid.mso.RestObjectWithRequestInfo; /** * Created by pickjonathan on 26/06/2017. */ public interface RestInterface { - /** - * Inits the rest client. - */ - MultivaluedHashMap initMsoClient(); - /** * Gets the. * * @param the generic type * @param t the t - * @param sourceId the source id * @param path the path * @param restObject the rest object + * @param warpException * @throws Exception the exception */ - void Get (T t, String sourceId, String path, RestObject restObject ); + RestObjectWithRequestInfo Get(T t, String path, RestObject restObject, boolean warpException); /** * Delete. @@ -32,25 +27,22 @@ public interface RestInterface { * @param the generic type * @param t the t * @param r the r - * @param sourceID the source ID * @param path the path * @param restObject the rest object * @throws Exception the exception */ - void Delete(T t, Object r, String sourceID, String path, RestObject restObject); + void Delete(T t, Object r, String path, RestObject restObject); /** * Post. * - * @param the generic type * @param t the t * @param r the r - * @param sourceID the source ID * @param path the path * @param restObject the rest object * @throws Exception the exception */ - void Post(T t, Object r, String sourceID, String path, RestObject restObject); + void Post(String t, Object r, String path, RestObject restObject); /** * Put. @@ -58,11 +50,12 @@ public interface RestInterface { * @param the generic type * @param t the t * @param r the r - * @param sourceID the source ID * @param path the path * @param restObject the rest object * @throws Exception the exception */ - void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String sourceID, String path, RestObject restObject); + void Put(T t, RequestDetailsWrapper r, String path, RestObject restObject); + + RestObject GetForObject(String path, Class clazz); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/SubscriberInfo.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/SubscriberInfo.java new file mode 100644 index 00000000..0c8d7c2a --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/SubscriberInfo.java @@ -0,0 +1,144 @@ + +package org.onap.vid.mso.rest; + +import com.fasterxml.jackson.annotation.*; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +import java.util.HashMap; +import java.util.Map; + + +/** + * fields providing information about the subscriber associated with the request + * + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "globalSubscriberId", + "subscriberCommonSiteId", + "subscriberName" +}) +public class SubscriberInfo { + + /** + * global Customer Id understood by A&AI + * + */ + @JsonProperty("globalSubscriberId") + private String globalSubscriberId; + /** + * id representing the location of the subscriber + * + */ + @JsonProperty("subscriberCommonSiteId") + private String subscriberCommonSiteId; + /** + * name of the customer or subscriber + * + */ + @JsonProperty("subscriberName") + private String subscriberName; + @JsonIgnore + private Map additionalProperties = new HashMap<>(); + + /** + * global Customer Id understood by A&AI + * + * @return + * The globalSubscriberId + */ + @JsonProperty("globalSubscriberId") + public String getGlobalSubscriberId() { + return globalSubscriberId; + } + + /** + * global Customer Id understood by A&AI + * + * @param globalSubscriberId + * The globalSubscriberId + */ + @JsonProperty("globalSubscriberId") + public void setGlobalSubscriberId(String globalSubscriberId) { + this.globalSubscriberId = globalSubscriberId; + } + + /** + * id representing the location of the subscriber + * + * @return + * The subscriberCommonSiteId + */ + @JsonProperty("subscriberCommonSiteId") + public String getSubscriberCommonSiteId() { + return subscriberCommonSiteId; + } + + /** + * id representing the location of the subscriber + * + * @param subscriberCommonSiteId + * The subscriberCommonSiteId + */ + @JsonProperty("subscriberCommonSiteId") + public void setSubscriberCommonSiteId(String subscriberCommonSiteId) { + this.subscriberCommonSiteId = subscriberCommonSiteId; + } + + /** + * name of the customer or subscriber + * + * @return + * The subscriberName + */ + @JsonProperty("subscriberName") + public String getSubscriberName() { + return subscriberName; + } + + /** + * name of the customer or subscriber + * + * @param subscriberName + * The subscriberName + */ + @JsonProperty("subscriberName") + public void setSubscriberName(String subscriberName) { + this.subscriberName = subscriberName; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(globalSubscriberId).append(subscriberCommonSiteId).append(subscriberName).append(additionalProperties).toHashCode(); + } + + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + if (!(other instanceof SubscriberInfo)) { + return false; + } + SubscriberInfo rhs = ((SubscriberInfo) other); + return new EqualsBuilder().append(globalSubscriberId, rhs.globalSubscriberId).append(subscriberCommonSiteId, rhs.subscriberCommonSiteId).append(subscriberName, rhs.subscriberName).append(additionalProperties, rhs.additionalProperties).isEquals(); + } + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyProperties.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyProperties.java deleted file mode 100644 index 940adddb..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyProperties.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.onap.vid.policy; - -import org.onap.portalsdk.core.util.SystemProperties; - - -public class PolicyProperties extends SystemProperties { - - public static final String POLICY_CLIENTAUTH_VAL = "policy.ClientAuth"; - - public static final String POLICY_CLIENT_MECHID_VAL = "policy.client.mechId"; - - public static final String POLICY_CLIENT_PASSWORD_VAL = "policy.client.password"; - - public static final String POLICY_USERNAME_VAL = "policy.username"; - - public static final String POLICY_PASSWORD_VAL = "policy.password"; - - public static final String POLICY_AUTHORIZATION_VAL = "policy.Authorization"; - - public static final String POLICY_SERVER_URL_VAL = "policy.server.url"; - - public static final String POLICY_ENVIRONMENT_VAL = "policy.environment"; - - public static final String POLICY_GET_CONFIG_VAL = "policy.get.config"; - -} diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyResponseWrapper.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyResponseWrapper.java deleted file mode 100644 index d5a4d124..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyResponseWrapper.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.onap.vid.policy; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.ToStringBuilder; - -/** - * This wrapper encapsulates the Policy response - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "status", - "entity" -}) - -public class PolicyResponseWrapper { - - @JsonProperty("status") - private int status; - - @JsonProperty("entity") - private String entity; - - @JsonProperty("entity") - public String getEntity() { - return entity; - } - - @JsonProperty("status") - public int getStatus() { - return status; - } - - @JsonProperty("status") - public void setStatus(int v) { - this.status = v; - } - - @JsonProperty("entity") - public void setEntity(String v) { - this.entity = v; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - public String getResponse () { - - StringBuilder b = new StringBuilder ("{ \"status\": "); - b.append(getStatus()).append(", \"entity\": " ).append(this.getEntity()).append("}"); - return (b.toString()); - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInt.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInt.java deleted file mode 100644 index 65dcb818..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInt.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.policy; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.policy.rest.RequestDetails; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class PolicyRestInt { - - /** The logger. */ - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInt.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - /** The request date format. */ - public DateFormat requestDateFormat = new SimpleDateFormat("EEE, dd MMM YYYY HH:mm:ss z"); - - public PolicyRestInt() { - requestDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT")); - } - - /** - * Log request. - * - * @param r the r - */ - public void logRequest ( RequestDetails r ) { - String methodName = "logRequest"; - ObjectMapper mapper = new ObjectMapper(); - String r_json_str = ""; - if ( r != null ) { - r_json_str = r.toString(); - try { - r_json_str = mapper.writeValueAsString(r); - } - catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse request as json"); - } - } - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Request=(" + r_json_str + ")"); - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java deleted file mode 100644 index e550f026..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterface.java +++ /dev/null @@ -1,230 +0,0 @@ -package org.onap.vid.policy; - -import org.apache.commons.codec.binary.Base64; -import org.eclipse.jetty.util.security.Password; -import org.json.simple.JSONObject; -import org.onap.vid.client.HttpBasicClient; -import org.onap.vid.exceptions.GenericUncheckedException; -import org.onap.vid.policy.rest.RequestDetails; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; - -public class PolicyRestInterface extends PolicyRestInt implements PolicyRestInterfaceIfc { - - /** The logger. */ - private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyRestInterface.class); - - public static final String APPLICATION_JSON = "application/json"; - - /** The client. */ - private static Client client = null; - - /** The common headers. */ - private MultivaluedHashMap commonHeaders; - public PolicyRestInterface() { - super(); - } - - /** The Constant dateFormat. */ - static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - public void initRestClient() - { - final String methodname = "initRestClient()"; - - final String mechId = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_MECHID_VAL); - final String clientPassword = SystemProperties.getProperty(PolicyProperties.POLICY_CLIENT_PASSWORD_VAL); - final String username = SystemProperties.getProperty(PolicyProperties.POLICY_USERNAME_VAL); - final String password = SystemProperties.getProperty(PolicyProperties.POLICY_PASSWORD_VAL); - final String environment = SystemProperties.getProperty(PolicyProperties.POLICY_ENVIRONMENT_VAL); - - final String decrypted_client_password = Password.deobfuscate(clientPassword); - String mechAuthString = mechId + ":" + decrypted_client_password; - byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes()); - String clientAuth = new String(mechAuthEncBytes); - - final String decrypted_password = Password.deobfuscate(password); - String authString = username + ":" + decrypted_password; - byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); - String authorization = new String(authEncBytes); - - commonHeaders = new MultivaluedHashMap<> (); - commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth))); - commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization))); - commonHeaders.put("Environment", Collections.singletonList((Object) (environment))); - - if (client == null) { - - try { - client = HttpBasicClient.getClient(); - } catch (Exception e) { - System.out.println( methodname + " Unable to get the SSL client"); - } - } - } - - @SuppressWarnings("unchecked") - public void Get (T t, String sourceId, String path, RestObject restObject ) { - String methodName = "Get"; - - logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start"); - - String url=""; - restObject.set(t); - - url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " sending request to url= " + url); - - initRestClient(); - - final Response cres = client.target(url) - .request() - .accept(APPLICATION_JSON) - .headers(commonHeaders) - .get(); - - int status = cres.getStatus(); - restObject.setStatusCode (status); - - if (status == 200) { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + methodName + " REST api was successfull!"); - - } else { - throw new GenericUncheckedException(methodName + " with status="+ status + ", url= " + url ); - } - - logger.debug(EELFLoggerDelegate.debugLogger,methodName + " received status=" + status ); - - return; - } - - @SuppressWarnings("unchecked") - public void Delete(T t, RequestDetails r, String sourceID, String path, RestObject restObject) { - - String methodName = "Delete"; - String url=""; - Response cres = null; - - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " start"); - logRequest (r); - - try { - initRestClient(); - - url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + " methodName sending request to: " + url); - - cres = client.target(url) - .request() - .accept(APPLICATION_JSON) - .headers(commonHeaders) - //.entity(r) - .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke(); - - int status = cres.getStatus(); - restObject.setStatusCode (status); - - if (status == 404) { // resource not found - String msg = "Resource does not exist...: " + cres.getStatus(); - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); - } else if (status == 200 || status == 204){ - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + "Resource " + url + " deleted"); - } else if (status == 202) { - String msg = "Delete in progress: " + status; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); - } - else { - String msg = "Deleting Resource failed: " + status; - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + msg); - } - - try { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " No response entity, this is probably ok, e=" - + e.getMessage()); - } - - } - catch (Exception e) - { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); - throw e; - - } - } - - @SuppressWarnings("unchecked") - public void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject restObject) { - - String methodName = "Post"; - String url=""; - - System.out.println( "POST policy rest interface"); - - try { - - initRestClient(); - - url = SystemProperties.getProperty(PolicyProperties.POLICY_SERVER_URL_VAL) + path; - System.out.println( "<== " + methodName + " sending request to url= " + url); - // Change the content length - final Response cres = client.target(url) - .request() - .accept(APPLICATION_JSON) - .headers(commonHeaders) - //.header("content-length", 201) - //.header("X-FromAppId", sourceID) - .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON)); - - try { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - catch ( Exception e ) { - - System.out.println("<== " + methodName + " No response entity, this is probably ok, e=" + e.getMessage()); - } - - int status = cres.getStatus(); - restObject.setStatusCode (status); - - if ( status >= 200 && status <= 299 ) { - System.out.println( "<== " + methodName + " REST api POST was successful!"); - - } else { - System.out.println( "<== " + methodName + " with status="+status+", url="+url); - } - - } catch (Exception e) - { - System.out.println( "<== " + methodName + " with url="+url+ ", Exception: " + e.toString()); - throw e; - - } - } - - public T getInstance(Class clazz) throws IllegalAccessException, InstantiationException - { - return clazz.newInstance(); - } - - @Override - public void logRequest(RequestDetails r) { - // TODO Auto-generated method stub - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceFactory.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceFactory.java deleted file mode 100644 index 40cb854b..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceFactory.java +++ /dev/null @@ -1,14 +0,0 @@ - -package org.onap.vid.policy; - -public class PolicyRestInterfaceFactory { - - - public static PolicyRestInterfaceIfc getInstance () { - PolicyRestInterfaceIfc obj = null; - - obj = new PolicyRestInterface(); - - return ( obj ); - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java deleted file mode 100644 index 61108fc5..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyRestInterfaceIfc.java +++ /dev/null @@ -1,58 +0,0 @@ - -package org.onap.vid.policy; - -import org.json.simple.JSONObject; -import org.onap.vid.policy.rest.RequestDetails; - -public interface PolicyRestInterfaceIfc { - /** - * Inits the rest client. - */ - public void initRestClient(); - - /** - * Gets the. - * - * @param the generic type - * @param t the t - * @param sourceId the source id - * @param path the path - * @param restObject the rest object - * @throws Exception the exception - */ - public void Get (T t, String sourceId, String path, RestObject restObject ); - - /** - * Delete. - * - * @param the generic type - * @param t the t - * @param r the r - * @param sourceID the source ID - * @param path the path - * @param restObject the rest object - * @throws Exception the exception - */ - public void Delete(T t, RequestDetails r, String sourceID, String path, RestObject restObject); - - /** - * Post. - * - * @param the generic type - * @param t the t - * @param r the r - * @param sourceID the source ID - * @param path the path - * @param restObject the rest object - * @throws Exception the exception - */ - public void Post(T t, JSONObject r, String sourceID, String path, RestObject restObject); - - /*** - * Log request. - * - * @param r the r - */ - public void logRequest ( RequestDetails r ); - -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyUtil.java b/vid-app-common/src/main/java/org/onap/vid/policy/PolicyUtil.java deleted file mode 100644 index 74056975..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/PolicyUtil.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.onap.vid.policy; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.glassfish.jersey.client.ClientResponse; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.policy.PolicyResponseWrapper; -import org.onap.vid.policy.PolicyUtil; -import org.onap.vid.policy.RestObject; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class PolicyUtil { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PolicyUtil.class); - - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); - - public static PolicyResponseWrapper wrapResponse ( String body, int statusCode ) { - - PolicyResponseWrapper w = new PolicyResponseWrapper(); - w.setStatus (statusCode); - w.setEntity(body); - - return w; - } - - public static PolicyResponseWrapper wrapResponse (ClientResponse cres) { - String resp_str = ""; - if ( cres != null ) { - resp_str = cres.readEntity(String.class); - } - int statuscode = cres.getStatus(); - PolicyResponseWrapper w = PolicyUtil.wrapResponse ( resp_str, statuscode ); - return (w); - } - - public static PolicyResponseWrapper wrapResponse (RestObject rs) { - String resp_str = ""; - int status = 0; - if ( rs != null ) { - resp_str = rs.get(); - status = rs.getStatusCode(); - } - PolicyResponseWrapper w = PolicyUtil.wrapResponse ( resp_str, status ); - return (w); - } - - public static String convertPojoToString ( T t ) throws com.fasterxml.jackson.core.JsonProcessingException { - - String methodName = "convertPojoToString"; - ObjectMapper mapper = new ObjectMapper(); - String r_json_str = ""; - if ( t != null ) { - try { - r_json_str = mapper.writeValueAsString(t); - } - catch ( com.fasterxml.jackson.core.JsonProcessingException j ) { - logger.debug(EELFLoggerDelegate.debugLogger,dateFormat.format(new Date()) + "<== " + methodName + " Unable to parse object as json"); - } - } - return (r_json_str); - } - - - public static void main(String[] args) { - // TODO Auto-generated method stub - } -} diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/RestObject.java b/vid-app-common/src/main/java/org/onap/vid/policy/RestObject.java deleted file mode 100644 index 81b354eb..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/RestObject.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.policy; - -/** - * The Class RestObject. - * - * @param the generic type - */ -public class RestObject { - - /** - * Generic version of the RestObject class. - * - */ - // T stands for "Type" - private T t; - - /** The status code. */ - private int statusCode= 0; - - /** - * Sets the. - * - * @param t the t - */ - public void set(T t) { this.t = t; } - - /** - * Gets the. - * - * @return the t - */ - public T get() { return t; } - - /** - * Sets the status code. - * - * @param v the new status code - */ - public void setStatusCode(int v) { this.statusCode = v; } - - /** - * Gets the status code. - * - * @return the status code - */ - public int getStatusCode() { return this.statusCode; } - -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/policy/rest/RequestDetails.java b/vid-app-common/src/main/java/org/onap/vid/policy/rest/RequestDetails.java deleted file mode 100644 index 81e2f2d8..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/policy/rest/RequestDetails.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.policy.rest; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -/* - [ - { - "policyConfigMessage": "Config Retrieved! ", - "policyConfigStatus": "CONFIG_RETRIEVED", - "type": "JSON", - "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_zone_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_zone\"}}", - "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_zone_localTime.1.xml", - "policyVersion": "1", - "matchingConditions": { - "ECOMPName": "SNIRO-Placement", - "ConfigName": "", - "service": "TimeLimitAndVerticalTopology", - "uuid": "", - "Location": "" - }, - "responseAttributes": {}, - "property": null - }, - { - "policyConfigMessage": "Config Retrieved! ", - "policyConfigStatus": "CONFIG_RETRIEVED", - "type": "JSON", - "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_pserver_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf_pserver\"}}", - "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_pserver_localTime.1.xml", - "policyVersion": "1", - "matchingConditions": { - "ECOMPName": "SNIRO-Placement", - "ConfigName": "", - "service": "TimeLimitAndVerticalTopology", - "uuid": "", - "Location": "" - }, - "responseAttributes": {}, - "property": null - }, - { - "policyConfigMessage": "Config Retrieved! ", - "policyConfigStatus": "CONFIG_RETRIEVED", - "type": "JSON", - "config": "{\"service\":\"TimeLimitAndVerticalTopology\",\"policyName\":\"SNIRO_CM_1707.Demo_TimeLimitAndVerticalTopology_vnf_localTime\",\"description\":\"dev instance\",\"templateVersion\":\"1702.03\",\"version\":\"1707\",\"priority\":\"4\",\"riskType\":\"test\",\"riskLevel\":\"3\",\"guard\":\"False\",\"content\":{\"serviceType\":\"networkOnDemand\",\"identity\":\"vnf_upgrade_policy\",\"policyScope\":{\"serviceType\":[\"networkOnDemand\"],\"aicZone\":[\" \"],\"entityType\":[\"vnf\"]},\"timeSchedule\":{\"allowedPeriodicTime\":[{\"day\":\"weekday\",\"timeRange\":[{\"start_time\":\"04:00:00\",\"end_time\":\"13:00:00\"}]}]},\"nodeType\":[\"vnf\"],\"type\":\"timeLimitAndVerticalTopology\",\"conflictScope\":\"vnf\"}}", - "policyName": "SNIRO_CM_1707.Config_MS_Demo_TimeLimitAndVerticalTopology_vnf_localTime.1.xml", - "policyVersion": "1", - "matchingConditions": { - "ECOMPName": "SNIRO-Placement", - "ConfigName": "", - "service": "TimeLimitAndVerticalTopology", - "uuid": "", - "Location": "" - }, - "responseAttributes": {}, - "property": null - } - ] -*/ -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "policyConfigMessage", - "policyConfigStatus", - "type", - "config", - "policyName", - "policyVersion", - "matchingConditions" -}) -public class RequestDetails { - - @JsonProperty("policyName") - private String policyName; - - @JsonProperty("policyName") - public String getPolicyName() { - return policyName; - } - - @JsonProperty("policyName") - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - -} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/Features.java b/vid-app-common/src/main/java/org/onap/vid/properties/Features.java index cc623d44..6c521107 100644 --- a/vid-app-common/src/main/java/org/onap/vid/properties/Features.java +++ b/vid-app-common/src/main/java/org/onap/vid/properties/Features.java @@ -10,10 +10,8 @@ public enum Features implements Feature { */ FLAG_ASYNC_JOBS, - FLAG_REGION_ID_FROM_REMOTE, CREATE_INSTANCE_TEST, EMPTY_DRAWING_BOARD_TEST, - FLAG_ADVANCED_PORTS_FILTER, FLAG_ADD_MSO_TESTAPI_FIELD, FLAG_ASYNC_INSTANTIATION, FLAG_SERVICE_MODEL_CACHE, @@ -21,9 +19,30 @@ public enum Features implements Feature { FLAG_NETWORK_TO_ASYNC_INSTANTIATION, FLAG_COLLECTION_RESOURCE_SUPPORT, FLAG_SHOW_ASSIGNMENTS, - FLAG_SHOW_VERIFY_SERVICE, + FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS, + FLAG_SHOW_VERIFY_SERVICE, // AKA POMBA + FLAG_DUPLICATE_VNF, + FLAG_DEFAULT_VNF, FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD, - FLAG_PNP_INSTANTIATION; + FLAG_PNP_INSTANTIATION, + FLAG_RESTRICTED_SELECT, + FLAG_5G_IN_NEW_INSTANTIATION_UI, + FLAG_ASYNC_ALACARTE_VNF, + FLAG_A_LA_CARTE_AUDIT_INFO, + FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS, + FLAG_ASYNC_ALACARTE_VFMODULE, + FLAG_SUPPLEMENTARY_FILE, + FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF, + FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI, + FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY, + FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST, + FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE, + FLAG_1810_AAI_LOCAL_CACHE, + FLAG_1810_IDENTIFY_SERVICE_FOR_NEW_UI, + FLAG_1902_NEW_VIEW_EDIT, + FLAG_EXP_USE_DEFAULT_HOST_NAME_VERIFIER, + FLAG_1902_VNF_GROUPING, + ; public boolean isActive() { return FeatureContext.getFeatureManager().isActive(this); diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java b/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java index ef28ea40..88bcce87 100644 --- a/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java +++ b/vid-app-common/src/main/java/org/onap/vid/properties/FeaturesTogglingConfiguration.java @@ -24,16 +24,18 @@ public class FeaturesTogglingConfiguration { public FeatureManager featureManager(ServletContext servletContext, Environment environment) { final String defaultFilename = "features.properties"; - String filename = environment.getProperty("featureFlags.filename"); + String filename = environment.getProperty("features.set.filename"); if (StringUtils.isBlank(filename)) { filename = defaultFilename; } + filename = StringUtils.trimToNull(filename); + return new FeatureManagerBuilder() .featureEnum(Features.class) .stateRepository(new FileBasedStateRepository( - new File(servletContext.getRealPath("/WEB-INF/conf/" + filename)) + new File(filename.startsWith("/")? filename : servletContext.getRealPath("/WEB-INF/conf/" + filename)) )) .build(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java b/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java index d670e978..0a7d8d1a 100644 --- a/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java +++ b/vid-app-common/src/main/java/org/onap/vid/properties/VidProperties.java @@ -20,13 +20,10 @@ package org.onap.vid.properties; +import org.apache.commons.lang3.StringUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.model.ModelConstants; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; /** * The Class VidProperties. */ @@ -37,6 +34,7 @@ public class VidProperties extends SystemProperties { public static final String MSO_DEFAULT_TEST_API="mso.defaultTestAPI"; public static final String MSO_MAX_OPENED_INSTANTIATION_REQUESTS="mso.maxOpenedInstantiationRequests"; public static final String MSO_ASYNC_POLLING_INTERVAL_SECONDS="mso.asyncPollingIntervalSeconds"; + public static final String PROBE_SDC_MODEL_UUID="probe.sdc.model.uuid"; /** The Constant VID_TRUSTSTORE_FILENAME. */ public static final String VID_TRUSTSTORE_FILENAME = "vid.truststore.filename"; @@ -49,9 +47,9 @@ public class VidProperties extends SystemProperties { /** The Constant LOG. */ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidProperties.class); - - /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + + public static final String VID_JOB_MAX_HOURS_IN_PROGRESS = "vid.asyncJob.maxHoursInProgress"; + /** * Gets the asdc model namespace prefix property * @@ -67,7 +65,7 @@ public class VidProperties extends SystemProperties { } } catch ( Exception e ) { - LOG.error (EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodName + "unable to find the value, using the default " + LOG.error (EELFLoggerDelegate.errorLogger, methodName + "unable to find the value, using the default " + ModelConstants.DEFAULT_ASDC_MODEL_NAMESPACE); asdcModelNamespace = ModelConstants.DEFAULT_ASDC_MODEL_NAMESPACE; } @@ -88,10 +86,28 @@ public class VidProperties extends SystemProperties { } } catch ( Exception e ) { - LOG.error (EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + methodName + "unable to find the value, using the default " + LOG.error (EELFLoggerDelegate.errorLogger, methodName + "unable to find the value, using the default " + defaultValue); propValue = defaultValue; } return (propValue); } + + public static long getLongProperty(String key) { + return getLongProperty(key, 0); + } + + public static long getLongProperty(String key, long defaultValue) { + if (!containsProperty(key)) { + LOG.debug(EELFLoggerDelegate.debugLogger, "No such property: {}. {} value is used", key, defaultValue); + return defaultValue; + } + String configValue = getProperty(key); + if (StringUtils.isNumeric(configValue)) { + return Long.parseLong(configValue); + } else { + LOG.debug(EELFLoggerDelegate.debugLogger, "{} property value is not valid: {}. {} value is used", key, configValue, defaultValue); + return defaultValue; + } + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java b/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java index b83f751f..d4256f89 100644 --- a/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java +++ b/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java @@ -26,7 +26,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.joshworks.restclient.http.HttpResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.web.support.UserUtils; -import org.onap.vid.aai.AaiResponse; import org.onap.vid.aai.exceptions.RoleParsingException; import org.onap.vid.model.ModelConstants; import org.onap.vid.model.Subscriber; @@ -37,6 +36,8 @@ import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.*; +import java.util.stream.Collectors; + /** * Created by Oren on 7/1/17. @@ -46,46 +47,32 @@ import java.util.*; public class RoleProvider { private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(RoleProvider.class); - final String readPermissionString = "read"; - SubscriberList subscribers; - ObjectMapper om = new ObjectMapper(); + static final String READ_PERMISSION_STRING = "read"; + private final ObjectMapper om = new ObjectMapper(); + @Autowired private AaiService aaiService; - public static List extractRoleFromSession(HttpServletRequest request) { - - return new ArrayList(); - - } - - public void init() { - LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method started"); - HttpResponse subscribersResponse = aaiService.getFullSubscriberList(); - subscribers = subscribersResponse.getBody(); - LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method finished"); - } - public List getUserRoles(HttpServletRequest request) { String logPrefix = "Role Provider (" + UserUtils.getUserId(request) + ") ==>"; LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Entering to get user role for user " + UserUtils.getUserId(request)); List roleList = new ArrayList<>(); - Map roles = UserUtils.getRoles(request); for (Object role : roles.keySet()) { org.onap.portalsdk.core.domain.Role sdkRol = (org.onap.portalsdk.core.domain.Role) roles.get(role); LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Role " + sdkRol.getName() + " is being proccessed"); try { - if (sdkRol.getName().contains(readPermissionString)) { - LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + " Role " + sdkRol.getName() + " contain " + readPermissionString); + if (sdkRol.getName().contains(READ_PERMISSION_STRING)) { + LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + " Role " + sdkRol.getName() + " contain " + READ_PERMISSION_STRING); continue; } String[] roleParts = splitRole((sdkRol.getName()), logPrefix); roleList.add(createRoleFromStringArr(roleParts, logPrefix)); - String msg = String.format(logPrefix + " User %s got permissions %s", UserUtils.getUserId(request), Arrays.toString(roleParts)); + String msg = String.format("%s User %s got permissions %s", logPrefix, UserUtils.getUserId(request), Arrays.toString(roleParts)); LOG.debug(EELFLoggerDelegate.debugLogger, msg); } catch (Exception e) { LOG.error(logPrefix + " Failed to parse permission"); @@ -102,29 +89,30 @@ public class RoleProvider { } public boolean userPermissionIsReadOnly(List roles) { - - return (!(roles.size() > 0)); + return roles.isEmpty(); } public boolean userPermissionIsReadLogs(List roles){ for(Role role: roles){ - if(role.getServiceType().equals("LOGS")){ - if(role.getTenant().equals("PERMITTED")){ - return true; - } + if ( role.getServiceType().equals("LOGS") && role.getTenant().equals("PERMITTED") ) { + return true; } } return false; } - private String replaceSubscriberNameToGlobalCustomerID(String subscriberName, String logPrefix) throws JsonProcessingException { - if (subscribers == null) { - LOG.debug(EELFLoggerDelegate.debugLogger, "replaceSubscriberNameToGlobalCustomerID calling init method"); - init(); - } - LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer)); - LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer)); + private String replaceSubscriberNameToGlobalCustomerID(String subscriberName, String logPrefix) { + // SubscriberList should be cached by cacheProvider so by calling getFullSubscriberList() method we just gat it from cache + HttpResponse subscribersResponse = aaiService.getFullSubscriberList(); + SubscriberList subscribers = subscribersResponse.getBody(); + try { + LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is " + subscribers.customer.size() + " with the values " + om.writeValueAsString(subscribers.customer)); + } catch (JsonProcessingException e) { + // log subscriberNames without object mapper + LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "subscribers list size is " + subscribers.customer.size() + + " with the values " + subscribers.customer.stream().map(subscriber -> subscriber.subscriberName).collect(Collectors.joining(","))); + } Optional s = subscribers.customer.stream().filter(x -> x.subscriberName.equals(subscriberName)).findFirst(); //Fixing bug of logging "optional get" before isPresent @@ -133,7 +121,7 @@ public class RoleProvider { return replacement; } - public Role createRoleFromStringArr(String[] roleParts, String rolePrefix) throws JsonProcessingException, RoleParsingException { + public Role createRoleFromStringArr(String[] roleParts, String rolePrefix) throws RoleParsingException { String globalCustomerID = replaceSubscriberNameToGlobalCustomerID(roleParts[0], rolePrefix); try { if (roleParts.length > 2) { @@ -153,5 +141,8 @@ public class RoleProvider { } + public RoleValidator getUserRolesValidator(HttpServletRequest request) { + return new RoleValidator(getUserRoles(request)); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/RestObject.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/RestObject.java deleted file mode 100644 index 4accb55d..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/RestObject.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.scheduler; - - -public class RestObject { - - private T t; - - private int statusCode= 0; - - public String uuid; - - public void set(T t) { this.t = t; } - - public T get() { return t; } - - public void setStatusCode(int v) { this.statusCode = v; } - - public int getStatusCode() { return this.statusCode; } - - public void setUUID(String uuid) { this.uuid = uuid; } - - public String getUUID() { return this.uuid; } -} - diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/RestObjects/RestObject.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/RestObjects/RestObject.java deleted file mode 100644 index ff1ffb4c..00000000 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/RestObjects/RestObject.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.scheduler.RestObjects; - - -public class RestObject { - - private T t; - - private int statusCode= 0; - - public void set(T t) { this.t = t; } - - public T get() { return t; } - - public void setStatusCode(int v) { this.statusCode = v; } - - public int getStatusCode() { return this.statusCode; } - -} - diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java index a4c5b00a..c986f225 100644 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java @@ -4,12 +4,16 @@ import com.att.eelf.configuration.EELFLogger; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import io.joshworks.restclient.http.HttpResponse; +import org.apache.http.HttpException; import org.eclipse.jetty.util.security.Password; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.client.SyncRestClient; import org.onap.vid.client.SyncRestClientInterface; import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.RestObjectWithRequestInfo; import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; @@ -24,8 +28,9 @@ import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; @Service public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { - final private static EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("scheduler"); + private static final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("scheduler"); private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + private static final String SUCCESSFUL_API_MESSAGE=" REST api GET was successful!"; private SyncRestClientInterface syncRestClient; private Function propertyGetter; private Map commonHeaders; @@ -50,30 +55,43 @@ public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { logger.info("\t<== Client Initialized \n"); } - public void Get(T t, String sourceId, String path, org.onap.vid.scheduler.RestObject restObject) { - initRestClient(); - String methodName = "Get"; - String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); - Map requestHeaders = ImmutableMap.builder() - .putAll(commonHeaders) - .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()).build(); - final HttpResponse response = ((HttpResponse) syncRestClient.get(url, requestHeaders, - Collections.emptyMap(), t.getClass())); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); - int status = response.getStatus(); - restObject.setStatusCode(status); - - if (status == 200) { - t = response.getBody(); - restObject.set(t); - - } else { - throw new GenericUncheckedException(String.format("%s with status=%d, url=%s", methodName, status, url)); + public RestObjectWithRequestInfo Get(T t, String path, RestObject restObject) { + + String url = null; + String rawData = null; + Integer status = null; + + try { + String methodName = "Get"; + url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); + initRestClient(); + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + Map requestHeaders = ImmutableMap.builder() + .putAll(commonHeaders) + .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) + .build(); + final HttpResponse response = ((HttpResponse) syncRestClient.get(url, requestHeaders, + Collections.emptyMap(), t.getClass())); + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); + status = response.getStatus(); + restObject.setStatusCode(status); + + if (status == 200) { + t = response.getBody(); + restObject.set(t); + logger.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE); + logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + SUCCESSFUL_API_MESSAGE); + } else { + throw new GenericUncheckedException(new HttpException(String.format("%s with status=%d, url=%s", methodName, status, url))); + } + return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData); + } + catch (RuntimeException e) { + throw new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e); } } - public void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject restObject) { + public void Delete(T t, String sourceID, String path, RestObject restObject) { initRestClient(); String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java index d39e938b..ca5c0265 100644 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterfaceIfc.java @@ -1,6 +1,8 @@ package org.onap.vid.scheduler; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.RestObjectWithRequestInfo; import org.springframework.stereotype.Service; @Service @@ -8,10 +10,9 @@ public interface SchedulerRestInterfaceIfc { void initRestClient(); - void Get(T t, String sourceId, String path, org.onap.vid.scheduler.RestObject restObject); + RestObjectWithRequestInfo Get(T t, String path, RestObject restObject); - void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject restObject) - throws Exception; + void Delete(T t, String sourceID, String path, RestObject restObject); } diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerService.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerService.java new file mode 100644 index 00000000..b4246d5c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerService.java @@ -0,0 +1,7 @@ +package org.onap.vid.scheduler; + +import org.onap.vid.model.probes.ExternalComponentStatus; + +public interface SchedulerService { + ExternalComponentStatus probeGetSchedulerChangeManagements(); +} diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerServiceImpl.java new file mode 100644 index 00000000..99754fcd --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerServiceImpl.java @@ -0,0 +1,43 @@ +package org.onap.vid.scheduler; + +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.model.probes.ErrorMetadata; +import org.onap.vid.model.probes.ExternalComponentStatus; +import org.onap.vid.model.probes.HttpRequestMetadata; +import org.onap.vid.mso.RestObjectWithRequestInfo; +import org.onap.vid.services.ChangeManagementService; +import org.onap.vid.utils.Logging; +import org.springframework.beans.factory.annotation.Autowired; + +public class SchedulerServiceImpl implements SchedulerService{ + + private final ChangeManagementService changeManagementService; + + + @Autowired + public SchedulerServiceImpl(ChangeManagementService changeManagementService) { + this.changeManagementService = changeManagementService; + } + + @Override + public ExternalComponentStatus probeGetSchedulerChangeManagements() { + long startTime = System.currentTimeMillis(); + try { + RestObjectWithRequestInfo response = this.changeManagementService.getSchedulerChangeManagementsWithRequestInfo(); + return new ExternalComponentStatus( + ExternalComponentStatus.Component.SCHEDULER, + true, + new HttpRequestMetadata(response, "OK", startTime) + ); + } catch (ExceptionWithRequestInfo e) { + long duration = System.currentTimeMillis() - startTime; + return new ExternalComponentStatus(ExternalComponentStatus.Component.SCHEDULER, + false, + new HttpRequestMetadata(e, duration)); + } catch (Exception e) { + long duration = System.currentTimeMillis() - startTime; + return new ExternalComponentStatus(ExternalComponentStatus.Component.SCHEDULER, false, + new ErrorMetadata(Logging.exceptionToDescription(e), duration)); + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java b/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java new file mode 100644 index 00000000..432ab640 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/AAIServiceTree.java @@ -0,0 +1,247 @@ +package org.onap.vid.services; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.util.AAITreeConverter; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.parser.ServiceModelInflator; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.aaiTree.AAITreeNode; +import org.onap.vid.model.aaiTree.ServiceInstance; +import org.onap.vid.utils.Tree; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import javax.ws.rs.core.Response; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static java.lang.Thread.sleep; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.toSet; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.onap.vid.services.AAITreeNodeBuilder.*; + +@Component +public class AAIServiceTree { + + private final AAITreeNodeBuilder aaiTreeNodeBuilder; + + private final AAITreeConverter aaiTreeConverter; + + private final AaiClientInterface aaiClient; + + private final VidService sdcService; + + private final ServiceModelInflator serviceModelInflator; + + private final ObjectMapper mapper = new ObjectMapper(); + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AAIServiceTree.class); + + public static final Tree AAI_TREE_PATHS = + new Tree<>(new AaiRelationship(SERVICE_INSTANCE)); + + static { + AAI_TREE_PATHS.addPath(toAaiRelationshipList(GENERIC_VNF, VG)); + AAI_TREE_PATHS.addPath(toAaiRelationshipList(NETWORK)); + AAI_TREE_PATHS.addPath(toAaiRelationshipList(GENERIC_VNF, NETWORK)); + AAI_TREE_PATHS.addPath(toAaiRelationshipList(INSTANCE_GROUP)); + } + + @Inject + public AAIServiceTree(AaiClientInterface aaiClient, AAITreeNodeBuilder aaiTreeNodeBuilder, + AAITreeConverter aaiTreeConverter, VidService sdcService, + ServiceModelInflator serviceModelInflator) { + this.aaiClient = aaiClient; + this.aaiTreeNodeBuilder = aaiTreeNodeBuilder; + this.aaiTreeConverter = aaiTreeConverter; + this.sdcService = sdcService; + this.serviceModelInflator = serviceModelInflator; + } + + public List buildAAITree(String getUrl, Tree pathsToSearch) { + + ConcurrentSkipListSet nodesAccumulator = createNodesAccumulator(); + + List aaiTreeNodes = fetchAAITree(getUrl, pathsToSearch, nodesAccumulator, true); + + enrichNodesWithModelVersionAndModelName(nodesAccumulator); + + return aaiTreeNodes; + } + + public ServiceInstance getServiceInstanceTopology(String globalCustomerId, String serviceType, String serviceInstanceId) { + + String getURL = "business/customers/customer/" + + globalCustomerId + "/service-subscriptions/service-subscription/" + + serviceType + "/service-instances/service-instance/" + serviceInstanceId; + + //Used later to get the nodes UUID + ConcurrentSkipListSet nodesAccumulator = createNodesAccumulator(); + + AAITreeNode aaiTree = fetchAAITree(getURL, AAI_TREE_PATHS, nodesAccumulator, false).get(0); + + //Populate nodes with model-name & model-version (from aai) + enrichNodesWithModelVersionAndModelName(nodesAccumulator); + + final ServiceModel serviceModel = getServiceModel(aaiTree.getModelVersionId()); + + //Populate nodes with model-customization-name (from sdc model) + enrichNodesWithModelCustomizationName(nodesAccumulator, serviceModel); + + return aaiTreeConverter.convertTreeToUIModel(aaiTree, globalCustomerId, serviceType, getInstantiationType(serviceModel)); + } + + private List fetchAAITree(String getUrl, Tree pathsToSearch, + ConcurrentSkipListSet nodesAccumulator, boolean partialTreeOnTimeout) { + ThreadPoolExecutor threadPool = getThreadPool(); + + List aaiTree = aaiTreeNodeBuilder.buildNode(SERVICE_INSTANCE, + getUrl, defaultIfNull(nodesAccumulator, createNodesAccumulator()), + threadPool, new ConcurrentLinkedQueue<>(), + new AtomicInteger(0), pathsToSearch); + + boolean timeoutOccurred = waitForTreeFetch(threadPool); + + if (timeoutOccurred) { + if (!partialTreeOnTimeout) { + throw new GenericUncheckedException("Timeout on fetchAAITree. Fetched " + nodesAccumulator.size() + " nodes for url: " + getUrl); + } + LOGGER.warn(EELFLoggerDelegate.errorLogger, "Timeout on fetchAAITree for url: " + getUrl); + } + + return aaiTree; + } + + private ConcurrentSkipListSet createNodesAccumulator() { + return new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + } + + private String getInstantiationType(ServiceModel serviceModel) { + if (serviceModel.getService() != null && serviceModel.getService().getInstantiationType() != null) { + return serviceModel.getService().getInstantiationType(); + } else { + return null; + } + } + + private ServiceModel getServiceModel(String modelVersionId) { + try { + final ServiceModel serviceModel = sdcService.getService(modelVersionId); + if (serviceModel == null) { + throw new GenericUncheckedException("Model version '" + modelVersionId + "' not found"); + } + return serviceModel; + } catch (AsdcCatalogException e) { + throw new GenericUncheckedException("Exception while loading model version '" + modelVersionId + "'", e); + } + + } + + void enrichNodesWithModelCustomizationName(Collection nodes, ServiceModel serviceModel) { + final Map customizationNameByVersionId = serviceModelInflator.toNamesByVersionId(serviceModel); + + nodes.forEach(node -> { + final ServiceModelInflator.Names names = customizationNameByVersionId.get(node.getModelVersionId()); + if (names != null) { + node.setKeyInModel(names.getModelKey()); + node.setModelCustomizationName(names.getModelCustomizationName()); + } + }); + } + + + private void enrichNodesWithModelVersionAndModelName(Collection nodes) { + + Collection invariantIDs = getModelInvariantIds(nodes); + + Map modelVersionByModelVersionId = new HashMap<>(); + Map modelNameByModelVersionId = new HashMap<>(); + + JsonNode models = getModels(aaiClient, invariantIDs); + for (JsonNode model: models) { + JsonNode modelVersions = model.get("model-vers").get("model-ver"); + for (JsonNode modelVersion: modelVersions) { + final String modelVersionId = modelVersion.get("model-version-id").asText(); + modelVersionByModelVersionId.put(modelVersionId, modelVersion.get("model-version").asText()); + modelNameByModelVersionId.put(modelVersionId, modelVersion.get("model-name").asText()); + } + } + + nodes.forEach(node -> { + node.setModelVersion(modelVersionByModelVersionId.get(node.getModelVersionId())); + node.setModelName(modelNameByModelVersionId.get(node.getModelVersionId())); + }); + + } + + private JsonNode getModels(AaiClientInterface aaiClient, Collection invariantIDs) { + Response response = aaiClient.getVersionByInvariantId(ImmutableList.copyOf(invariantIDs)); + try { + JsonNode responseJson = mapper.readTree(response.readEntity(String.class)); + return responseJson.get("model"); + } catch (Exception e) { + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to getVersionByInvariantId from A&AI", e); + } + return mapper.createObjectNode(); + } + + private Set getModelInvariantIds(Collection nodes) { + return nodes.stream() + .map(AAITreeNode::getModelInvariantId) + .filter(Objects::nonNull) + .collect(toSet()); + } + + private boolean waitForTreeFetch(ThreadPoolExecutor threadPool) { + int timer = 60; + try { + //Stop fetching information if it takes more than 1 minute + while (threadPool.getActiveCount() != 0 && + timer > 0) { + sleep(1000); + timer--; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new GenericUncheckedException(e); + } + threadPool.shutdown(); + return (timer == 0); + } + + private ThreadPoolExecutor getThreadPool() { + //Use at least one thread, and never more than 75% of the available thread. + int cores = Math.max((int)(Runtime.getRuntime().availableProcessors() * 0.75), 1); + BlockingQueue queue = new LinkedBlockingQueue<>(); + return new ThreadPoolExecutor(1, cores, 10, TimeUnit.SECONDS, queue); + } + + public static class AaiRelationship { + + public final String type; + + public AaiRelationship(String type) { + this.type = type; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof AaiRelationship)) return false; + AaiRelationship that = (AaiRelationship) o; + return Objects.equals(type, that.type); + } + + @Override + public int hashCode() { + return Objects.hash(type); + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java b/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java new file mode 100644 index 00000000..41f0144c --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/AAITreeNodeBuilder.java @@ -0,0 +1,281 @@ +package org.onap.vid.services; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList; +import org.onap.vid.model.aaiTree.AAITreeNode; +import org.onap.vid.model.aaiTree.FailureAAITreeNode; +import org.onap.vid.utils.Streams; +import org.onap.vid.utils.Tree; +import org.onap.vid.utils.Unchecked; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.*; +import static org.onap.vid.utils.Streams.not; + + +@Component +public class AAITreeNodeBuilder { + + private AaiClientInterface aaiClient; + + private final ObjectMapper mapper = new ObjectMapper(); + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AAITreeNodeBuilder.class); + + //List of all the node types the tree should include + public static final String SERVICE_INSTANCE = "service-instance"; + public static final String GENERIC_VNF = "generic-vnf"; + public static final String NETWORK = "l3-network"; + public static final String FAILURE = "failure_node"; + public static final String COLLECTION_RESOURCE = "collection"; + public static final String CONFIGURATION = "configuration"; + public static final String PNF = "pnf"; + public static final String VF_MODULE = "vf-module"; + public static final String INSTANCE_GROUP = "instance-group"; + public static final String PORT = "l-interface"; + public static final String VG = "volume-group"; + public static final String VLAN_TAG = "vlan-tag"; + + //Hashmap that defines the node-type and the tag that should be used to find it's ID key in the JSON. + private static HashMap nodeTypeToIdKeyMap = generateTypeToIdKeyMap(); + + //Hashmap that defines the node-type and the tag that should be used to find it's NAMR key in the JSON. + private static HashMap nodeTypeToNameKeyMap = generateTypeToNameKeyMap(); + + public enum AAIBaseProperties { + ORCHESTRATION_STATUS("orchestration-status"), + PROV_STATUS("prov-status"), + IN_MAINT("in-maint"), + MODEL_VERSION_ID("model-version-id"), + MODEL_CUSTOMIZATION_ID("model-customization-id"), + MODEL_INVARIANT_ID("model-invariant-id"), + RELATIONSHIP_LIST("relationship-list"); + + private final String aaiKey; + + AAIBaseProperties(String aaiKey) { + this.aaiKey = aaiKey; + } + + public String getAaiKey() { + return aaiKey; + } + } + + public static List toAaiRelationshipList(String... types) { + return Stream.of(types).map(AAIServiceTree.AaiRelationship::new).collect(Collectors.toList()); + } + + @Inject + public AAITreeNodeBuilder(AaiClientInterface aaiClient) { + this.aaiClient = aaiClient; + } + + public List buildNode(String nodeType, + String requestURL, + ConcurrentSkipListSet nodesAccumulator, ExecutorService threadPool, + ConcurrentLinkedQueue visitedNodes, + AtomicInteger nodesCounter, + Tree pathsTree) { + + JsonNode topLevelJson = aaiClient.typedAaiGet(Unchecked.toURI(requestURL), JsonNode.class); + + if (topLevelJson.has(nodeType) && topLevelJson.get(nodeType).isArray()) { + return Streams.fromIterable(topLevelJson.get(nodeType)) + .map(item -> parseNodeAndGetChildren(nodeType, requestURL, item, + nodesAccumulator, threadPool, visitedNodes, nodesCounter, pathsTree)) + .collect(toList()); + } else { + return ImmutableList.of(parseNodeAndGetChildren(nodeType, requestURL, topLevelJson, + nodesAccumulator, threadPool, visitedNodes, nodesCounter, pathsTree)); + } + } + + private AAITreeNode parseNodeAndGetChildren(String nodeType, + String requestURL, + JsonNode topLevelJson, + ConcurrentSkipListSet nodesAccumulator, ExecutorService threadPool, + ConcurrentLinkedQueue visitedNodes, + AtomicInteger nodesCounter, + Tree pathsTree) { + AAITreeNode node = jsonToAaiNode(nodeType, topLevelJson, nodesAccumulator, nodesCounter); + + RelationshipList relationships = mapper.convertValue(topLevelJson.get(AAIBaseProperties.RELATIONSHIP_LIST.getAaiKey()), RelationshipList.class); + if (relationships != null) { + getChildren(threadPool, nodesAccumulator, relationships.getRelationship(), visitedNodes, node, nodesCounter, pathsTree); + } + if (StringUtils.equals(node.getType(), GENERIC_VNF)) { + getRelatedVfModules(threadPool, nodesAccumulator, requestURL, node, nodesCounter); + } + return node; + } + + private AAITreeNode jsonToAaiNode(String nodeType, JsonNode topLevelJson, ConcurrentSkipListSet nodesAccumulator, AtomicInteger nodesCounter) { + AAITreeNode node = fillNodeMetaData(nodeType, topLevelJson, nodesCounter); + + nodesAccumulator.add(node); + + return node; + } + + private void getRelatedVfModules(ExecutorService threadPool, ConcurrentSkipListSet nodesAccumulator, String parentURL, AAITreeNode parentNode, AtomicInteger nodesCounter) { + /* + VNFs do not report their direct related-to vf-modules, so try + directly fetching a resource URI. + */ + + threadPool.execute(() -> { + // the response is an array of vf-modules + final JsonNode topLevelJson; + try { + topLevelJson = aaiClient.typedAaiGet(Unchecked.toURI(parentURL + "/vf-modules"), JsonNode.class); + } catch (ExceptionWithRequestInfo e) { + if (e.getHttpCode().equals(404)) { + // it's ok, as we're just optimistically fetching + // the /vf-modules uri; 404 says this time it was + // a bad guess + return; + } else { + throw e; + } + } + + if (topLevelJson != null) { + parentNode.getChildren().addAll( + Streams.fromIterable(topLevelJson.get(VF_MODULE)) + .map(vfModuleNode -> jsonToAaiNode(VF_MODULE, vfModuleNode, nodesAccumulator, nodesCounter)) + .collect(toList()) + ); + } else { + LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to get vf-modules for vnf " + parentNode.getId()); + } + }); + } + + private void getChildren(ExecutorService threadPool, ConcurrentSkipListSet nodesAccumulator, + List relationships, ConcurrentLinkedQueue visitedNodes, AAITreeNode parent, AtomicInteger nodesCounter, Tree pathsTree) { + for (Relationship relationship : relationships) { + createChildNode(threadPool, nodesAccumulator, relationship, visitedNodes, parent, nodesCounter, pathsTree); + } + } + + private void createChildNode(ExecutorService threadPool, ConcurrentSkipListSet nodesAccumulator, + Relationship relationship, ConcurrentLinkedQueue visitedNodes, AAITreeNode parent, AtomicInteger nodesCounter, Tree pathsTree) { + String newNodeType = relationship.getRelatedTo(); + Tree subTree = pathsTree.getSubTree(new AAIServiceTree.AaiRelationship(newNodeType)); + if (subTree!=null) { + String newNodeUrl = relationship.getRelatedLink(); + if (!visitedNodes.contains(newNodeUrl)) { + visitedNodes.add(newNodeUrl); + threadPool.execute(() -> { + try { + parent.addChildren(buildNode(newNodeType, newNodeUrl, nodesAccumulator, threadPool, visitedNodes, nodesCounter, subTree)); + } catch (Exception e) { + parent.getChildren().add(createFailureNode(e)); + } + } + ); + } + } + } + + private AAITreeNode fillNodeMetaData(String nodeType, JsonNode model, @NotNull AtomicInteger nodesCounter) { + AAITreeNode node = new AAITreeNode(); + node.setType(nodeType); + node.setUniqueNumber(nodesCounter.getAndIncrement()); + node.setOrchestrationStatus(getStringDataFromJsonIfExists(model, AAIBaseProperties.ORCHESTRATION_STATUS.getAaiKey())); + node.setProvStatus(getStringDataFromJsonIfExists(model, AAIBaseProperties.PROV_STATUS.getAaiKey())); + node.setInMaint(getBooleanDataFromJsonIfExists(model, AAIBaseProperties.IN_MAINT.getAaiKey())); + node.setModelVersionId(getStringDataFromJsonIfExists(model, AAIBaseProperties.MODEL_VERSION_ID.getAaiKey())); + node.setModelCustomizationId(getStringDataFromJsonIfExists(model, AAIBaseProperties.MODEL_CUSTOMIZATION_ID.getAaiKey())); + node.setModelInvariantId(getStringDataFromJsonIfExists(model, AAIBaseProperties.MODEL_INVARIANT_ID.getAaiKey())); + node.setId(getStringDataFromJsonIfExists(model, nodeTypeToIdKeyMap.get(nodeType))); + node.setName(getStringDataFromJsonIfExists(model, nodeTypeToNameKeyMap.get(nodeType))); + node.setAdditionalProperties(aggregateAllOtherProperties(model, nodeType)); + + return node; + } + + private AAITreeNode createFailureNode(Exception exception) { + return FailureAAITreeNode.of(exception); + } + + private String getStringDataFromJsonIfExists(JsonNode model, String key) { + if (model.has(key)) { + return model.get(key).asText(); + } + return null; + } + + private Boolean getBooleanDataFromJsonIfExists(JsonNode model, String key) { + if (model.has(key)) { + return model.get(key).asBoolean(); + } + return false; + } + + private Map aggregateAllOtherProperties(JsonNode model, String nodeType) { + Set ignoreProperties = Stream.of(AAIBaseProperties.values()) + .map(AAIBaseProperties::getAaiKey).collect(toSet()); + + return Streams.fromIterator(model.fields()) + .filter(not(field -> StringUtils.equals(field.getKey(), nodeTypeToIdKeyMap.get(nodeType)))) + .filter(not(field -> StringUtils.equals(field.getKey(), nodeTypeToNameKeyMap.get(nodeType)))) + .filter(not(field -> ignoreProperties.contains(field.getKey()))) + .collect(toMap(Map.Entry::getKey, v -> v.getValue().asText())); + } + + private static HashMap generateTypeToIdKeyMap() { + HashMap result = new HashMap<>(); + result.put(SERVICE_INSTANCE, "service-instance-id"); + result.put(GENERIC_VNF, "vnf-id"); + result.put(NETWORK, "network-id"); + result.put(COLLECTION_RESOURCE, "collection-id"); + result.put(CONFIGURATION, "configuration-id"); + result.put(PNF, "pnf-id"); + result.put(VF_MODULE, "vf-module-id"); + result.put(INSTANCE_GROUP, "id"); + result.put(PORT, "l-interface-id"); + result.put(VG, "volume-group-id"); + result.put(VLAN_TAG, "vlan-id"); + + return result; + } + + private static HashMap generateTypeToNameKeyMap() { + HashMap result = new HashMap<>(); + result.put(SERVICE_INSTANCE, "service-instance-name"); + result.put(GENERIC_VNF, "vnf-name"); + result.put(NETWORK, "network-name"); + result.put(COLLECTION_RESOURCE, "collection-name"); + result.put(CONFIGURATION, "configuration-name"); + result.put(PNF, "pnf-name"); + result.put(VF_MODULE, "vf-module-name"); + result.put(INSTANCE_GROUP, "instance-group-name"); + result.put(PORT, "l-interface-name"); + result.put(VG, "volume-group-name"); + result.put(VLAN_TAG, "vlan-name"); + + return result; + } +} \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java index d2ee32cb..bd751c5c 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java @@ -22,6 +22,7 @@ package org.onap.vid.services; import io.joshworks.restclient.http.HttpResponse; +import org.onap.vid.aai.AaiGetVnfResponse; import org.onap.vid.aai.AaiResponse; import org.onap.vid.aai.AaiResponseTranslator; import org.onap.vid.aai.SubscriberFilteredResults; @@ -32,6 +33,7 @@ import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; import org.onap.vid.aai.model.PortDetailsTranslator; import org.onap.vid.asdc.beans.Service; import org.onap.vid.model.SubscriberList; +import org.onap.vid.model.aaiTree.RelatedVnf; import org.onap.vid.roles.RoleValidator; import javax.ws.rs.core.Response; @@ -64,7 +66,7 @@ public interface AaiService { AaiResponse getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId); - Response getVNFData(String globalSubscriberId, String serviceType); + AaiResponse getVNFData(String globalSubscriberId, String serviceType); AaiResponse getTenants(String globalCustomerId, String serviceType, RoleValidator roleValidator); @@ -87,4 +89,10 @@ public interface AaiService { List getPortMirroringSourcePorts(String configurationId); AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId); + + String getAAIServiceTree(String globalCustomerId, String serviceType, String serviceInstanceId); + + GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId); + + List searchGroupMembers(String globalCustomerId, String serviceType, String invariantId, String groupType, String groupRole); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java index acdf0afb..fe4a6618 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java @@ -21,38 +21,35 @@ package org.onap.vid.services; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.joshworks.restclient.http.HttpResponse; import org.apache.http.HttpStatus; -import org.codehaus.jackson.JsonNode; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.vid.aai.*; -import org.onap.vid.aai.ServiceInstance; -import org.onap.vid.aai.ServiceSubscription; -import org.onap.vid.aai.Services; -import org.onap.vid.aai.model.AaiGetAicZone.AicZones; -import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetails; +import org.onap.vid.aai.model.*; import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetRelatedInstanceGroupsByVnfId; import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; import org.onap.vid.aai.model.AaiGetPnfs.Pnf; import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone; +import org.onap.vid.aai.model.Properties; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; -import org.onap.vid.aai.model.*; import org.onap.vid.asdc.beans.Service; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.ServiceInstanceSearchResult; import org.onap.vid.model.SubscriberList; +import org.onap.vid.model.aaiTree.AAITreeNode; +import org.onap.vid.model.aaiTree.RelatedVnf; import org.onap.vid.roles.RoleValidator; import org.onap.vid.utils.Intersection; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.utils.Tree; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; import java.util.stream.Collectors; -import org.springframework.beans.factory.annotation.Qualifier; /** * Created by Oren on 7/4/17. @@ -62,18 +59,25 @@ public class AaiServiceImpl implements AaiService { private static final String SERVICE_TYPE = "service-subscription.service-type"; private static final String CUSTOMER_ID = "customer.global-customer-id"; private static final String SERVICE_INSTANCE_NAME = "service-instance.service-instance-name"; + private static final String TENANT_NODE_TYPE = "tenant"; + private static final String CLOUD_REGION_NODE_TYPE = "cloud-region"; private int indexOfSubscriberName = 6; @Autowired private AaiClientInterface aaiClient; @Autowired - @Qualifier("aaiClientForCodehausMapping") private AaiOverTLSClientInterface aaiOverTLSClient; @Autowired private AaiResponseTranslator aaiResponseTranslator; + @Autowired + private AAITreeNodeBuilder aaiTreeNode; + + @Autowired + private AAIServiceTree aaiServiceTree; + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiServiceImpl.class); private List convertModelToService(Model model) { @@ -277,9 +281,7 @@ public class AaiServiceImpl implements AaiService { new ServiceInstanceSearchResult(serviceInstance.serviceInstanceId, subscriberId, serviceType, serviceInstance.serviceInstanceName, subscriberName, serviceInstance.modelInvariantId, serviceInstance.modelVersionId, serviceSubscription.isPermitted); - if (instanceIdentifier == null) { - results.add(serviceInstanceSearchResult); - } else if (serviceInstanceMatchesIdentifier(instanceIdentifier, serviceInstance)) { + if ((instanceIdentifier == null) || (serviceInstanceMatchesIdentifier(instanceIdentifier, serviceInstance))){ results.add(serviceInstanceSearchResult); } } @@ -345,13 +347,31 @@ public class AaiServiceImpl implements AaiService { } @Override - public Response getVNFData(String globalSubscriberId, String serviceType) { - return aaiClient.getVNFData(globalSubscriberId, serviceType); + public AaiResponse getVNFData(String globalSubscriberId, String serviceType) { + AaiResponse response = aaiClient.getVNFData(globalSubscriberId, serviceType); + return filterChangeManagementVNFCandidatesResponse(response); + } + + private AaiResponse filterChangeManagementVNFCandidatesResponse(AaiResponse response) { + + + if (response != null && response.getT() != null) { + response.getT().results = + response.getT().results.stream() + .filter(result -> ( + result.nodeType.equalsIgnoreCase("generic-vnf") || + result.nodeType.equalsIgnoreCase("service-instance"))) + .collect(Collectors.toList()); + + return response; + } + + return new AaiResponse(); } @Override public AaiResponse getAaiZones() { - return (AaiResponse) aaiClient.getAllAicZones(); + return aaiClient.getAllAicZones(); } @Override @@ -386,14 +406,12 @@ public class AaiServiceImpl implements AaiService { @Override public AaiResponse getNetworkCollectionDetails(String serviceInstanceId){ - AaiResponse getNetworkCollectionDetailsAaiResponse = aaiClient.getNetworkCollectionDetails(serviceInstanceId); - return getNetworkCollectionDetailsAaiResponse; + return aaiClient.getNetworkCollectionDetails(serviceInstanceId); } @Override public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction){ - AaiResponse getInstanceGroupsByCloudRegionResponse = aaiClient.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction); - return getInstanceGroupsByCloudRegionResponse; + return aaiClient.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction); } @Override @@ -452,6 +470,66 @@ public class AaiServiceImpl implements AaiService { return aaiClient.getInstanceGroupsByVnfInstanceId(vnfInstanceId); } + @Override + public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) { + return aaiClient.getHomingDataByVfModule(vnfInstanceId,vfModuleId); + } + + @Override + public List searchGroupMembers(String globalCustomerId, String serviceType, String invariantId, String groupType, String groupRole) { + String getURL = "business/customers/customer/" + + globalCustomerId + "/service-subscriptions/service-subscription/" + + serviceType + "/service-instances?model-invariant-id=" + invariantId; + + Tree pathsToSearch = new Tree<>(new AAIServiceTree.AaiRelationship(AAITreeNodeBuilder.SERVICE_INSTANCE)); + pathsToSearch.addPath(AAITreeNodeBuilder.toAaiRelationshipList(AAITreeNodeBuilder.GENERIC_VNF, AAITreeNodeBuilder.INSTANCE_GROUP)); + + //get all vnfs related to service-instances from the model-invariant-id + List aaiTree = aaiServiceTree.buildAAITree(getURL, pathsToSearch); + + //filter by instance-group-role & instance-group-type properties (from getAdditionalProperties) + //only vnfs has related instance-group with the same groupType & groupRole - are filtered out. + List filteredVnfs = filterByInstanceGroupRoleAndType(aaiTree, groupRole, groupType); + + //convert vnfs to expected result + return filteredVnfs.stream() + .map(RelatedVnf::from) + .map(this::enrichRelatedVnfWithCloudRegionAndTenant) + .collect(Collectors.toList()); + } + + private List filterByInstanceGroupRoleAndType(List aaiTree, String groupRole, String groupType) { + + return aaiTree.stream() + .map(AAITreeNode::getChildren) + .flatMap(Collection::stream) + .filter(vnf -> isInstanceGroupsNotMatchRoleAndType(vnf.getChildren(), groupRole, groupType)) + .collect(Collectors.toList()); + } + + public boolean isInstanceGroupsNotMatchRoleAndType(List instanceGroups, String groupRole, String groupType) { + return instanceGroups.stream() + .map(AAITreeNode::getAdditionalProperties) + .allMatch(props -> + (!(groupRole.equals(props.get("instance-group-role")) && + groupType.equals(props.get("instance-group-type")))) + ); + } + + public RelatedVnf enrichRelatedVnfWithCloudRegionAndTenant(RelatedVnf vnf) { + Map cloudRegionAndTenant = aaiClient.getCloudRegionAndTenantByVnfId(vnf.getInstanceId()); + + if (cloudRegionAndTenant.containsKey(TENANT_NODE_TYPE)) { + vnf.setTenantId(cloudRegionAndTenant.get(TENANT_NODE_TYPE).getTenantId()); + vnf.setTenantName(cloudRegionAndTenant.get(TENANT_NODE_TYPE).getTenantName()); + } + + if (cloudRegionAndTenant.containsKey(CLOUD_REGION_NODE_TYPE)) { + vnf.setLcpCloudRegionId(cloudRegionAndTenant.get(CLOUD_REGION_NODE_TYPE).getCloudRegionId()); + } + + return vnf; + } private List convertGetInstanceGroupsResponseToSimpleResponse(AaiGetRelatedInstanceGroupsByVnfId response) { List instanceGroupInfoList = new ArrayList<>(); for(org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship: response.getRelationshipList().getRelationship()){ @@ -524,4 +602,16 @@ public class AaiServiceImpl implements AaiService { return relationshipValues; } + + public String getAAIServiceTree(String globalCustomerId, String serviceType, String serviceInstanceId) { + ObjectMapper om = new ObjectMapper(); + String result; + try { + org.onap.vid.model.aaiTree.ServiceInstance tree = aaiServiceTree.getServiceInstanceTopology(globalCustomerId, serviceType, serviceInstanceId); + result = om.writeValueAsString(tree); + } catch (Exception e) { + throw new GenericUncheckedException(e); + } + return result; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java index 90eb0d2b..07bf4615 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogic.java @@ -5,12 +5,13 @@ import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.job.Job; import org.onap.vid.model.JobAuditStatus; import org.onap.vid.model.ServiceInfo; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.model.serviceInstantiation.*; +import org.onap.vid.mso.model.*; import org.onap.vid.mso.rest.AsyncRequestStatus; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.function.Consumer; @@ -22,10 +23,40 @@ public interface AsyncInstantiationBusinessLogic { List pushBulkJob(ServiceInstantiation request, String userId); - RequestDetailsWrapper generateServiceInstantiationRequest(UUID uuid, ServiceInstantiation details, String userId); + RequestDetailsWrapper generateMacroServiceInstantiationRequest(UUID uuid, ServiceInstantiation details, String optimisticUniqueServiceInstanceName, String userId); + + RequestDetailsWrapper generateALaCarteServiceInstantiationRequest(UUID uuid, ServiceInstantiation details, String optimisticUniqueServiceInstanceName, String userId); + + RequestDetailsWrapper generateALaCarteServiceDeletionRequest(UUID uuid, ServiceInstantiation details, String userId); + + RequestDetailsWrapper generateVnfInstantiationRequest(Vnf vnfDetails, ModelInfo serviceModelInfo, String serviceInstanceId, String userId); + + RequestDetailsWrapper generateVfModuleInstantiationRequest(VfModule vfModuleDetails, ModelInfo serviceModelInfo, String serviceInstanceId, ModelInfo vnfModelInfo, String vnfInstanceId, String vgInstanceId, String userId); + + RequestDetailsWrapper generateVolumeGroupInstantiationRequest(VfModule vfModuleDetails, ModelInfo serviceModelInfo, String serviceInstanceId, ModelInfo vnfModelInfo, String vnfInstanceId, String userId); + + RequestDetailsWrapper generateNetworkInstantiationRequest(Network networkDetails, ModelInfo serviceModelInfo, String serviceInstanceId, String userId); + + RequestDetailsWrapper generateInstanceGroupInstantiationRequest(InstanceGroup request, ModelInfo serviceModelInfo, String serviceInstanceId, String userId); + + List> buildVnfInstanceParams(List> currentVnfInstanceParams, List vfModules); String getServiceInstantiationPath(ServiceInstantiation serviceInstantiationRequest); + String getServiceDeletionPath(String serviceInstanceId); + + String getVnfInstantiationPath(String serviceInstanceId); + + String getNetworkInstantiationPath(String serviceInstanceId); + + String getVfmoduleInstantiationPath(String serviceInstanceId, String vnfInstanceId); + + String getVolumeGroupInstantiationPath(String serviceInstanceId, String vnfInstanceId); + + String getInstanceGroupInstantiationPath(); + + String getInstanceGroupDeletePath(String instanceGroupId); + String getOrchestrationRequestsPath(); ServiceInfo getServiceInfoByJobId(UUID jobUUID); @@ -57,4 +88,6 @@ public interface AsyncInstantiationBusinessLogic { void setMaxRetriesGettingFreeNameFromAai(int maxRetriesGettingFreeNameFromAai); String getUniqueName(String name, ResourceType resourceType); + + } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java index df8e92d6..c4264c6b 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java @@ -1,42 +1,17 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.services; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import io.joshworks.restclient.http.HttpResponse; -import java.io.IOException; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.service.DataAccessService; import org.onap.vid.aai.AaiClientInterface; -import org.onap.vid.aai.AaiOverTLSClientInterface; -import org.onap.vid.aai.AaiResponse; -import org.onap.vid.aai.exceptions.InvalidAAIResponseException; -import org.onap.vid.aai.model.AaiNodeQueryResponse; +import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.domain.mso.CloudConfiguration; -import org.onap.vid.domain.mso.SubscriberInfo; import org.onap.vid.exceptions.DbFailureUncheckedException; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.exceptions.MaxRetriesException; @@ -46,22 +21,25 @@ import org.onap.vid.job.Job.JobStatus; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobType; import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.model.Action; import org.onap.vid.model.JobAuditStatus; import org.onap.vid.model.NameCounter; import org.onap.vid.model.ServiceInfo; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.model.serviceInstantiation.VfModule; -import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.model.serviceInstantiation.*; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoProperties; -import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.mso.model.*; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails.RequestParameters; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails.*; +import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails.RequestParametersVfModule; +import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails.UserParamMap; import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.mso.rest.SubscriberInfo; +import org.onap.vid.properties.Features; import org.onap.vid.utils.DaoUtils; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.service.DataAccessService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; +import org.togglz.core.manager.FeatureManager; import java.sql.Timestamp; import java.time.LocalDateTime; @@ -69,14 +47,19 @@ import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; +import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; import static org.onap.vid.utils.Logging.debugRequestDetails; @Service -public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBusinessLogic { +public class AsyncInstantiationBusinessLogicImpl implements + AsyncInstantiationBusinessLogic { private static final int MAX_RETRIES_GETTING_COUNTER = 100; private static final int MAX_RETRIES_GETTING_FREE_NAME_FROM_AAI = 10000; - private static final String NAME_FOR_CHECK_AAI_STATUS = "NAME_FOR_CHECK_AAI_STATUS"; + public static final String NAME_FOR_CHECK_AAI_STATUS = "NAME_FOR_CHECK_AAI_STATUS"; + private static final String VID_SOURCE = "VID"; private final DataAccessService dataAccessService; @@ -84,64 +67,86 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu private final JobsBrokerService jobService; + private final CloudOwnerService cloudOwnerService; + private SessionFactory sessionFactory; - private AaiOverTLSClientInterface aaiOverTLSClient; + private AaiClientInterface aaiClient; + + private FeatureManager featureManager; private int maxRetriesGettingFreeNameFromAai = MAX_RETRIES_GETTING_FREE_NAME_FROM_AAI; - private static final EELFLoggerDelegate logger = EELFLoggerDelegate - .getLogger(AsyncInstantiationBusinessLogicImpl.class); + private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AsyncInstantiationBusinessLogicImpl.class); private Map msoStateToJobStatusMap = ImmutableMap.builder() - .put("inprogress", JobStatus.IN_PROGRESS) - .put("failed", JobStatus.FAILED) - .put("pause", JobStatus.PAUSE) - .put("paused", JobStatus.PAUSE) - .put("complete", JobStatus.COMPLETED) - .put("pending", JobStatus.IN_PROGRESS) - .put("pendingmanualtask", JobStatus.PAUSE) - .put("unlocked", JobStatus.IN_PROGRESS) - .build(); + .put("inprogress", JobStatus.IN_PROGRESS) + .put("failed", JobStatus.FAILED) + .put("pause", JobStatus.PAUSE) + .put("paused", JobStatus.PAUSE) + .put("complete", JobStatus.COMPLETED) + .put("pending", JobStatus.IN_PROGRESS) + .put("pendingmanualtask", JobStatus.PAUSE) + .put("unlocked", JobStatus.IN_PROGRESS) + .build(); @Autowired public AsyncInstantiationBusinessLogicImpl(DataAccessService dataAccessService, - JobAdapter jobAdapter, - JobsBrokerService jobService, - SessionFactory sessionFactory, - @Qualifier("aaiClientForFasterXmlMapping") AaiOverTLSClientInterface aaiOverTLSClient) { + JobAdapter jobAdapter, + JobsBrokerService jobService, + SessionFactory sessionFactory, + AaiClientInterface aaiClient, + FeatureManager featureManager, + CloudOwnerService cloudOwnerService) { this.dataAccessService = dataAccessService; this.jobAdapter = jobAdapter; this.jobService = jobService; this.sessionFactory = sessionFactory; - this.aaiOverTLSClient = aaiOverTLSClient; + this.aaiClient = aaiClient; + this.featureManager = featureManager; + this.cloudOwnerService = cloudOwnerService; } @Override public List getAllServicesInfo() { - return dataAccessService - .getList(ServiceInfo.class, filterByCreationDateAndNotDeleted(), orderByCreatedDateAndStatus(), null); + return dataAccessService.getList(ServiceInfo.class, filterByCreationDateAndNotDeleted(), orderByCreatedDateAndStatus(), null); } private String filterByCreationDateAndNotDeleted() { LocalDateTime minus3Months = LocalDateTime.now().minusMonths(3); Timestamp filterDate = Timestamp.valueOf(minus3Months); return " where" + - " hidden = false" + - " and deleted_at is null" + // don't fetch deleted - " and created >= '" + filterDate + "' "; + " hidden = false" + + " and deleted_at is null" + // don't fetch deleted + " and created >= '" + filterDate + "' "; } private String orderByCreatedDateAndStatus() { return " createdBulkDate DESC ,\n" + - " (CASE jobStatus\n" + - " WHEN 'COMPLETED' THEN 0\n" + - " WHEN 'FAILED' THEN 0\n" + - " WHEN 'IN_PROGRESS' THEN 1\n" + - " WHEN 'PAUSE' THEN 2\n" + - " WHEN 'PENDING' THEN 3\n" + - " WHEN 'STOPPED' THEN 3 END),\n" + - " statusModifiedDate "; + " (CASE jobStatus\n" + + " WHEN 'COMPLETED' THEN 0\n" + + " WHEN 'FAILED' THEN 0\n" + + " WHEN 'COMPLETED_WITH_ERRORS' THEN 0\n" + + " WHEN 'IN_PROGRESS' THEN 1\n" + + " WHEN 'PAUSE' THEN 2\n" + + " WHEN 'PENDING' THEN 3\n" + + " WHEN 'STOPPED' THEN 3 END),\n" + + " statusModifiedDate "; + } + + JobType getJobType(ServiceInstantiation request) { + if (request.isALaCarte()) { + switch (defaultIfNull(request.getAction(), Action.Create)) { + case Delete: + return JobType.ALaCarteService; + case None: + return JobType.ALaCarteService; + default: + return JobType.ALaCarteServiceInstantiation; + } + } else { + return JobType.MacroServiceInstantiation; + } } @Override @@ -151,173 +156,460 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu int bulkSize = request.getBulkSize(); UUID templateId = UUID.randomUUID(); for (int i = 0; i < bulkSize; i++) { - Job job = jobAdapter.createJob(JobType.ServiceInstantiation, request, templateId, userId, i); + ServiceInfo.ServiceAction serviceAction = getAction(request); + JobType jobType = getJobType(request); + final String optimisticUniqueServiceInstanceName = getOptimisticUniqueServiceInstanceName(request); + Job job = jobAdapter.createServiceInstantiationJob(jobType, request, templateId, userId, optimisticUniqueServiceInstanceName, i); UUID jobId = jobService.add(job); + dataAccessService.saveDomainObject(createServiceInfo(userId, request, jobId, templateId, createdBulkDate, optimisticUniqueServiceInstanceName, serviceAction), DaoUtils.getPropsMap()); auditVidStatus(jobId, job.getStatus()); uuids.add(jobId); - dataAccessService.saveDomainObject(createServiceInfo(userId, request, jobId, templateId, createdBulkDate), - DaoUtils.getPropsMap()); } return uuids; } - private ServiceInfo createServiceInfo(String userId, ServiceInstantiation serviceInstantiation, UUID jobId, - UUID templateId, Date createdBulkDate) { + private ServiceInfo.ServiceAction getAction(ServiceInstantiation request) { + if (request.getAction() == null) { + //throw new GenericUncheckedException("Required 'action' field not provided at service level"); + return Action.Create.getServiceAction(); + } + return request.getAction().getServiceAction(); + } + + + private String getOptimisticUniqueServiceInstanceName(ServiceInstantiation request) { + return StringUtils.isNotEmpty(request.getInstanceName()) ? getUniqueNameFromDbOnly(request.getInstanceName()) : request.getInstanceName(); + } + + protected ServiceInfo createServiceInfo(String userId, ServiceInstantiation serviceInstantiation, UUID jobId, UUID templateId, Date createdBulkDate, String optimisticUniqueServiceInstanceName, ServiceInfo.ServiceAction serviceAction) { return new ServiceInfo( - userId, Job.JobStatus.PENDING, serviceInstantiation.isPause(), jobId, templateId, - serviceInstantiation.getOwningEntityId(), - serviceInstantiation.getOwningEntityName(), - serviceInstantiation.getProjectName(), - serviceInstantiation.getAicZoneId(), - serviceInstantiation.getAicZoneName(), - serviceInstantiation.getTenantId(), - serviceInstantiation.getTenantName(), - serviceInstantiation.getLcpCloudRegionId(), - null, - serviceInstantiation.getSubscriptionServiceType(), - serviceInstantiation.getSubscriberName(), - null, - serviceInstantiation.getInstanceName(), - serviceInstantiation.getModelInfo().getModelInvariantId(), - serviceInstantiation.getModelInfo().getModelName(), - serviceInstantiation.getModelInfo().getModelVersion(), - createdBulkDate + userId, + serviceInstantiation.isALaCarte(), + Job.JobStatus.PENDING, serviceInstantiation.isPause(), jobId, templateId, + serviceInstantiation.getOwningEntityId(), + serviceInstantiation.getOwningEntityName(), + serviceInstantiation.getProjectName(), + serviceInstantiation.getAicZoneId(), + serviceInstantiation.getAicZoneName(), + serviceInstantiation.getTenantId(), + serviceInstantiation.getTenantName(), + serviceInstantiation.getLcpCloudRegionId(), + null, + serviceInstantiation.getSubscriptionServiceType(), + serviceInstantiation.getSubscriberName(), + serviceInstantiation.getGlobalSubscriberId(), + serviceInstantiation.getInstanceId(), + optimisticUniqueServiceInstanceName, + serviceInstantiation.getModelInfo().getModelVersionId(), + serviceInstantiation.getModelInfo().getModelName(), + serviceInstantiation.getModelInfo().getModelVersion(), + createdBulkDate, + serviceAction ); } @Override - public RequestDetailsWrapper generateServiceInstantiationRequest(UUID jobId, - ServiceInstantiation payload, String userId) { + public RequestDetailsWrapper generateMacroServiceInstantiationRequest(UUID jobId, ServiceInstantiation payload, String optimisticUniqueServiceInstanceName, String userId) { + String serviceInstanceName = generateServiceName(jobId, payload, optimisticUniqueServiceInstanceName); + + List serviceInstantiationServiceList = generateServiceInstantiationServicesList(payload, serviceInstanceName, createServiceInstantiationVnfList(payload)); + + RequestParameters requestParameters = new RequestParameters(payload.getSubscriptionServiceType(), false, serviceInstantiationServiceList); + + ServiceInstantiationRequestDetails requestDetails = generateServiceInstantiationRequestDetails(payload,requestParameters,serviceInstanceName, userId); + + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper<>(requestDetails); + debugRequestDetails(requestDetailsWrapper, logger); + + return requestDetailsWrapper; + } + + @Override + public RequestDetailsWrapper generateALaCarteServiceInstantiationRequest(UUID jobId, ServiceInstantiation payload, String optimisticUniqueServiceInstanceName, String userId) { + String serviceInstanceName = generateServiceName(jobId, payload, optimisticUniqueServiceInstanceName); + + List userParams = generateUserParamList(); + + RequestParameters requestParameters = new RequestParameters(payload.getSubscriptionServiceType(), true, userParams, payload.getTestApi()); + + ServiceInstantiationRequestDetails requestDetails = generateServiceInstantiationRequestDetails(payload,requestParameters,serviceInstanceName, userId); + + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper<>(requestDetails); + debugRequestDetails(requestDetailsWrapper, logger); + return requestDetailsWrapper; + } + + + @Override + public RequestDetailsWrapper generateALaCarteServiceDeletionRequest(UUID jobId, ServiceInstantiation payload, String userId){ + + ServiceDeletionRequestDetails.RequestParameters requestParameters = new ServiceDeletionRequestDetails.RequestParameters( true, payload.getTestApi()); + + ServiceDeletionRequestDetails.RequestInfo requestInfo = new ServiceDeletionRequestDetails.RequestInfo( + VID_SOURCE, + userId); + + ServiceDeletionRequestDetails requestDetails = new ServiceDeletionRequestDetails(payload.getModelInfo(), requestInfo, requestParameters); + + RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper<>(requestDetails); + debugRequestDetails(requestDetailsWrapper, logger); + return requestDetailsWrapper; + } + + @Override + public RequestDetailsWrapper generateVnfInstantiationRequest(Vnf vnfDetails, ModelInfo serviceModelInfo, String serviceInstanceId, String userId) { + + VnfInstantiationRequestDetails.RequestInfo requestInfo = new VnfInstantiationRequestDetails.RequestInfo( + getUniqueNameIfNeeded(vnfDetails.getInstanceName(), ResourceType.GENERIC_VNF), + vnfDetails.getProductFamilyId(), + VID_SOURCE, + vnfDetails.isRollbackOnFailure(), + userId); + CloudConfiguration cloudConfiguration = generateCloudConfiguration(vnfDetails.getLcpCloudRegionId(), vnfDetails.getTenantId()); + VnfInstantiationRequestDetails.Platform platform = new VnfInstantiationRequestDetails.Platform(vnfDetails.getPlatformName()); + VnfInstantiationRequestDetails.LineOfBusiness lineOfBusiness = new VnfInstantiationRequestDetails.LineOfBusiness(vnfDetails.getLineOfBusiness()); + VnfInstantiationRequestDetails.RequestParameters requestParameters = new VnfInstantiationRequestDetails.RequestParameters(generateUserParamList()); + VnfInstantiationRequestDetails.RelatedInstance serviceInstance = new VnfInstantiationRequestDetails.RelatedInstance(serviceModelInfo, serviceInstanceId); + List relatedInstanceList = new ArrayList<>(); + relatedInstanceList.add(serviceInstance); + return new RequestDetailsWrapper<>(new VnfInstantiationRequestDetails(vnfDetails.getModelInfo(), cloudConfiguration, requestInfo, platform, lineOfBusiness, relatedInstanceList, requestParameters)); + } + + @Override + public RequestDetailsWrapper generateVfModuleInstantiationRequest(VfModule vfModuleDetails, ModelInfo serviceModelInfo, String serviceInstanceId, ModelInfo vnfModelInfo, String vnfInstanceId, String vgInstanceId, String userId) { + + VfModuleInstantiationRequestDetails.RequestInfo requestInfo = new VfModuleInstantiationRequestDetails.RequestInfo( + getUniqueNameIfNeeded(vfModuleDetails.getInstanceName(), ResourceType.VF_MODULE), + null, + VID_SOURCE, + vfModuleDetails.isRollbackOnFailure(), + userId); + + //cloud configuration + CloudConfiguration cloudConfiguration = generateCloudConfiguration(vfModuleDetails.getLcpCloudRegionId(), vfModuleDetails.getTenantId()); + + //request parameters + List> userParams = aggregateAllInstanceParams(extractActualInstanceParams(vfModuleDetails.getInstanceParams()), vfModuleDetails.getSupplementaryParams()); + RequestParametersVfModule requestParameters = new RequestParametersVfModule(userParams, vfModuleDetails.isUsePreload()); + + //related instance list + VfModuleInstantiationRequestDetails.RelatedInstance serviceInstance = new VfModuleInstantiationRequestDetails.RelatedInstance(serviceModelInfo, serviceInstanceId); + VfModuleInstantiationRequestDetails.RelatedInstance vnfInstance = new VfModuleInstantiationRequestDetails.RelatedInstance(vnfModelInfo, vnfInstanceId); + List relatedInstanceList = new ArrayList<>(); + relatedInstanceList.add(serviceInstance); + relatedInstanceList.add(vnfInstance); + if (vgInstanceId != null) { + ModelInfo volumeGroupModel = new ModelInfo(); + volumeGroupModel.setModelType("volumeGroup"); + VfModuleInstantiationRequestDetails.RelatedInstance volumeGroupInstance = new VfModuleInstantiationRequestDetails.RelatedInstance(volumeGroupModel, vgInstanceId, vfModuleDetails.getVolumeGroupInstanceName()); + relatedInstanceList.add(volumeGroupInstance); + } + + return new RequestDetailsWrapper<>(new VfModuleInstantiationRequestDetails(vfModuleDetails.getModelInfo(), cloudConfiguration, requestInfo, relatedInstanceList, requestParameters)); + } + + protected CloudConfiguration generateCloudConfiguration(String lcpCloudRegionId, String tenantId) { + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setLcpCloudRegionId(lcpCloudRegionId); + cloudConfiguration.setTenantId(tenantId); + cloudOwnerService.enrichCloudConfigurationWithCloudOwner(cloudConfiguration, lcpCloudRegionId); + return cloudConfiguration; + } + + @Override + public RequestDetailsWrapper generateVolumeGroupInstantiationRequest(VfModule vfModuleDetails, ModelInfo serviceModelInfo, String serviceInstanceId, ModelInfo vnfModelInfo, String vnfInstanceId, String userId) { + VolumeGroupRequestDetails.RequestInfo requestInfo = new VolumeGroupRequestDetails.RequestInfo( + getUniqueNameIfNeeded(vfModuleDetails.getVolumeGroupInstanceName(), ResourceType.VOLUME_GROUP), + null, + VID_SOURCE, + vfModuleDetails.isRollbackOnFailure(), + userId); + CloudConfiguration cloudConfiguration = generateCloudConfiguration(vfModuleDetails.getLcpCloudRegionId(), vfModuleDetails.getTenantId()); + + List> userParams = aggregateAllInstanceParams(extractActualInstanceParams(vfModuleDetails.getInstanceParams()), vfModuleDetails.getSupplementaryParams()); + RequestParametersVfModule requestParameters = new RequestParametersVfModule(userParams, vfModuleDetails.isUsePreload()); + + VfModuleInstantiationRequestDetails.RelatedInstance serviceInstance = new VfModuleInstantiationRequestDetails.RelatedInstance(serviceModelInfo, serviceInstanceId); + VfModuleInstantiationRequestDetails.RelatedInstance vnfInstance = new VfModuleInstantiationRequestDetails.RelatedInstance(vnfModelInfo, vnfInstanceId); + List relatedInstancs = ImmutableList.of(serviceInstance, vnfInstance); + + ModelInfo modelInfo = vfModuleDetails.getModelInfo(); + modelInfo.setModelType("volumeGroup"); + return new RequestDetailsWrapper<>(new VolumeGroupRequestDetails(modelInfo, cloudConfiguration, requestInfo, relatedInstancs, requestParameters)); + } + + protected List> aggregateAllInstanceParams(Map instanceParams, Map supplementaryParams) { + Map instanceParamsFinal = defaultIfNull(instanceParams, new HashMap<>()); + Map supplementaryParamsFinal = defaultIfNull(supplementaryParams, new HashMap<>()); + + if (!(instanceParamsFinal.isEmpty() && supplementaryParamsFinal.isEmpty())) { + //remove duplicate keys from instanceParams if exist in supplementaryParams + instanceParamsFinal = instanceParams.entrySet().stream().filter(m-> + !supplementaryParamsFinal.containsKey(m.getKey()) + ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + //aggregate the 2 collections and format them as UserParamMap + UserParamMap aggregatedParams = new UserParamMap<>(); + aggregatedParams.putAll(instanceParamsFinal); + aggregatedParams.putAll(supplementaryParamsFinal); + + return ImmutableList.of(aggregatedParams); + } - ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity owningEntity = new ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity( - payload.getOwningEntityId(), payload.getOwningEntityName()); + return Collections.emptyList(); + } + + @Override + public RequestDetailsWrapper generateNetworkInstantiationRequest(Network networkDetails, ModelInfo serviceModelInfo, String serviceInstanceId, String userId) { + + NetworkInstantiationRequestDetails.RequestInfo requestInfo = new NetworkInstantiationRequestDetails.RequestInfo( + getUniqueNameIfNeeded(networkDetails.getInstanceName(), ResourceType.L3_NETWORK), + networkDetails.getProductFamilyId(), + VID_SOURCE, + networkDetails.isRollbackOnFailure(), + userId); + CloudConfiguration cloudConfiguration = generateCloudConfiguration(networkDetails.getLcpCloudRegionId(), networkDetails.getTenantId()); + NetworkInstantiationRequestDetails.Platform platform = new NetworkInstantiationRequestDetails.Platform(networkDetails.getPlatformName()); + NetworkInstantiationRequestDetails.LineOfBusiness lineOfBusiness = new NetworkInstantiationRequestDetails.LineOfBusiness(networkDetails.getLineOfBusiness()); + NetworkInstantiationRequestDetails.RequestParameters requestParameters = new NetworkInstantiationRequestDetails.RequestParameters(generateUserParamList()); + NetworkInstantiationRequestDetails.RelatedInstance serviceInstance = new NetworkInstantiationRequestDetails.RelatedInstance(serviceModelInfo, serviceInstanceId); + List relatedInstanceList = new ArrayList<>(); + relatedInstanceList.add(serviceInstance); + return new RequestDetailsWrapper<>(new NetworkInstantiationRequestDetails(networkDetails.getModelInfo(), cloudConfiguration, requestInfo, platform, lineOfBusiness, relatedInstanceList, requestParameters)); + } + @Override + public RequestDetailsWrapper generateInstanceGroupInstantiationRequest(InstanceGroup instanceGroupDetails, ModelInfo serviceModelInfo, String serviceInstanceId, String userId) { + InstanceGroupInstantiationRequestDetails.RequestInfo requestInfo = new InstanceGroupInstantiationRequestDetails.RequestInfo( + getUniqueNameIfNeeded(instanceGroupDetails.getInstanceName(), ResourceType.INSTANCE_GROUP), + null, + "VID", + instanceGroupDetails.isRollbackOnFailure(), + userId); + InstanceGroupInstantiationRequestDetails.RequestParameters requestParameters = new InstanceGroupInstantiationRequestDetails.RequestParameters(generateUserParamList()); + InstanceGroupInstantiationRequestDetails.RelatedInstance serviceInstance = new InstanceGroupInstantiationRequestDetails.RelatedInstance(serviceModelInfo, serviceInstanceId); + List relatedInstanceList = ImmutableList.of(serviceInstance); + return new RequestDetailsWrapper<>(new InstanceGroupInstantiationRequestDetails(instanceGroupDetails.getModelInfo(), requestInfo, relatedInstanceList, requestParameters)); + } + + // TODO + private List generateUserParamList() { + return Collections.emptyList(); + } + + protected List generateServiceInstantiationServicesList(ServiceInstantiation payload, String serviceInstanceName, ServiceInstantiationVnfList vnfList) { + List serviceInstantiationServiceList = new LinkedList<>(); + List> unFilteredInstanceParams = defaultIfNull(payload.getInstanceParams(), Collections.emptyList()); + List> filteredInstanceParams = removeUnNeededParams(unFilteredInstanceParams); + ServiceInstantiationService serviceInstantiationService = new ServiceInstantiationService( + payload.getModelInfo(), + serviceInstanceName, + filteredInstanceParams, + vnfList + ); + serviceInstantiationServiceList.add(serviceInstantiationService); + return serviceInstantiationServiceList; + } + + private ServiceInstantiationRequestDetails generateServiceInstantiationRequestDetails(ServiceInstantiation payload, RequestParameters requestParameters, String serviceInstanceName, String userId) { + ServiceInstantiationRequestDetails.RequestInfo requestInfo = new ServiceInstantiationRequestDetails.RequestInfo(serviceInstanceName, + payload.getProductFamilyId(), + VID_SOURCE, + payload.isRollbackOnFailure(), + userId); + ServiceInstantiationOwningEntity owningEntity = new ServiceInstantiationOwningEntity(payload.getOwningEntityId(), payload.getOwningEntityName()); + SubscriberInfo subscriberInfo = generateSubscriberInfo(payload); + Project project = payload.getProjectName() != null ? new Project(payload.getProjectName()) : null; + return new ServiceInstantiationRequestDetails(payload.getModelInfo(), owningEntity, subscriberInfo, project, requestInfo, requestParameters); + } + + + protected SubscriberInfo generateSubscriberInfo(ServiceInstantiation payload) { SubscriberInfo subscriberInfo = new SubscriberInfo(); subscriberInfo.setGlobalSubscriberId(payload.getGlobalSubscriberId()); + return subscriberInfo; + } + protected String generateServiceName(UUID jobId, ServiceInstantiation payload, String optimisticUniqueServiceInstanceName) { String serviceInstanceName = null; - if (payload.isUserProvidedNaming()) { + if(StringUtils.isNotEmpty(optimisticUniqueServiceInstanceName)) { + serviceInstanceName = peekServiceName(jobId, payload, optimisticUniqueServiceInstanceName); + } + return serviceInstanceName; + } + + protected String peekServiceName(UUID jobId, ServiceInstantiation payload, String optimisticUniqueServiceInstanceName) { + String serviceInstanceName; + // unique name already exist in service info. If it's free in AAI we use it + if (isNameFreeInAai(optimisticUniqueServiceInstanceName, ResourceType.SERVICE_INSTANCE)) { + serviceInstanceName = optimisticUniqueServiceInstanceName; + } + //otherwise we used the original service instance name (from payload) to get a new unique name from DB and AAI + else { serviceInstanceName = getUniqueName(payload.getInstanceName(), ResourceType.SERVICE_INSTANCE); - String finalServiceInstanceName = serviceInstanceName; - updateServiceInfo(jobId, x -> x.setServiceInstanceName(finalServiceInstanceName)); } - ServiceInstantiationRequestDetails.RequestInfo requestInfo = new ServiceInstantiationRequestDetails.RequestInfo( - serviceInstanceName, - payload.getProductFamilyId(), - "VID", - payload.isRollbackOnFailure(), - userId); - - List serviceInstantiationService = new LinkedList<>(); - List> unFilteredInstanceParams = - payload.getInstanceParams() != null ? payload.getInstanceParams() : new LinkedList<>(); - List> filteredInstanceParams = removeUnNeededParams(unFilteredInstanceParams); - ServiceInstantiationRequestDetails.ServiceInstantiationService serviceInstantiationService1 = new ServiceInstantiationRequestDetails.ServiceInstantiationService( - payload.getModelInfo(), - serviceInstanceName, - filteredInstanceParams, - createServiceInstantiationVnfList(payload) - ); - serviceInstantiationService.add(serviceInstantiationService1); - ServiceInstantiationRequestDetails.RequestParameters requestParameters = new ServiceInstantiationRequestDetails.RequestParameters( - payload.getSubscriptionServiceType(), false, serviceInstantiationService); + //update serviceInfo with new name if needed + try { + updateServiceInfo(jobId, x -> x.setServiceInstanceName(serviceInstanceName)); + } catch (Exception e) { + logger.error("Failed updating service name {} in serviceInfo", serviceInstanceName, e); + } - ServiceInstantiationRequestDetails.Project project = - payload.getProjectName() != null ? new ServiceInstantiationRequestDetails.Project(payload.getProjectName()) - : null; + return serviceInstanceName; + } - ServiceInstantiationRequestDetails requestDetails = new ServiceInstantiationRequestDetails( - payload.getModelInfo(), owningEntity, subscriberInfo, - project, requestInfo, requestParameters); + @Override + public List> buildVnfInstanceParams(List> currentVnfInstanceParams, List vfModules){ + List> filteredVnfInstanceParams = removeUnNeededParams(currentVnfInstanceParams); - RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper( - requestDetails); - debugRequestDetails(requestDetailsWrapper, logger); - return requestDetailsWrapper; + if (!featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)) { + return filteredVnfInstanceParams; + } + + Map vnfInstanceParams = extractActualInstanceParams(filteredVnfInstanceParams); + vfModules.stream() + .map(x->extractActualInstanceParams(x.getInstanceParams())) + .forEach(vnfInstanceParams::putAll); + return vnfInstanceParams.isEmpty() ? Collections.emptyList() : ImmutableList.of(vnfInstanceParams); + } + + //Make sure we always get a one Map from InstanceParams + private Map extractActualInstanceParams(List> originalInstanceParams) { + if (originalInstanceParams==null || originalInstanceParams.isEmpty() || originalInstanceParams.get(0)==null) { + return new HashMap<>(); + } + return originalInstanceParams.get(0); } private List> removeUnNeededParams(List> instanceParams) { List keysToRemove = new ArrayList<>(); - if (instanceParams != null && !instanceParams.isEmpty()) { - for (String key : instanceParams.get(0).keySet()) { - for (String paramToIgnore : PARAMS_TO_IGNORE) { - if ((key.equalsIgnoreCase(paramToIgnore))) { - keysToRemove.add(key); - } + if (instanceParams == null || instanceParams.isEmpty()) { + return Collections.emptyList(); + } + + for (String key : instanceParams.get(0).keySet()) { + for (String paramToIgnore : PARAMS_TO_IGNORE) + if ((key.equalsIgnoreCase(paramToIgnore))) { + keysToRemove.add(key); } - } - for (String key : keysToRemove) { - instanceParams.get(0).remove(key); - } - //TODO will be removed on once we stop using List> - if (instanceParams.get(0).isEmpty()) { - return Collections.emptyList(); - } } - return instanceParams; + + Map result = instanceParams.get(0).entrySet().stream() + .filter(entry->!keysToRemove.contains(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return result.isEmpty() ? Collections.emptyList() : Collections.singletonList(result); } - private ServiceInstantiationRequestDetails.ServiceInstantiationVnfList createServiceInstantiationVnfList( - ServiceInstantiation payload) { - CloudConfiguration cloudConfiguration = new CloudConfiguration(); - cloudConfiguration.setTenantId(payload.getTenantId()); - cloudConfiguration.setLcpCloudRegionId(payload.getLcpCloudRegionId()); + private ServiceInstantiationVnfList createServiceInstantiationVnfList(ServiceInstantiation payload) { + CloudConfiguration cloudConfiguration = generateCloudConfiguration(payload.getLcpCloudRegionId(), payload.getTenantId()); Map vnfs = payload.getVnfs(); - List vnfList = new ArrayList<>(); + List vnfList = new ArrayList<>(); for (Vnf vnf : vnfs.values()) { Map> vfModules = vnf.getVfModules(); - List convertedUnFilteredVfModules = convertVfModuleMapToList(vfModules); - List filteredVfModules = filterInstanceParamsFromVfModuleAndUniqueNames( - convertedUnFilteredVfModules, vnf.isUserProvidedNaming()); - ServiceInstantiationRequestDetails.ServiceInstantiationVnf serviceInstantiationVnf = new ServiceInstantiationRequestDetails.ServiceInstantiationVnf( - vnf.getModelInfo(), - cloudConfiguration, - vnf.getPlatformName(), - vnf.getLineOfBusiness(), - payload.getProductFamilyId(), - removeUnNeededParams(vnf.getInstanceParams()), - filteredVfModules, - vnf.isUserProvidedNaming() ? getUniqueName(vnf.getInstanceName(), ResourceType.GENERIC_VNF) : null + List convertedUnFilteredVfModules = convertVfModuleMapToList(vfModules); + List filteredVfModules = filterInstanceParamsFromVfModuleAndUniqueNames(convertedUnFilteredVfModules); + ServiceInstantiationVnf serviceInstantiationVnf = new ServiceInstantiationVnf( + vnf.getModelInfo(), + cloudConfiguration, + vnf.getPlatformName(), + vnf.getLineOfBusiness(), + payload.getProductFamilyId(), + buildVnfInstanceParams(vnf.getInstanceParams(), filteredVfModules), + filteredVfModules, + getUniqueNameIfNeeded(vnf.getInstanceName(), ResourceType.GENERIC_VNF) ); vnfList.add(serviceInstantiationVnf); } - return new ServiceInstantiationRequestDetails.ServiceInstantiationVnfList(vnfList); + return new ServiceInstantiationVnfList(vnfList); } - private List convertVfModuleMapToList(Map> vfModules) { - return vfModules.values().stream().flatMap(vfModule -> vfModule.values().stream()).collect(Collectors.toList()); + private List convertVfModuleMapToList(Map> vfModules) { + ObjectMapper mapper = new ObjectMapper(); + return vfModules.values().stream().flatMap(vfModule -> + vfModule.values().stream().map(item -> { + List> aggregatedParams = aggregateAllInstanceParams(extractActualInstanceParams(item.getInstanceParams()), item.getSupplementaryParams()); + List> aggregatedParamsConverted = mapper.convertValue(aggregatedParams, new TypeReference>(){}); + + return new VfModuleMacro( + item.getModelInfo(), + item.getInstanceName(), + item.getVolumeGroupInstanceName(), + aggregatedParamsConverted); + } + ) + ).collect(Collectors.toList()); } - private List filterInstanceParamsFromVfModuleAndUniqueNames(List unFilteredVfModules, - boolean isUserProvidedNaming) { + private List filterInstanceParamsFromVfModuleAndUniqueNames(List unFilteredVfModules) { return unFilteredVfModules.stream().map(vfModule -> - new VfModule( - vfModule.getModelInfo(), - getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getInstanceName(), ResourceType.VF_MODULE), - getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getVolumeGroupInstanceName(), - ResourceType.VOLUME_GROUP), - removeUnNeededParams(vfModule.getInstanceParams()))) - .collect(Collectors.toList()); + new VfModuleMacro( + vfModule.getModelInfo(), + getUniqueNameIfNeeded(vfModule.getInstanceName(), ResourceType.VF_MODULE), + getUniqueNameIfNeeded(vfModule.getVolumeGroupInstanceName(), ResourceType.VOLUME_GROUP), + removeUnNeededParams(vfModule.getInstanceParams()))) + .collect(Collectors.toList()); } - private String getUniqueNameIfNeeded(boolean isUserProvidedNaming, String name, ResourceType resourceType) { - return isUserProvidedNaming && !StringUtils.isEmpty(name) ? - getUniqueName(name, resourceType) : null; + private String getUniqueNameIfNeeded(String name, ResourceType resourceType) { + return StringUtils.isNotEmpty(name) ? getUniqueName(name, resourceType) : null; } @Override public String getServiceInstantiationPath(ServiceInstantiation serviceInstantiationRequest) { //in case pause flag is true - use assign , else - use create. return MsoBusinessLogicImpl.validateEndpointPath( - serviceInstantiationRequest.isPause() ? - "mso.restapi.serviceInstanceAssign" : "mso.restapi.serviceInstanceCreate" + serviceInstantiationRequest.isPause() ? + MsoProperties.MSO_REST_API_SERVICE_INSTANCE_ASSIGN : MsoProperties.MSO_REST_API_SERVICE_INSTANCE_CREATE ); } + @Override + public String getServiceDeletionPath(String serviceInstanceId) { + return MsoBusinessLogicImpl.validateEndpointPath( MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE) + "/" + serviceInstanceId; + } + + @Override + public String getVnfInstantiationPath(String serviceInstanceId) { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE). + replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + } + + @Override + public String getNetworkInstantiationPath(String serviceInstanceId) { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE). + replaceFirst(SVC_INSTANCE_ID, serviceInstanceId); + } + + @Override + public String getVfmoduleInstantiationPath(String serviceInstanceId, String vnfInstanceId) { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE) + .replaceFirst(SVC_INSTANCE_ID, serviceInstanceId) + .replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + } + + @Override + public String getVolumeGroupInstantiationPath(String serviceInstanceId, String vnfInstanceId) { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE) + .replaceFirst(SVC_INSTANCE_ID, serviceInstanceId) + .replaceFirst(VNF_INSTANCE_ID, vnfInstanceId); + } + + @Override + public String getInstanceGroupInstantiationPath() { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_INSTANCE_GROUP); + } + + @Override + public String getInstanceGroupDeletePath(String instanceGroupId) { + return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_INSTANCE_GROUP) + + '/' + instanceGroupId; + } + @Override public String getOrchestrationRequestsPath() { return MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_GET_ORC_REQ); @@ -333,7 +625,7 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu @Override public ServiceInfo updateServiceInfoAndAuditStatus(UUID jobUuid, JobStatus jobStatus) { - auditVidStatus(jobUuid, jobStatus); + auditVidStatus(jobUuid,jobStatus); return updateServiceInfo(jobUuid, x -> setServiceInfoStatus(x, jobStatus)); } @@ -343,12 +635,9 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu } public ServiceInfo getServiceInfoByJobId(UUID jobUUID) { - List serviceInfoList = dataAccessService - .getList(ServiceInfo.class, String.format(" where jobId = '%s' ", jobUUID), null, null); + List serviceInfoList = dataAccessService.getList(ServiceInfo.class, String.format(" where jobId = '%s' ", jobUUID), null, null); if (serviceInfoList.size() != 1) { - throw new GenericUncheckedException( - "Failed to retrieve job with uuid " + jobUUID + " from ServiceInfo table. Instances found: " - + serviceInfoList.size()); + throw new GenericUncheckedException("Failed to retrieve job with uuid " + jobUUID + " from ServiceInfo table. Instances found: " + serviceInfoList.size()); } return serviceInfoList.get(0); } @@ -356,46 +645,43 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu public List getAuditStatuses(UUID jobUUID, JobAuditStatus.SourceStatus source) { return dataAccessService.getList( JobAuditStatus.class, - String.format(" where SOURCE = '%s' and JOB_ID = '%s'", source, jobUUID), + String.format(" where SOURCE = '%s' and JOB_ID = '%s'",source, jobUUID), " CREATED_DATE ", null); } - private JobAuditStatus getLatestAuditStatus(UUID jobUUID, JobAuditStatus.SourceStatus source) { - List list = getAuditStatuses(jobUUID, source); - return !list.isEmpty() ? list.get(list.size() - 1) : null; + private JobAuditStatus getLatestAuditStatus(UUID jobUUID, JobAuditStatus.SourceStatus source){ + List list = getAuditStatuses(jobUUID,source); + return !list.isEmpty() ? list.get(list.size()-1) : null; } @Override - public void auditVidStatus(UUID jobUUID, JobStatus jobStatus) { + public void auditVidStatus(UUID jobUUID, JobStatus jobStatus){ JobAuditStatus vidStatus = new JobAuditStatus(jobUUID, jobStatus.toString(), JobAuditStatus.SourceStatus.VID); auditStatus(vidStatus); } @Override - public void auditMsoStatus(UUID jobUUID, AsyncRequestStatus.Request msoRequestStatus) { - auditMsoStatus(jobUUID, msoRequestStatus.requestStatus.getRequestState(), msoRequestStatus.requestId, - msoRequestStatus.requestStatus.getStatusMessage()); + public void auditMsoStatus(UUID jobUUID, AsyncRequestStatus.Request msoRequestStatus){ + auditMsoStatus(jobUUID, msoRequestStatus.requestStatus.getRequestState(), msoRequestStatus.requestId, msoRequestStatus.requestStatus.getStatusMessage()); } @Override - public void auditMsoStatus(UUID jobUUID, String jobStatus, String requestId, String additionalInfo) { + public void auditMsoStatus(UUID jobUUID, String jobStatus, String requestId, String additionalInfo){ JobAuditStatus msoStatus = new JobAuditStatus(jobUUID, jobStatus, JobAuditStatus.SourceStatus.MSO, - requestId != null ? UUID.fromString(requestId) : null, - additionalInfo); + requestId != null ? UUID.fromString(requestId) : null, + additionalInfo); auditStatus(msoStatus); } - private void auditStatus(JobAuditStatus jobAuditStatus) { + private void auditStatus(JobAuditStatus jobAuditStatus){ JobAuditStatus latestStatus = getLatestAuditStatus(jobAuditStatus.getJobId(), jobAuditStatus.getSource()); - if (latestStatus == null || !latestStatus.equals(jobAuditStatus)) { + if (latestStatus == null || !latestStatus.equals(jobAuditStatus)) dataAccessService.saveDomainObject(jobAuditStatus, DaoUtils.getPropsMap()); - } } public Job.JobStatus calcStatus(AsyncRequestStatus asyncRequestStatus) { - String msoRequestState = asyncRequestStatus.request.requestStatus.getRequestState().toLowerCase() - .replaceAll("[^a-z]+", ""); + String msoRequestState = asyncRequestStatus.request.requestStatus.getRequestState().toLowerCase().replaceAll("[^a-z]+", ""); JobStatus jobStatus = msoStateToJobStatusMap.get(msoRequestState); return (jobStatus != null ? jobStatus : JobStatus.IN_PROGRESS); } @@ -404,11 +690,11 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu public void handleFailedInstantiation(UUID jobUUID) { ServiceInfo serviceInfo = updateServiceInfoAndAuditStatus(jobUUID, JobStatus.FAILED); List serviceInfoList = dataAccessService.getList( - ServiceInfo.class, - String.format(" where templateId = '%s' and jobStatus = '%s'", - serviceInfo.getTemplateId(), - JobStatus.PENDING), - null, null); + ServiceInfo.class, + String.format(" where templateId = '%s' and jobStatus = '%s'", + serviceInfo.getTemplateId(), + JobStatus.PENDING), + null, null); serviceInfoList.forEach(si -> updateServiceInfoAndAuditStatus(si.getJobId(), JobStatus.STOPPED)); } @@ -423,9 +709,9 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu public void hideServiceInfo(UUID jobUUID) { ServiceInfo serviceInfo = getServiceInfoByJobId(jobUUID); if (!serviceInfo.getJobStatus().isFinal()) { - String message = String.format("jobId %s: Service status does not allow hide service, status = %s", - serviceInfo.getJobId(), - serviceInfo.getJobStatus()); + String message = String.format( "jobId %s: Service status does not allow hide service, status = %s", + serviceInfo.getJobId(), + serviceInfo.getJobStatus()); logger.error(EELFLoggerDelegate.errorLogger, message); throw new OperationNotAllowedException(message); } @@ -434,31 +720,30 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu } @Override - public int - - getCounterForName(String name) { + public int getCounterForName(String name) { String hqlSelectNC = "from NameCounter where name = :name"; String hqlUpdateCounter = "update NameCounter set counter = :newCounter " + - "where name= :name " + - "and counter= :prevCounter"; + "where name= :name " + + "and counter= :prevCounter"; Integer counter = null; GenericUncheckedException lastException = null; - for (int i = 0; i < MAX_RETRIES_GETTING_COUNTER && counter == null; i++) { + for (int i = 0; i< MAX_RETRIES_GETTING_COUNTER && counter==null; i++) { try { counter = calcCounter(name, hqlSelectNC, hqlUpdateCounter); - } catch (GenericUncheckedException exception) { + } + catch (GenericUncheckedException exception) { lastException = exception; //do nothing, we will try again in the loop } } - if (counter != null) { + if (counter!=null) { return counter; } - throw lastException != null ? new DbFailureUncheckedException(lastException) : - new DbFailureUncheckedException("Failed to get counter for " + name + " due to unknown error"); + throw lastException!=null ? new DbFailureUncheckedException(lastException) : + new DbFailureUncheckedException("Failed to get counter for "+name+" due to unknown error"); } @@ -466,14 +751,14 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu Integer counter; counter = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { NameCounter nameCounter = (NameCounter) session.createQuery(hqlSelectNC) - .setText("name", name) - .uniqueResult(); + .setText("name", name) + .uniqueResult(); if (nameCounter != null) { int updatedRows = session.createQuery(hqlUpdateCounter) - .setText("name", nameCounter.getName()) - .setInteger("prevCounter", nameCounter.getCounter()) - .setInteger("newCounter", nameCounter.getCounter() + 1) - .executeUpdate(); + .setText("name", nameCounter.getName()) + .setInteger("prevCounter", nameCounter.getCounter()) + .setInteger("newCounter", nameCounter.getCounter() + 1) + .executeUpdate(); if (updatedRows == 1) { return nameCounter.getCounter() + 1; } @@ -481,7 +766,7 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu Object nameAsId = session.save(new NameCounter(name)); //if save success if (nameAsId != null) { - return 1; + return 0; } } //in case of failure return null, in order to continue the loop @@ -506,34 +791,28 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu //Prevents unnecessary increasing of the counter while AAI doesn't response isNameFreeInAai(NAME_FOR_CHECK_AAI_STATUS, resourceType); - for (int i = 0; i < getMaxRetriesGettingFreeNameFromAai(); i++) { - int counter = getCounterForName(name); - String newName = formatNameAndCounter(name, counter); + for (int i=0; i aaiResponse = aaiOverTLSClient - .searchNodeTypeByName(name, resourceType); - if (aaiResponse.getStatus() > 399 || aaiResponse.getBody() == null) { - try { - String message = IOUtils.toString(aaiResponse.getRawBody(), "UTF-8"); - throw new InvalidAAIResponseException(aaiResponse.getStatus(), message); - } catch (IOException e) { - throw new InvalidAAIResponseException(aaiResponse.getStatus(), aaiResponse.getStatusText()); - } - } - return CollectionUtils.isEmpty(aaiResponse.getBody().resultData); + private boolean isNameFreeInAai(String name, ResourceType resourceType) throws ExceptionWithRequestInfo { + return !aaiClient.isNodeTypeExistsByName(name, resourceType); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java b/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java index 19569a7f..01443dea 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AuditService.java @@ -1,11 +1,18 @@ package org.onap.vid.services; -import org.onap.vid.model.RequestReferencesContainer; -import org.onap.vid.mso.RestObject; +import org.onap.vid.model.JobAuditStatus; +import java.util.List; import java.util.UUID; public interface AuditService { void setFailedAuditStatusFromMso(UUID jobUuid, String requestId, int statusCode, String msoResponse); + + + List getAuditStatusFromMsoByRequestId(UUID jobId, UUID requestId); + + List getAuditStatusFromMsoByServiceInstanceId(UUID jobId, UUID serviceInstanceId); + + List getAuditStatusFromMsoByJobId(UUID jobId); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java index b4806f1c..339a9edd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/AuditServiceImpl.java @@ -1,47 +1,42 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.services; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.mso.MsoProperties; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.mso.rest.AsyncRequestStatusList; import org.springframework.stereotype.Service; import javax.inject.Inject; import java.io.IOException; +import java.util.List; import java.util.UUID; +import java.util.stream.Collectors; @Service public class AuditServiceImpl implements AuditService{ + private final AsyncInstantiationBusinessLogic asyncInstantiationBL; + private final RestMsoImplementation restMso; + @Inject - private AsyncInstantiationBusinessLogic asyncInstantiationBL; - public static final String FAILED_MSO_REQUEST_STATUS = "FAILED"; + public AuditServiceImpl(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation restMso) { + this.asyncInstantiationBL = asyncInstantiationBL; + this.restMso = restMso; + } @Override public void setFailedAuditStatusFromMso(UUID jobUuid, String requestId, int statusCode, String msoResponse){ + final String failedMsoRequestStatus = "FAILED"; String additionalInfo = formatExceptionAdditionalInfo(statusCode, msoResponse); - asyncInstantiationBL.auditMsoStatus(jobUuid, FAILED_MSO_REQUEST_STATUS, requestId, additionalInfo); + asyncInstantiationBL.auditMsoStatus(jobUuid, failedMsoRequestStatus, requestId, additionalInfo); } private String formatExceptionAdditionalInfo(int statusCode, String msoResponse) { @@ -64,4 +59,90 @@ public class AuditServiceImpl implements AuditService{ } return errorMsg; } + + @Override + public List getAuditStatusFromMsoByRequestId(UUID jobId, UUID requestId) { + String filter = "requestId:EQUALS:" + requestId; + return getAuditStatusFromMso(jobId, filter, null); + } + + @Override + public List getAuditStatusFromMsoByServiceInstanceId(UUID jobId, UUID serviceInstanceId) { + String filter = "serviceInstanceId:EQUALS:" + serviceInstanceId; + return getAuditStatusFromMso(jobId, filter, serviceInstanceId); + } + + @Override + public List getAuditStatusFromMsoByJobId(UUID jobId) { + List auditStatuses = asyncInstantiationBL.getAuditStatuses(jobId, JobAuditStatus.SourceStatus.MSO); + String instanceName = getInstanceNameFromServiceInfo(jobId); + auditStatuses.stream().forEach(status -> + status.setInstanceName(instanceName) + ); + return auditStatuses; + } + + + + private List getAuditStatusFromMso(UUID jobId, String filter, UUID serviceInstanceId) { + + String path = MsoBusinessLogicImpl.validateEndpointPath(MsoProperties.MSO_REST_API_GET_ORC_REQS) + "filter=" + filter; + RestObject msoResponse = restMso.GetForObject(path , AsyncRequestStatusList.class); + if (msoResponse.getStatusCode() >= 400 || msoResponse.get() == null) { + throw new BadResponseFromMso(msoResponse); + } + + //add service name from service info for each audit status (in case that serviceInstanceId is null all statuses belong to service) + String userInstanceName = serviceInstanceId == null ? getInstanceNameFromServiceInfo(jobId): null; + return convertMsoResponseStatusToJobAuditStatus(msoResponse.get().getRequestList(), userInstanceName); + } + + private String getInstanceNameFromServiceInfo(UUID jobId) { + return asyncInstantiationBL.getServiceInfoByJobId(jobId).getServiceInstanceName(); + } + + protected List convertMsoResponseStatusToJobAuditStatus(List msoStatuses, String defaultName){ + return msoStatuses.stream().map(status -> { + UUID requestId = null; + String instanceName = defaultName; + String jobStatus = null; + String additionalInfo = null; + String created = null; + String instanceType = null; + + AsyncRequestStatus.Request request = status.request; + if(request != null) { + requestId = UUID.fromString(request.requestId); + instanceName = extractInstanceName(instanceName, request); + instanceType = request.requestScope; + if(request.requestStatus != null) { + jobStatus = request.requestStatus.getRequestState(); + additionalInfo = request.requestStatus.getStatusMessage(); + if(!request.requestStatus.getAdditionalProperties().isEmpty()) { + created = request.requestStatus.getAdditionalProperties().get("finishTime") != null? request.requestStatus.getAdditionalProperties().get("finishTime").toString() : request.requestStatus.getTimestamp(); + } + } + } + return new JobAuditStatus(instanceName, jobStatus, requestId, additionalInfo, created, instanceType); + }).collect(Collectors.toList()); + } + + private String extractInstanceName(String instanceName, AsyncRequestStatus.Request request) { + if(request.requestDetails != null && request.requestDetails.requestInfo != null && request.requestDetails.requestInfo.instanceName != null) { + instanceName = request.requestDetails.requestInfo.instanceName; + } + return instanceName; + } + + public static class BadResponseFromMso extends RuntimeException { + private final RestObject msoResponse; + + public BadResponseFromMso(RestObject msoResponse) { + this.msoResponse = msoResponse; + } + + public RestObject getMsoResponse() { + return msoResponse; + } + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java index 387edc12..645a6122 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationService.java @@ -1,15 +1,11 @@ package org.onap.vid.services; -import org.onap.vid.model.JobBulk; import org.onap.vid.model.JobModel; -import java.util.Map; import java.util.UUID; public interface BulkInstantiationService { - JobBulk saveBulk(Map bulkRequest); - JobModel getJob(UUID uuid); } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java index 2a868f13..20f719a7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/BulkInstantiationServiceImpl.java @@ -3,14 +3,11 @@ package org.onap.vid.services; import org.onap.vid.job.Job; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobsBrokerService; -import org.onap.vid.model.JobBulk; import org.onap.vid.model.JobModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.ws.rs.NotFoundException; -import java.util.List; -import java.util.Map; import java.util.UUID; @Service @@ -25,13 +22,6 @@ public class BulkInstantiationServiceImpl implements BulkInstantiationService { this.jobAdapter = jobAdapter; } - @Override - public JobBulk saveBulk(Map bulkRequest) { - List jobList = jobAdapter.createBulkOfJobs(bulkRequest); - jobList.forEach(jobsBrokerService::add); - return jobAdapter.toModelBulk(jobList); - } - @Override public JobModel getJob(UUID uuid) { Job job = jobsBrokerService.peek(uuid); diff --git a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java index ab6239fd..c83e1937 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementService.java @@ -1,8 +1,9 @@ package org.onap.vid.services; +import com.fasterxml.jackson.databind.node.ArrayNode; import org.apache.commons.lang3.tuple.Pair; -import org.json.simple.JSONArray; import org.onap.vid.changeManagement.*; +import org.onap.vid.mso.RestObjectWithRequestInfo; import org.onap.vid.mso.rest.Request; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -13,7 +14,8 @@ import java.util.List; public interface ChangeManagementService { Collection getMSOChangeManagements(); ResponseEntity doChangeManagement(ChangeManagementRequest request, String vnfName); - JSONArray getSchedulerChangeManagements(); + ArrayNode getSchedulerChangeManagements(); + RestObjectWithRequestInfo getSchedulerChangeManagementsWithRequestInfo(); /** * Deleting a scheduled flow. diff --git a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java index e4a6b399..13525f84 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/ChangeManagementServiceImpl.java @@ -1,20 +1,23 @@ package org.onap.vid.services; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.hibernate.NonUniqueObjectException; import org.json.JSONObject; -import org.json.simple.JSONArray; -import org.json.simple.parser.JSONParser; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.*; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.exceptions.NotFoundException; import org.onap.vid.model.VNFDao; import org.onap.vid.model.VidWorkflow; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoResponseWrapperInterface; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.RestObjectWithRequestInfo; import org.onap.vid.mso.rest.Request; import org.onap.vid.scheduler.SchedulerProperties; import org.onap.vid.scheduler.SchedulerRestInterfaceIfc; @@ -34,26 +37,27 @@ import java.util.stream.Collectors; @Service public class ChangeManagementServiceImpl implements ChangeManagementService { - private final static String PRIMARY_KEY = "payload"; - private final static Set REQUIRED_KEYS = new HashSet<>(Arrays.asList("request-parameters", "configuration-parameters")); + private static final String PRIMARY_KEY = "payload"; + private static final Set REQUIRED_KEYS = new HashSet<>(Arrays.asList("request-parameters", "configuration-parameters")); private final DataAccessService dataAccessService; private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ChangeManagementServiceImpl.class); private MsoBusinessLogic msoBusinessLogic; private final SchedulerRestInterfaceIfc restClient; + private final CloudOwnerService cloudOwnerService; @Autowired private CsvService csvService; @Autowired - public ChangeManagementServiceImpl(DataAccessService dataAccessService, MsoBusinessLogic msoBusinessLogic, SchedulerRestInterfaceIfc schedulerRestInterface) { + public ChangeManagementServiceImpl(DataAccessService dataAccessService, MsoBusinessLogic msoBusinessLogic, SchedulerRestInterfaceIfc schedulerRestInterface, CloudOwnerService cloudOwnerService) { this.dataAccessService = dataAccessService; this.msoBusinessLogic = msoBusinessLogic; this.restClient = schedulerRestInterface; + this.cloudOwnerService = cloudOwnerService; } @Override public Collection getMSOChangeManagements() { - Collection result = null; return msoBusinessLogic.getOrchestrationRequestsForDashboard(); } @@ -86,14 +90,17 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { try { switch (requestType.toLowerCase()) { case ChangeManagementRequest.UPDATE: { + cloudOwnerService.enrichRequestWithCloudOwner(currentRequestDetails); msoResponseWrapperObject = msoBusinessLogic.updateVnf(currentRequestDetails, serviceInstanceId, vnfInstanceId); break; } case ChangeManagementRequest.REPLACE: { + cloudOwnerService.enrichRequestWithCloudOwner(currentRequestDetails); msoResponseWrapperObject = msoBusinessLogic.replaceVnf(currentRequestDetails, serviceInstanceId, vnfInstanceId); break; } case ChangeManagementRequest.VNF_IN_PLACE_SOFTWARE_UPDATE: { + cloudOwnerService.enrichRequestWithCloudOwner(currentRequestDetails); msoResponseWrapperObject = msoBusinessLogic.updateVnfSoftware(currentRequestDetails, serviceInstanceId, vnfInstanceId); break; } @@ -105,10 +112,10 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { msoResponseWrapperObject = msoBusinessLogic.scaleOutVfModuleInstance(currentRequestDetails, serviceInstanceId, vnfInstanceId); break; } - default: - logger.error("Failure during doChangeManagement with request " + request.toString()); + default: + throw new GenericUncheckedException("Failure during doChangeManagement with request " + request.toString()); } - response = new ResponseEntity(msoResponseWrapperObject.getResponse(), HttpStatus.OK); + response = new ResponseEntity<>(msoResponseWrapperObject.getResponse(), HttpStatus.OK); return response; } catch (Exception e) { logger.error("Failure during doChangeManagement with request " + request.toString(), e); @@ -141,32 +148,26 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { } @Override - public JSONArray getSchedulerChangeManagements() { - JSONArray result = null; - try { - String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_SCHEDULES); - org.onap.vid.scheduler.RestObject restObject = new org.onap.vid.scheduler.RestObject<>(); - - String str = new String(); - restObject.set(str); - restClient.Get(str, "", path, restObject); - String restCallResult = restObject.get(); - JSONParser parser = new JSONParser(); - Object parserResult = parser.parse(restCallResult); - result = (JSONArray) parserResult; - } catch (Exception e) { - e.printStackTrace(); - } + public RestObjectWithRequestInfo getSchedulerChangeManagementsWithRequestInfo() { + String path = SystemProperties.getProperty(SchedulerProperties.SCHEDULER_GET_SCHEDULES); + RestObject restObject = new RestObject<>(); + ArrayNode jsonArray = new ArrayNode(new JsonNodeFactory(true)); + restObject.set(jsonArray); + return restClient.Get(jsonArray, path, restObject); + } - return result; + @Override + public ArrayNode getSchedulerChangeManagements() { + RestObjectWithRequestInfo responseWithRequestInfo = getSchedulerChangeManagementsWithRequestInfo(); + return responseWithRequestInfo.getRestObject().get(); } @Override public Pair deleteSchedule(String scheduleId) { try { String path = String.format(SystemProperties.getProperty(SchedulerProperties.SCHEDULER_DELETE_SCHEDULE), scheduleId); - org.onap.vid.scheduler.RestObject restObject = new org.onap.vid.scheduler.RestObject<>(); - String str = new String(); + RestObject restObject = new RestObject<>(); + String str = ""; restObject.set(str); restClient.Delete(str, "", path, restObject); String restCallResult = restObject.get(); @@ -187,11 +188,11 @@ public class ChangeManagementServiceImpl implements ChangeManagementService { continue; } @SuppressWarnings("unchecked") List vnfList = dataAccessService.getList(VNFDao.class, getVnfQueryString(workflowsDetail.getVnfDetails().getUUID(), workflowsDetail.getVnfDetails().getInvariantUUID()), null, null); - if (vnfList.size() == 0) { + if (vnfList.isEmpty()) { vnfList.add(saveNewVnf(workflowsDetail)); } @SuppressWarnings("unchecked") List workflowList = dataAccessService.getList(VidWorkflow.class, String.format(" where wokflowName = '%s'", workflowsDetail.getWorkflowName()), null, null); - if (workflowList.size() == 0) { + if (workflowList.isEmpty()) { vnfWorkflowRelationResponse.getErrors().add("Not Found instance of workflow " + workflowsDetail.getWorkflowName() + " for vnf with UUID " + workflowsDetail.getVnfDetails().getUUID() + " and with invariantUUID " + workflowsDetail.getVnfDetails().getInvariantUUID()); continue; } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerService.java b/vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerService.java new file mode 100644 index 00000000..1d453819 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerService.java @@ -0,0 +1,12 @@ +package org.onap.vid.services; + +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.rest.RequestDetails; + +public interface CloudOwnerService { + + void enrichRequestWithCloudOwner(RequestDetails msoRequest); + + void enrichCloudConfigurationWithCloudOwner(CloudConfiguration cloudConfiguration, String lcpCloudRegionId); + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerServiceImpl.java new file mode 100644 index 00000000..3acab9ff --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/services/CloudOwnerServiceImpl.java @@ -0,0 +1,76 @@ +package org.onap.vid.services; + + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.StringUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.properties.Features; +import org.springframework.beans.factory.annotation.Autowired; +import org.togglz.core.manager.FeatureManager; + +import java.util.List; +import java.util.Map; + +public class CloudOwnerServiceImpl implements CloudOwnerService { + + private static final List CLOUD_CONFIGURATION_PATH = ImmutableList.of("requestDetails", "cloudConfiguration"); + private static final List LCP_CLOUD_REGION_ID_PATH = ImmutableList.of("requestDetails", "cloudConfiguration", "lcpCloudRegionId"); + + private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(CloudOwnerService.class); + + private final AaiClientInterface aaiClient; + private final FeatureManager featureManager; + + @Autowired + public CloudOwnerServiceImpl(AaiClientInterface aaiClient, FeatureManager featureManager) { + this.aaiClient = aaiClient; + this.featureManager = featureManager; + } + + @Override + public void enrichRequestWithCloudOwner(RequestDetails msoRequest) { + if (!featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)) { + return; + } + try { + + //if cloudConfiguration field contains lcpRegion (e.g. in changeManagement scenarios) + if (msoRequest.getCloudConfiguration()!=null && StringUtils.isNotEmpty(msoRequest.getCloudConfiguration().getLcpCloudRegionId())) { + enrichCloudConfigurationWithCloudOwner(msoRequest.getCloudConfiguration(), msoRequest.getCloudConfiguration().getLcpCloudRegionId()); + } + //otherwise the cloudConfiguration is in the additionalProperties field of RequestDetails (e.g. in ng1 view/edit scenario) + else { + enrichRequestWithCloudOwnerByAdditionalProperties(msoRequest); + } + } + catch (Exception e) { + throw new GenericUncheckedException("Failed to enrich requestDetails with cloudOwner", e); + } + } + + protected void enrichRequestWithCloudOwnerByAdditionalProperties(RequestDetails msoRequest) { + String lcpCloudRegionId = null; + try { + lcpCloudRegionId = msoRequest.extractValueByPathUsingAdditionalProperties(LCP_CLOUD_REGION_ID_PATH, String.class); + } + catch (NotFoundException exception) { + LOGGER.debug("Can't find lcp region in RequestDetails. Assume no cloudOwner enrichment is needed. Reason: "+exception.getMessage()); + return; + } + String cloudOwner = aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId); + msoRequest.extractValueByPathUsingAdditionalProperties(CLOUD_CONFIGURATION_PATH, Map.class).put("cloudOwner", cloudOwner); + } + + @Override + public void enrichCloudConfigurationWithCloudOwner(CloudConfiguration cloudConfiguration, String lcpCloudRegionId) { + if (featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)) { + String cloudOwner = aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId); + cloudConfiguration.setCloudOwner(cloudOwner); + } + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CsvService.java b/vid-app-common/src/main/java/org/onap/vid/services/CsvService.java index 248068fb..6e4a0665 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/CsvService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/CsvService.java @@ -3,7 +3,6 @@ package org.onap.vid.services; import org.json.JSONObject; import org.springframework.web.multipart.MultipartFile; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; diff --git a/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java index c34bf4e6..6ba15222 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/CsvServiceImpl.java @@ -165,7 +165,7 @@ public class CsvServiceImpl implements CsvService{ * @throws IllegalAccessException * @throws InstantiationException */ - private T putJson(T json, String key, E values) throws IllegalAccessException, InstantiationException { + private T putJson(T json, String key, E values) { if (json instanceof JSONArray){ JSONArray currentJson= ((JSONArray)json); if (values == null) //array of strings (for last item) @@ -176,11 +176,8 @@ public class CsvServiceImpl implements CsvService{ if (keyExistsOrFirstElement(currentJson, key)) { currentJson.put(new JSONObject().put(key, values)); } else { - JSONObject lastItem = lastItemInArray(currentJson); - if(lastItem != null){ - lastItem.put(key, values); - } - + JSONObject lastItem = lastItemInArray(currentJson); + lastItem.put(key, values); } } } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java index 500f5ac7..3ff8db0e 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java @@ -23,16 +23,11 @@ package org.onap.vid.services; import io.joshworks.restclient.http.HttpResponse; import jline.internal.Log; -import org.onap.vid.aai.AaiClientInterface; -import org.onap.vid.aai.AaiOverTLSClientInterface; -import org.onap.vid.aai.AaiResponse; -import org.onap.vid.aai.ServiceSubscription; -import org.onap.vid.aai.Services; +import org.onap.vid.aai.*; import org.onap.vid.model.ModelConstants; import org.onap.vid.model.Subscriber; import org.onap.vid.model.SubscriberList; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.HashMap; @@ -46,7 +41,6 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { AaiClientInterface client; @Autowired - @Qualifier("aaiClientForCodehausMapping") AaiOverTLSClientInterface aaiOverTLSClient; public static final String DB_NAME = "vid_portal"; @@ -73,8 +67,9 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { } private String addAvailableRolesCombination(Boolean firstRun, SubscriberList subscribers) { - String query, availableRoles=""; - HashMap servicesNames = new HashMap(); + String query; + String availableRoles=""; + HashMap servicesNames = new HashMap<>(); for (Subscriber subscriber: subscribers.customer) { AaiResponse subscriberResponse = client.getSubscriberData(subscriber.globalCustomerId); for(ServiceSubscription service: subscriberResponse.getT().serviceSubscriptions.serviceSubscription) { @@ -146,13 +141,12 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService { } private String insertAvailableRolesToFnRole(){ - String query="INSERT INTO fn_role (ROLE_NAME, ACTIVE_YN, PRIORITY)\r\n" + + return "INSERT INTO fn_role (ROLE_NAME, ACTIVE_YN, PRIORITY)\r\n" + "SELECT RNAME, 'Y', 5\r\n" + "FROM available_roles\r\n" + "WHERE NOT EXISTS (SELECT ROLE_NAME\r\n" + "FROM fn_role \r\n" + "where RNAME = ROLE_NAME);\r\n"; - return query; } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java index 1890a5b3..aedd1b95 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/VidServiceImpl.java @@ -52,9 +52,7 @@ public class VidServiceImpl implements VidService { * The Constant LOG. */ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidServiceImpl.class); - /** - * The Constant dateFormat. - */ + protected final AsdcClient asdcClient; private final FeatureManager featureManager; @@ -126,7 +124,7 @@ public class VidServiceImpl implements VidService { final Service asdcServiceMetadata = asdcClient.getService(UUID.fromString(uuid)); return getServiceModel(uuid, serviceCsar, tosca, asdcServiceMetadata); } catch (Exception e) { - LOG.error("Failed to download and proccess service from SDC", e); + LOG.error("Failed to download and process service from SDC", e); } return serviceModel; } diff --git a/vid-app-common/src/main/java/org/onap/vid/services/WorkflowService.java b/vid-app-common/src/main/java/org/onap/vid/services/WorkflowService.java index ea139080..775b6a9d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/services/WorkflowService.java +++ b/vid-app-common/src/main/java/org/onap/vid/services/WorkflowService.java @@ -1,6 +1,5 @@ package org.onap.vid.services; -import org.onap.vid.model.Workflow; import java.util.Collection; public interface WorkflowService { diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/KotlinUtils.kt b/vid-app-common/src/main/java/org/onap/vid/utils/KotlinUtils.kt new file mode 100644 index 00000000..7ccdd1bc --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/KotlinUtils.kt @@ -0,0 +1,10 @@ +package org.onap.vid.utils + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper + +inline fun > getEnumFromMapOfStrings(map: Map, key:String, defaultValue:E): E { + return java.lang.Enum.valueOf(E::class.java, (map.getOrDefault(key, defaultValue.name) as String)) +} + +val JACKSON_OBJECT_MAPPER: ObjectMapper = jacksonObjectMapper() \ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java index 3ac90588..f02497b0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java @@ -28,12 +28,14 @@ import static org.onap.vid.utils.Streams.not; public class Logging { - Logging() { + private Logging() { } public static final String HTTP_REQUESTS_OUTGOING = "http.requests.outgoing."; public static final String REQUEST_ID_HEADER_KEY = SystemProperties.ECOMP_REQUEST_ID; + public static final String ONAP_REQUEST_ID_HEADER_KEY = "X-ONAP-RequestID"; + private static ObjectMapper objectMapper = new ObjectMapper(); diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Multival.java b/vid-app-common/src/main/java/org/onap/vid/utils/Multival.java new file mode 100644 index 00000000..3a9b518d --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Multival.java @@ -0,0 +1,54 @@ +package org.onap.vid.utils; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.util.Collection; +import java.util.function.Function; + +import static java.util.stream.Collectors.toSet; + +@JsonPropertyOrder({"keyType", "valuesType"}) +public class Multival { + private final String keyType; + private final String valuesType; + private final K key; + private final Collection values; + + private Multival(String keyType, K key, String valuesType, Collection values) { + this.keyType = keyType; + this.key = key; + this.valuesType = valuesType; + this.values = values; + } + + public static Multival of(String keyType, K key, String valuesType, Collection values) { + return new Multival<>(keyType, key, valuesType, values); + } + + public String getKeyType() { + return keyType; + } + + public String getValuesType() { + return valuesType; + } + + public K getKey() { + return key; + } + + public Collection getValues() { + return values; + } + + public Multival mapEachVal(Function mapper) { + return Multival.of( + this.getKeyType(), + this.getKey(), + this.getValuesType(), + this.getValues().stream() + .map(mapper) + .collect(toSet()) + ); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Streams.java b/vid-app-common/src/main/java/org/onap/vid/utils/Streams.java index 7f81b225..9c836912 100644 --- a/vid-app-common/src/main/java/org/onap/vid/utils/Streams.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Streams.java @@ -9,13 +9,22 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Streams { + + private Streams() { + // hide the implicit public constructor + } + public static Predicate not(Predicate predicate) { return predicate.negate(); } public static Stream fromIterator(final Iterator iterator) { Iterable iterable = () -> iterator; - return StreamSupport.stream(iterable.spliterator(), false); + return StreamSupport.stream(iterable.spliterator(), false); + } + + public static Stream fromIterable(final Iterable iterable) { + return StreamSupport.stream(iterable.spliterator(), false); } diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/TimeUtils.java b/vid-app-common/src/main/java/org/onap/vid/utils/TimeUtils.java new file mode 100644 index 00000000..7d281454 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/TimeUtils.java @@ -0,0 +1,21 @@ +package org.onap.vid.utils; + +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class TimeUtils { + private static DateTimeFormatter formatter = DateTimeFormatter.RFC_1123_DATE_TIME; + + private TimeUtils() { + // explicit private constructor, to hide the implicit public constructor + } + + public static ZonedDateTime parseZonedDateTime(String time) { + + return ZonedDateTime.from(formatter.parse(time)); + } + + public static String zonedDateTimeToString(ZonedDateTime time) { + return formatter.format(time); + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Tree.kt b/vid-app-common/src/main/java/org/onap/vid/utils/Tree.kt new file mode 100644 index 00000000..28f989bb --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Tree.kt @@ -0,0 +1,44 @@ +package org.onap.vid.utils + +data class Node(val value:T, val children:MutableMap> = hashMapOf()) + +data class Tree(private val root:Node) { + + constructor(value: T) : this(Node(value)) + + fun getRootValue():T { + return root.value; + } + + fun addPath(vararg path: T) { + addPath(path.asList()) + } + + fun addPath(path:Collection) { + var currentNode = root + path.forEach { + currentNode = currentNode.children.getOrPut(it) {Node(it)} + } + } + + fun getSubTree(vararg path: T): Tree? { + return getSubTree(path.asList()) + } + + fun getSubTree(path:Collection): Tree? { + var currentNode:Node = root + path.forEach { + currentNode = currentNode.children[it] ?: return null + } + return Tree(currentNode) + } + + fun isPathExist(vararg path: T): Boolean { + return isPathExist(path.asList()) + } + + fun isPathExist(path:Collection): Boolean { + return getSubTree(path)!=null + } +} + diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java b/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java new file mode 100644 index 00000000..25bf0efd --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Unchecked.java @@ -0,0 +1,23 @@ +package org.onap.vid.utils; + +import org.onap.vid.exceptions.GenericUncheckedException; + +import java.net.URI; +import java.net.URISyntaxException; + +public class Unchecked { + private Unchecked() { + // explicit private constructor, to hide the implicit public constructor + } + + public static URI toURI(String uri) { + try { + // Indulge spaces in the URI by the replcement + return new URI(uri.replace(" ", "%20")); + } catch (URISyntaxException e) { + throw new GenericUncheckedException(e); + } + } + + +} diff --git a/vid-app-common/src/main/resources/1712_ADIOD.zip b/vid-app-common/src/main/resources/1712_ADIOD.zip index 281ee8aa..de8fa7eb 100644 Binary files a/vid-app-common/src/main/resources/1712_ADIOD.zip and b/vid-app-common/src/main/resources/1712_ADIOD.zip differ diff --git a/vid-app-common/src/main/resources/2f80c596.zip b/vid-app-common/src/main/resources/2f80c596.zip index 0babeeb2..95161faa 100644 Binary files a/vid-app-common/src/main/resources/2f80c596.zip and b/vid-app-common/src/main/resources/2f80c596.zip differ diff --git a/vid-app-common/src/main/resources/adiod.zip b/vid-app-common/src/main/resources/adiod.zip index 6c928a35..6e024234 100644 Binary files a/vid-app-common/src/main/resources/adiod.zip and b/vid-app-common/src/main/resources/adiod.zip differ diff --git a/vid-app-common/src/main/resources/cacheConfig.json b/vid-app-common/src/main/resources/cacheConfig.json new file mode 100644 index 00000000..01836bd6 --- /dev/null +++ b/vid-app-common/src/main/resources/cacheConfig.json @@ -0,0 +1,17 @@ +{ + "getTenants" : { + "isActive": true, + "expireAfterWriteHours": 24, + "refreshAfterWriteSeconds": 300 + }, + "getServiceModelsByDistributionStatus" : { + "isActive": true, + "expireAfterWriteHours": 24, + "refreshAfterWriteSeconds": 300 + }, + "getAllSubscribers" : { + "isActive": true, + "expireAfterWriteHours": 24, + "refreshAfterWriteSeconds": 300 + } +} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/csar317927061915233480.zip b/vid-app-common/src/main/resources/csar317927061915233480.zip index ce58b17d..ad959896 100644 Binary files a/vid-app-common/src/main/resources/csar317927061915233480.zip and b/vid-app-common/src/main/resources/csar317927061915233480.zip differ diff --git a/vid-app-common/src/main/resources/csar3933948645405128424.zip b/vid-app-common/src/main/resources/csar3933948645405128424.zip index ee9b4fb0..13c65168 100644 Binary files a/vid-app-common/src/main/resources/csar3933948645405128424.zip and b/vid-app-common/src/main/resources/csar3933948645405128424.zip differ diff --git a/vid-app-common/src/main/resources/json/mso/cloudConfiguration b/vid-app-common/src/main/resources/json/mso/cloudConfiguration deleted file mode 100755 index eb627798..00000000 --- a/vid-app-common/src/main/resources/json/mso/cloudConfiguration +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "fields communicating the cloud configuration in a standard way", - "type": "object", - "properties": { - "nodeLocation": { - "description": "Location identifier for the node", - "type": "string" - }, - "lcpCloudRegionId": { - "description": "LCP Node Location identifier", - "type": "string" - }, - "tenantId": { - "description": "Openstack tenant id", - "type": "string" - } - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/instanceIds b/vid-app-common/src/main/resources/json/mso/instanceIds deleted file mode 100755 index c20ea9ad..00000000 --- a/vid-app-common/src/main/resources/json/mso/instanceIds +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "instanceIds that may be associated with a particular request", - "type": "object", - "properties": { - "networkInstanceId": { - "description": "UUID for the network instance (if any)", - "type": "string" - }, - "serviceInstanceId": { - "description": "UUID for the service instance", - "type": "string" - }, - "vfModuleInstanceId": { - "description": "UUID for the vfModule instance (if any)", - "type": "string" - }, - "vnfInstanceId": { - "description": "UUID for the vnf instance (if any)", - "type": "string" - }, - "volumeGroupInstanceId": { - "description": "UUID for the volume group instance (if any)", - "type": "string" - } - } -} - - \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/modelInfo b/vid-app-common/src/main/resources/json/mso/modelInfo deleted file mode 100755 index 56d268ce..00000000 --- a/vid-app-common/src/main/resources/json/mso/modelInfo +++ /dev/null @@ -1,42 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "fields describing the SDC entity being operated on by the request", - "type": "object", - "properties": { - "modelCustomizationName": { - "description": "reference to the customized set of parameters associated with a model in a given service context", - "type": "string" - }, - "modelCustomizationId": { - "description": "reference to the customized set of parameters associated with a model in a given service context", - "type": "string" - }, - "modelInvariantId": { - "description": "Invariant UUID for the model name, irrespective of the version, as defined in SDC--authoritative", - "type": "string", - "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" - }, - "modelVersionId": { - "description": "Version id for version", - "type": "string" - }, - "modelName": { - "description": "name of the model as defined in SDC--not authoritative", - "type": "string" - }, - "modelNameVersionId": { - "description": "UUID for the model name and version combination as defined in SDC--authoritative", - "type": "string", - "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" - }, - "modelType": { - "description": "short description of the entity being operated on", - "type": "string" - }, - "modelVersion": { - "description": "the version of the model as defined in SDC--not authoritative", - "type": "string" - } - }, - "required": ["modelType"] -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/relatedInstance b/vid-app-common/src/main/resources/json/mso/relatedInstance deleted file mode 100755 index 89554a54..00000000 --- a/vid-app-common/src/main/resources/json/mso/relatedInstance +++ /dev/null @@ -1,16 +0,0 @@ -{ - "description": "modelInfo and optional instanceId and instanceName for a model related to the modelInfo being operated on", - "type": "object", - "properties": { - "instanceName": { - "description": "optional name for the instance Id of the related model", - "type": "string" - }, - "instanceId": { - "description": "instance Id for the related model", - "type": "string" - }, - "modelInfo": {} - }, - "required": ["modelInfo"] -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/relatedModel b/vid-app-common/src/main/resources/json/mso/relatedModel deleted file mode 100755 index a70a1718..00000000 --- a/vid-app-common/src/main/resources/json/mso/relatedModel +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "modelInfo and optional instance id for a model related to the modelInfo being operated on", - "type": "object", - "properties": { - "instanceId": { - "description": "instance Id for the related model", - "type": "string" - }, - "modelInfo": {} - }, - "required": [ "modelInfo" ] -} - - diff --git a/vid-app-common/src/main/resources/json/mso/request b/vid-app-common/src/main/resources/json/mso/request deleted file mode 100755 index 61f10400..00000000 --- a/vid-app-common/src/main/resources/json/mso/request +++ /dev/null @@ -1,32 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "request structure", - "type": "object", - "properties": { - "finishTime": { - "description": "Date and time the request was finished in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT", - "type": "string" - }, - "instanceIds": {}, - "requestDetails": {}, - "requestId": { - "description": "UUID for the request generated by the instantiation service", - "type": "string", - "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" - }, - "requestScope": { - "description": "short description of the entity being operated on", - "type": "string" - }, - "requestStatus": {}, - "requestType": { - "description": "short description of the action being performed on the requestScope", - "type": "string" - }, - "startTime": { - "description": "Date and time the request was created in GMT with the following sample format: Wed, 15 Oct 2014 13:01:52 GMT", - "type": "string" - } - }, - "required": ["requestDetails", "requestId", "requestScope", "requestType", "startTime"] -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/requestDetails b/vid-app-common/src/main/resources/json/mso/requestDetails deleted file mode 100755 index c0ef5304..00000000 --- a/vid-app-common/src/main/resources/json/mso/requestDetails +++ /dev/null @@ -1,13 +0,0 @@ -{ - "description": "aggregates the context, configuraiton and detailed parameters associated with the request into a single structure", - "properties": { - "cloudConfiguration": {}, - "modelInfo": {}, - "relatedModelList": {}, - "requestInfo": {}, - "requestParameters": {}, - "subscriberInfo": {} - }, - "type": "object" -} - diff --git a/vid-app-common/src/main/resources/json/mso/requestError b/vid-app-common/src/main/resources/json/mso/requestError deleted file mode 100755 index 497f6719..00000000 --- a/vid-app-common/src/main/resources/json/mso/requestError +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "standard request error data structure", - "properties": { - "messageId": { - "description": "Unique message identifier of the format ABCnnnn where ABC is either SVC for Service Exceptions or POL for Policy Exception", - "type": "string" - }, - "text": { - "description": "Message text, with replacement variables marked with %n, where n is an index into the list of elements, starting at 1", - "type": "string" - }, - "url": { - "description": "Hyperlink to a detailed error resource e.g., an HTML page for browser user agents", - "type": "string" - }, - "variables": { - "description": "List of zero or more strings that represent the contents of the variables used by the message text", - "type": "string" - } - }, - "required": [ - "messageId", - "text" - ], - "type": "object" -} diff --git a/vid-app-common/src/main/resources/json/mso/requestInfo b/vid-app-common/src/main/resources/json/mso/requestInfo deleted file mode 100755 index 5fcf74c7..00000000 --- a/vid-app-common/src/main/resources/json/mso/requestInfo +++ /dev/null @@ -1,52 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "fields providing general context information for the request", - "properties": { - "billingAccountNumber": { - "description": "billing account associated with the model being operated on", - "type": "string" - }, - "callbackUrl": { - "description": "client URL to use for asynchronous responses", - "type": "string" - }, - "correlator": { - "description": "Optional correlationId for async callback requests", - "type": "string" - }, - "instanceName": { - "description": "Client provided name for the instance being operated on by the operation (note: not guaranteed to be unique)", - "type": "string" - }, - "orderNumber": { - "description": "reference to an order", - "type": "string" - }, - "orderVersion": { - "description": "order version number", - "type": "number" - }, - "productFamilyId": { - "description": "UUID for the product family associated with the model being operated on", - "type": "string" - }, - "source": { - "description": "source of the request--not authoritative--actual source revealed via authentication", - "type": "string" - }, - "suppressRollback": { - "description": "true or false boolean indicating whether rollbacks should be suppressed on failures", - "type": "boolean" - }, - "responseValue": { - "description": "Is the user selected value based on the validResponses list provided to complete the manual task", - "type": "string" - }, - "requestorId": { - "description": "The id of the person who initiated the completion request", - "type": "string" - } - }, - - "type": "object" -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/requestParameters b/vid-app-common/src/main/resources/json/mso/requestParameters deleted file mode 100755 index 010d7871..00000000 --- a/vid-app-common/src/main/resources/json/mso/requestParameters +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "type": "object", - "properties": { - "subscriptionServiceType": { - "type": "string" - }, - "userParams": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "value": { - "type": "string" - } - } - } - } - } - } \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/requestReferences b/vid-app-common/src/main/resources/json/mso/requestReferences deleted file mode 100755 index 30f64119..00000000 --- a/vid-app-common/src/main/resources/json/mso/requestReferences +++ /dev/null @@ -1,18 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "provides the instanceId and requestId associated with the request", - "type": "object", - "properties": { - "instanceId": { - "description": "UUID for the service instance", - "type": "string", - "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" - }, - "requestId": { - "description": "UUID for the request", - "type": "string", - "pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$" - } - }, - "required": [ "instanceId", "requestId" ] -} diff --git a/vid-app-common/src/main/resources/json/mso/requestStatus b/vid-app-common/src/main/resources/json/mso/requestStatus deleted file mode 100755 index 75b72151..00000000 --- a/vid-app-common/src/main/resources/json/mso/requestStatus +++ /dev/null @@ -1,32 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "fields describing the status of a request", - "properties": { - "percentProgress": { - "description": "percentage complete estimate from 0 to 100", - "type": "number" - }, - "requestState": { - "description": "short description of the instantiation state", - "type": "string" - }, - "statusMessage": { - "description": "additional descriptive information about the status", - "type": "string" - }, - "timestamp": { - "description": "GMT Datetime the requestStatus was created e.g.: Wed, 15 Oct 2014 13:01:52 GMT", - "type": "string" - }, - "wasRolledBack": { - "description": "true or false boolean indicating whether the request was rolled back", - "type": "boolean" - } - - }, - "required": [ - "requestState", - "timestamp" - ], - "type": "object" -} diff --git a/vid-app-common/src/main/resources/json/mso/response b/vid-app-common/src/main/resources/json/mso/response deleted file mode 100755 index fa37d2db..00000000 --- a/vid-app-common/src/main/resources/json/mso/response +++ /dev/null @@ -1,13 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "response structure", - "type": "object", - "code": { - "description": "Return code", - "type": "string" - }, - "message": { - "description": "Result message", - "type": "string" - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/json/mso/subscriberInfo b/vid-app-common/src/main/resources/json/mso/subscriberInfo deleted file mode 100755 index df787378..00000000 --- a/vid-app-common/src/main/resources/json/mso/subscriberInfo +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "fields providing information about the subscriber associated with the request", - "type": "object", - "properties": { - "globalSubscriberId": { - "description": "global Customer Id understood by A&AI", - "type": "string" - }, - "subscriberCommonSiteId": { - "description": "id representing the location of the subscriber", - "type": "string" - }, - "subscriberName": { - "description": "name of the customer or subscriber", - "type": "string" - } - } -} \ No newline at end of file diff --git a/vid-app-common/src/main/resources/pnf.zip b/vid-app-common/src/main/resources/pnf.zip index eb424846..541d89ec 100644 Binary files a/vid-app-common/src/main/resources/pnf.zip and b/vid-app-common/src/main/resources/pnf.zip differ diff --git a/vid-app-common/src/main/resources/sdcservices.json b/vid-app-common/src/main/resources/sdcservices.json index e300597e..965c9ceb 100644 --- a/vid-app-common/src/main/resources/sdcservices.json +++ b/vid-app-common/src/main/resources/sdcservices.json @@ -181,6 +181,48 @@ "distributionStatus": "DISTRIBUTED", "artifacts": null, "resources": null + }, + { + "uuid": "12344bb4-a416-4b4e-997e-0059973630b9", + "invariantUUID": "598e3f9e-3244-4d8f-a8e0-0e5d7a29eda9", + "name": "Fabric Configuration", + "version": "1.0", + "toscaModelURL": "./service-fabric-configuration.zip", + "category": "Mobility", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null + }, + { + "uuid": "1837481c-fa7d-4362-8ce1-d05fafc87bd1", + "invariantUUID": "93518289-3049-450f-a22d-86108c250265", + "name": "jenny vTSBC vlan SVC", + "version": "1.0", + "toscaModelURL": "./service-JennyVtsbcVlanSvc-csar.zip", + "category": "Network L1-3", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null + }, + { + "uuid": "4117a0b6-e234-467d-b5b9-fe2f68c8b0fc", + "invariantUUID": "7ee41ce4-4827-44b0-a48e-2707a59905d2", + "name": "Grouping Service for Test", + "version": "1.0", + "toscaModelURL": "./service-vnf-grouping-csar.zip", + "category": "Network L4+", + "lifecycleState": "CERTIFIED", + "lastUpdaterUserId": "rg276b", + "lastUpdaterFullName": null, + "distributionStatus": "DISTRIBUTED", + "artifacts": null, + "resources": null } ] } \ No newline at end of file diff --git a/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip b/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip index 1591a48f..c1fb9e08 100644 Binary files a/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip and b/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip differ diff --git a/vid-app-common/src/main/resources/service-vf-csar.zip b/vid-app-common/src/main/resources/service-vf-csar.zip index c3a9fbbe..3ecfa39a 100644 Binary files a/vid-app-common/src/main/resources/service-vf-csar.zip and b/vid-app-common/src/main/resources/service-vf-csar.zip differ diff --git a/vid-app-common/src/main/resources/service-vf-with-annotations.zip b/vid-app-common/src/main/resources/service-vf-with-annotations.zip index a6fcce7a..79c5fb0c 100644 Binary files a/vid-app-common/src/main/resources/service-vf-with-annotations.zip and b/vid-app-common/src/main/resources/service-vf-with-annotations.zip differ diff --git a/vid-app-common/src/main/resources/service-vl-csar.zip b/vid-app-common/src/main/resources/service-vl-csar.zip index 121192ae..dfe0b837 100644 Binary files a/vid-app-common/src/main/resources/service-vl-csar.zip and b/vid-app-common/src/main/resources/service-vl-csar.zip differ diff --git a/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties b/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties index 8ff0db2a..d82b043c 100644 --- a/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties +++ b/vid-app-common/src/main/webapp/WEB-INF/conf/dev.features.properties @@ -1,14 +1,32 @@ FLAG_ASYNC_INSTANTIATION = true FLAG_ASYNC_JOBS = true -FLAG_REGION_ID_FROM_REMOTE = true CREATE_INSTANCE_TEST = false EMPTY_DRAWING_BOARD_TEST = false -FLAG_ADVANCED_PORTS_FILTER = true FLAG_ADD_MSO_TESTAPI_FIELD = true FLAG_UNASSIGN_SERVICE = true FLAG_COLLECTION_RESOURCE_SUPPORT = true -FLAG_NETWORK_TO_ASYNC_INSTANTIATION = true +FLAG_NETWORK_TO_ASYNC_INSTANTIATION = false FLAG_SERVICE_MODEL_CACHE = true FLAG_SHOW_ASSIGNMENTS = true -FLAG_SHOW_VERIFY_SERVICE=false -FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD = false + +FLAG_SHOW_VERIFY_SERVICE = true +FLAG_DUPLICATE_VNF = true +FLAG_DEFAULT_VNF = true +FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD = true +FLAG_RESTRICTED_SELECT = false +FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS = true +FLAG_A_LA_CARTE_AUDIT_INFO=true +FLAG_5G_IN_NEW_INSTANTIATION_UI = true +FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS = true +FLAG_ASYNC_ALACARTE_VNF = true +FLAG_ASYNC_ALACARTE_VFMODULE= true +FLAG_SUPPLEMENTARY_FILE = true +FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF = true +FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI=false +FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST=true +FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY=true +FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE = true +FLAG_1810_AAI_LOCAL_CACHE = true +FLAG_1902_NEW_VIEW_EDIT= false +FLAG_EXP_USE_DEFAULT_HOST_NAME_VERIFIER = false +FLAG_1902_VNF_GROUPING = true diff --git a/vid-app-common/src/main/webapp/WEB-INF/conf/features.properties b/vid-app-common/src/main/webapp/WEB-INF/conf/features.properties index 3ca0e6e4..87b2d601 100644 --- a/vid-app-common/src/main/webapp/WEB-INF/conf/features.properties +++ b/vid-app-common/src/main/webapp/WEB-INF/conf/features.properties @@ -3,25 +3,43 @@ # This file is, generally, empty. -# Configure `featureFlags.filename` in system.properties to use +# Configure `features.set.filename` in system.properties to use # one of the ready-made sets: -# - featureFlags.filename = ci.features.properties -# - featureFlags.filename = ist.features.properties -# - featureFlags.filename = e2e.features.properties +# - features.set.filename = ci.features.properties +# - features.set.filename = ist.features.properties +# - features.set.filename = e2e.features.properties + +FLAG_PNP_INSTANTIATION = true FLAG_ASYNC_INSTANTIATION = true -FLAG_ASYNC_JOBS = false -FLAG_REGION_ID_FROM_REMOTE = true +FLAG_ASYNC_JOBS = true CREATE_INSTANCE_TEST = false EMPTY_DRAWING_BOARD_TEST = false -FLAG_ADVANCED_PORTS_FILTER = true FLAG_ADD_MSO_TESTAPI_FIELD = true FLAG_UNASSIGN_SERVICE = true FLAG_COLLECTION_RESOURCE_SUPPORT = true -FLAG_NETWORK_TO_ASYNC_INSTANTIATION = true +FLAG_NETWORK_TO_ASYNC_INSTANTIATION = false FLAG_SERVICE_MODEL_CACHE = true FLAG_SHOW_ASSIGNMENTS = true -FLAG_SHOW_VERIFY_SERVICE=false -FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD = false -FLAG_PNP_INSTANTIATION = true \ No newline at end of file +FLAG_SHOW_VERIFY_SERVICE = false +FLAG_DUPLICATE_VNF = true +FLAG_DEFAULT_VNF = true +FLAG_SETTING_DEFAULTS_IN_DRAWING_BOARD = true +FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS = true +FLAG_A_LA_CARTE_AUDIT_INFO=true +FLAG_5G_IN_NEW_INSTANTIATION_UI = true +FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS = true +FLAG_ASYNC_ALACARTE_VNF = true +FLAG_ASYNC_ALACARTE_VFMODULE= true +FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF = true +FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI=false +FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST=true +FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY=true +FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE = true +FLAG_1810_AAI_LOCAL_CACHE = true +FLAG_1902_NEW_VIEW_EDIT=false +FLAG_EXP_USE_DEFAULT_HOST_NAME_VERIFIER = false + +FLAG_SUPPLEMENTARY_FILE = true +FLAG_1902_VNF_GROUPING = true diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js b/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js index 947e6003..077a7840 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/constants/componentConstants.js @@ -25,8 +25,8 @@ appDS2 .constant("COMPONENT", (function() { return { A_LA_CARTE : "a la carte", + CLOUD_REGION_ID : "cloudRegionID", CLOUD_OWNER : "cloudOwner", - CLOUD_REGION_ID : "cloudRegionID", COMPONENT_STATUS : "ComponentStatus", CREATE_COMPONENT : "createComponent", IFRAME_DIALOG : "iframeDialog", @@ -47,6 +47,7 @@ appDS2 MODEL_VERSION_1 : "1", MSO_CREATE_REQ : "createInstance", MSO_DELETE_REQ : "deleteInstance", + MSO_CREATE_CONFIGURATION_REQ : 'createConfiguration', MSO_DELETE_CONFIGURATION_REQ : 'deleteConfiguration', MSO_CHANGE_CONFIG_STATUS_REQ: "changeConfigurationStatus", MSO_CHANGE_PORT_STATUS_REQ: "changePortStatus", @@ -55,6 +56,8 @@ appDS2 MSO_ACTIVATE_ENVIRONMENT: "activateEnvironmentInstance", MSO_ACTIVATE_SERVICE_REQ: "activateServiceInstance", MSO_DEACTIVATE_SERVICE_REQ: "deactivateServiceInstance", + MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ: "activateFabricConfigurationInstance", + MSO_DEACTIVATE_AND_CLOUD_DELETE: "deactivateAndCloudDelete", NAME : "name", NETWORK : "network", CONFIGURATION : "configuration", @@ -126,8 +129,8 @@ appDS2 AAI_GET_VERSION_BY_INVARIANT_ID:"aai_get_version_by_invariant_id/", AAI_GET_PORT_MIRRORING_CONFIGS_DATA : "aai_getPortMirroringConfigsData", AAI_GET_PORT_MIRRORING_SOURCE_PORTS : "aai_getPortMirroringSourcePorts", + AAI_GET_PROVIDER_NETWORKS_ASSOCIATIONS : "aai/standardQuery/vlansByNetworks", SEARCH_SERVICE_INSTANCES:"search_service_instances", - AAI_GET_VNF_DATA_PATH: "aai_get_vnf_data/", AAI_GET_VNF_BY_CUSTOMERID_AND_SERVICETYPE: "get_vnf_data_by_globalid_and_service_type/", AAI_GET_SERVICES_BY_OWNING_ENTITY_ID: 'aai_get_services_by_owning_entity_id', AAI_SUB_VIEWEDIT_PATH : "aai_sub_viewedit", @@ -138,6 +141,7 @@ appDS2 AAI_GET_PNF_INSTANCES_LIST: "aai_get_pnf_instances", AAI_GET_BY_URI: "aai_get_by_uri/", AAI_GET_CONFIGURATION: "aai_get_configuration/", + AAI_GET_HOMING_DATA: "aai_get_homing_by_vfmodule/@vnfInstanceId/@vfModuleId", AAI_GET_TEST_ENVIRONMENTS: "get_operational_environments?operationalEnvironmentType=", GET_CATEGORY_PARAMETERS : "category_parameter", PARAMETER_STANDARDIZATION_FAMILY: "PARAMETER_STANDARDIZATION", @@ -146,7 +150,6 @@ appDS2 CREATE_INSTANCE_PATH : "/models/services/createInstance", AAI_GET_PNF_BY_NAME : "aai_get_pnfs/pnf/", //1710 scheduler contants POST_CREATE_NEW_VNF_CHANGE:"post_create_new_vnf_change", - GET_POLICY:"get_policy", WORKFLOW: "workflow", GET_TIME_SLOTS:"get_time_slots", SUBMIT_VNF_CHANGE_TIMESLOTS:"submit_vnf_change_timeslots", @@ -166,6 +169,8 @@ appDS2 MSO_DELETE_SVC_INSTANCE_PATH : "mso_delete_svc_instance/", MSO_ACTIVATE_INSTANCE: "mso/mso_activate_service_instance/@serviceInstanceId", MSO_DEACTIVATE_INSTANCE: "mso/mso_deactivate_service_instance/@serviceInstanceId", + MSO_ACTIVATE_FABRIC_CONFIGURATION_INSTANCE: "mso/mso_activate_fabric_configuration/@serviceInstanceId", + MSO_DEACTIVATE_AND_CLOUD_DELETE_INSTANCE: "mso/mso_vfmodule_soft_delete/@serviceInstanceId/@vnfInstanceId/@vfModuleInstanceId", MSO_CREATE_REALATIONSHIP : "mso_add_relationship", MSO_REMOVE_RELATIONSHIP: "mso_remove_relationship", SELECTED_SERVICE_SUB_PATH : "#/instances/subdetails?", @@ -236,14 +241,18 @@ appDS2 FEATURE_FLAGS:{ FLAG_ASYNC_INSTANTIATION : "FLAG_ASYNC_INSTANTIATION", - FLAG_VLAN_TAGGING_VIEW_EDIT: "FLAG_VLAN_TAGGING_VIEW_EDIT", FLAG_NETWORK_TO_ASYNC_INSTANTIATION : "FLAG_NETWORK_TO_ASYNC_INSTANTIATION", - FLAG_REGION_ID_FROM_REMOTE : "FLAG_REGION_ID_FROM_REMOTE", FLAG_ADD_MSO_TESTAPI_FIELD : "FLAG_ADD_MSO_TESTAPI_FIELD", FLAG_COLLECTION_RESOURCE_SUPPORT : "FLAG_COLLECTION_RESOURCE_SUPPORT", FLAG_SHOW_ASSIGNMENTS: "FLAG_SHOW_ASSIGNMENTS", FLAG_SHOW_VERIFY_SERVICE: "FLAG_SHOW_VERIFY_SERVICE", - FLAG_PNP_INSTANTIATION: "FLAG_PNP_INSTANTIATION" + FLAG_PNP_INSTANTIATION: "FLAG_PNP_INSTANTIATION", + FLAG_DUPLICATE_VNF : "FLAG_DUPLICATE_VNF", + FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS: "FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS", + FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS: "FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS", + FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST: "FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST", + FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY: "FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY", + FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE: "FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE" } }; diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/constants/fieldConstants.js b/vid-app-common/src/main/webapp/app/vid/scripts/constants/fieldConstants.js index 544a8114..e00ede5e 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/constants/fieldConstants.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/constants/fieldConstants.js @@ -273,7 +273,8 @@ appDS2.factory("FIELD", ["PARAMETER", function (PARAMETER) { AAI_CREATED: "Created", AAI_DELETE: "Deleted", AAI_ENABLED: "Enabled", - AAI_DISABLED: "Disabled" + AAI_DISABLED: "Disabled", + ASSIGNED: "Assigned" }; var STYLE = { @@ -510,6 +511,6 @@ appDS2.factory("FIELD", ["PARAMETER", function (PARAMETER) { PROMPT: PROMPT, STATUS: STATUS, STYLE: STYLE, - ERROR: ERROR, + ERROR: ERROR } }]); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/constants/vidConfiguration.js b/vid-app-common/src/main/webapp/app/vid/scripts/constants/vidConfiguration.js index b2441fbe..05c96ed6 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/constants/vidConfiguration.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/constants/vidConfiguration.js @@ -30,7 +30,7 @@ appDS2.constant("VIDCONFIGURATION", (function() { * UPLOAD_SUPPLEMENTARY_STATUS_CHECK_ENABLED: Determines the Property to Govern Presence of Upload Supplementary File on Volume Group Screen. * Set to false, to disable the check. */ - var UPLOAD_SUPPLEMENTARY_STATUS_CHECK_ENABLED = false; + var UPLOAD_SUPPLEMENTARY_STATUS_CHECK_ENABLED = true; /* * List of valid VNF status combinations */ @@ -91,6 +91,8 @@ appDS2.constant("VIDCONFIGURATION", (function() { */ var MSO_POLLING_INTERVAL_MSECS = 200; + var SERVER_RESPONSE_TIMEOUT_MSECS = 300000; + var SCHEDULER_POLLING_INTERVAL_MSECS = 10000; var SCHEDULER_MAX_POLLS = 10; @@ -113,6 +115,7 @@ appDS2.constant("VIDCONFIGURATION", (function() { ASDC_MODEL_STATUS : ASDC_MODEL_STATUS, MSO_MAX_POLLS : MSO_MAX_POLLS, MSO_POLLING_INTERVAL_MSECS : MSO_POLLING_INTERVAL_MSECS, + SERVER_RESPONSE_TIMEOUT_MSECS : SERVER_RESPONSE_TIMEOUT_MSECS, SCHEDULER_MAX_POLLS : SCHEDULER_MAX_POLLS, SCHEDULER_POLLING_INTERVAL_MSECS : SCHEDULER_POLLING_INTERVAL_MSECS, VNF_STATUS_CHECK_ENABLED : VNF_STATUS_CHECK_ENABLED, diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js index 1b3ab09c..06622cfb 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/InstantiationController.js @@ -27,7 +27,7 @@ appDS2.requires.push('ui.tree'); - appDS2.controller("InstantiationController", function ($scope, $route, $location, $timeout, COMPONENT, VIDCONFIGURATION, FIELD, DataService, PropertyService, UtilityService, VnfService, $http, vidService, AaiService, PnfService, CrService, AsdcService, $q, featureFlags, _, CreationService, $window) { + appDS2.controller("InstantiationController", function ($scope, $route, $location, $timeout, $uibModal, COMPONENT, VIDCONFIGURATION, FIELD, DataService, PropertyService, UtilityService, VnfService, $http, vidService, AaiService, PnfService, CrService, AsdcService, $q, featureFlags, _, CreationService, $window, DeleteResumeService) { $scope.popup = new Object(); $scope.defaultBaseUrl = ""; $scope.responseTimeoutMsec = 60000; @@ -53,27 +53,8 @@ // takes a default value, retrieves the prop value from the file system and sets it var polls = PropertyService.retrieveMsoMaxPolls(); PropertyService.setMsoMaxPolls(polls); + }; - PropertyService.setServerResponseTimeoutMsec(30000); - - /* - * Common parameters that shows an example of how the view edit screen - * is expected to pass some common service instance values to the - * popups. - */ - -// DataService.setSubscriberName("Mobility"); -// DataService.setGlobalCustomerId("CUSTID12345") -// DataService.setServiceType("Mobility Type 1"); -// DataService.setServiceInstanceName("Example Service Instance Name"); -// DataService.setServiceName("Mobility Service 1"); -// DataService.setServiceInstanceId("mmsc-test-service-instance"); -// DataService.setServiceUuid("XXXX-YYYY-ZZZZ"); -// DataService.setUserServiceInstanceName("USER_SERVICE_INSTANCE_NAME"); - - } - - //PropertyService.setMsoBaseUrl("testmso"); $scope.convertModel = function (asdcModel) { if (!asdcModel) return undefined; @@ -305,20 +286,86 @@ DataService.setServiceUuid($scope.service.model.service.uuid); } - $scope.deleteVfModule = function (serviceObject, vfModule, vnf) { + var modalInstance; - console.log("Removing VF-Module " + vfModule.name); + var openMsoModal = function (msoType, requestParams, callbackFunction, configuration) { + modalInstance = $uibModal.open({ + templateUrl: 'app/vid/scripts/modals/mso-commit/mso-commit.html', + controller: "msoCommitModalController", + backdrop: false, + resolve: { + msoType: function () { + return msoType; + }, + requestParams: function () { + requestParams.callbackFunction = callbackFunction; + return requestParams; + }, + configuration: function () { + return configuration; + } + } + }); + }; - populate_popup_vfModule(serviceObject, vfModule, vnf); + var openVfModuleWithHomingDataModal = function(action, vfModule) { + modalInstance = $uibModal.open({ + controller: 'vfModuleActionModalController', + templateUrl: 'app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.html', + backdrop: false, + resolve: { + action: function () { + return action; + }, + vfModule: function() { + return vfModule; + } + } + }); - $scope.$broadcast(COMPONENT.DELETE_RESUME_COMPONENT, { - componentId: COMPONENT.VF_MODULE, - callbackFunction: deleteOrResumeCallback, - dialogMethod: COMPONENT.DELETE + modalInstance.result.then(function (data) { + if (data.msoType && data.requestParams) { + openMsoModal(data.msoType, data.requestParams, deleteOrResumeCallback, null); + } }); + }; - return; + function getLcpCloudRegionTenantList() { + AaiService.getLcpCloudRegionTenantList(DataService + .getGlobalCustomerId(), DataService.getServiceType(), function( + response) { + $scope.lcpAndTenant = response; + $scope.isFeatureFlagCloudOwner = featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST); + $scope.lcpRegionList = _.uniqBy(response, 'cloudRegionId'); + }); + } + $scope.deleteVfModule = function (serviceObject, vfModule, vnf) { + $scope.isSoftDeleteEnabled = true; + + populate_popup_vfModule(serviceObject, vfModule, vnf); + + if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE)) { + + if (DataService.getLoggedInUserId()) { + openVfModuleWithHomingDataModal(COMPONENT.DELETE, vfModule); + } + else { + AaiService.getLoggedInUserID(function (response) { + var userID = response.data; + DataService.setLoggedInUserId(userID); + openVfModuleWithHomingDataModal(COMPONENT.DELETE, vfModule); + }); + } + } + else { + $scope.$broadcast(COMPONENT.DELETE_RESUME_COMPONENT, { + componentId: COMPONENT.VF_MODULE, + callbackFunction: deleteOrResumeCallback, + dialogMethod: COMPONENT.DELETE + }); + } + console.log("Removing VF-Module", vfModule); }; function setCurrentServiceModelInfoFromScope() { @@ -1175,11 +1222,27 @@ setCurrentVNFModelInfo(vnfModel); DataService.setVfModuleInstanceName(vfModule.object[FIELD.ID.VF_MODULE_NAME]); setCurrentServiceModelInfoFromScope(); - $scope.$broadcast(COMPONENT.DELETE_RESUME_COMPONENT, { - componentId: COMPONENT.VF_MODULE, - callbackFunction: deleteOrResumeCallback, - dialogMethod: COMPONENT.RESUME - }); + + if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_SOFT_DELETE_ALACARTE_VF_MODULE)) { + + if (DataService.getLoggedInUserId()) { + openVfModuleWithHomingDataModal(COMPONENT.RESUME, vfModule); + } + else { + AaiService.getLoggedInUserID(function (response) { + var userID = response.data; + DataService.setLoggedInUserId(userID); + openVfModuleWithHomingDataModal(COMPONENT.RESUME, vfModule); + }); + } + } + else { + $scope.$broadcast(COMPONENT.DELETE_RESUME_COMPONENT, { + componentId: COMPONENT.VF_MODULE, + callbackFunction: deleteOrResumeCallback, + dialogMethod: COMPONENT.RESUME + }); + } }; $scope.deleteConfiguration = function (serviceObject, configuration) { diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js index aee4c05f..f0a6ebdf 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js @@ -121,9 +121,6 @@ var polls = PropertyService.retrieveMsoMaxPolls(); PropertyService.setMsoMaxPolls(polls); - - //PropertyService.setMsoBaseUrl("testmso"); - PropertyService.setServerResponseTimeoutMsec(30000); }; $scope.prevPage = function() { @@ -186,14 +183,17 @@ "description": serviceModel.service.description, "category":serviceModel.service.category }); - DataService.setALaCarte (true); + + var shouldTakeTheAsyncInstantiationFlow = AsdcService.shouldTakeTheAsyncInstantiationFlow(serviceModel); + DataService.setShouldIncludeInAsyncInstantiationFlow(shouldTakeTheAsyncInstantiationFlow); + + DataService.setALaCarte (true); DataService.setPnf(!angular.equals(serviceModel.pnfs, {})); $scope.createType = COMPONENT.A_LA_CARTE; var broadcastType = COMPONENT.CREATE_COMPONENT; if (AsdcService.isMacro(serviceModel) || DataService.getE2EService()) { DataService.setALaCarte(false); - if(AsdcService.shouldExcludeMacroFromAsyncInstatiationFlow(serviceModel)){ - DataService.setShouldExcludeMacroFromAsyncInstatiationFlow(true); + if(!shouldTakeTheAsyncInstantiationFlow){ $scope.createType = COMPONENT.MACRO; var convertedAsdcModel = UtilityService.convertModel(serviceModel); @@ -210,7 +210,6 @@ "serviceRole": serviceModel.service.serviceRole, "displayInputs": convertedAsdcModel.completeDisplayInputs }); - } } diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceProxyConfigController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceProxyConfigController.js index 5d17faa9..96939a42 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceProxyConfigController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceProxyConfigController.js @@ -25,8 +25,14 @@ "use strict"; -appDS2.controller("ServiceProxyConfigController", ["COMPONENT", "$log", "FIELD", "PARAMETER", "DataService", "CreationService", "$scope", "$window", "$location", "AaiService", "$uibModal", "UtilityService", "$timeout", - function (COMPONENT, $log, FIELD, PARAMETER, DataService, CreationService, $scope, $window, $location, AaiService, $uibModal, UtilityService, $timeout) { +appDS2.controller( + "ServiceProxyConfigController", ["COMPONENT", "$log", "FIELD", "PARAMETER", "DataService", + "CreationService", "$scope", "$window", "$location", "AaiService", "$uibModal", "UtilityService", "$timeout", + "featureFlags", + function (COMPONENT, $log, FIELD, PARAMETER, DataService, + CreationService, $scope, $window, $location, AaiService, $uibModal, UtilityService, $timeout, + featureFlags + ) { $scope.selectedMetadata = {}; @@ -159,7 +165,7 @@ appDS2.controller("ServiceProxyConfigController", ["COMPONENT", "$log", "FIELD", backdrop: true, resolve: { msoType: function () { - return COMPONENT.MSO_CREATE_REQ; + return COMPONENT.MSO_CREATE_CONFIGURATION_REQ; }, requestParams: function () { return requestParams; @@ -252,6 +258,10 @@ appDS2.controller("ServiceProxyConfigController", ["COMPONENT", "$log", "FIELD", loadCollectorProxies(); }; + $scope.shouldLetSelectingCollectorType = function() { + return $scope.collectorType === 'vnf' || featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_LET_SELECTING_COLLECTOR_TYPE_UNCONDITIONALLY); + }; + function clearSourceProxySelection() { $scope.sourceInstance = undefined; } @@ -274,9 +284,8 @@ appDS2.controller("ServiceProxyConfigController", ["COMPONENT", "$log", "FIELD", function loadProxyInstances(service, serviceType, serviceProxy) { $scope[service.instanceListScopePropertyName] = null; - // $scope.collectorType = $scope.configurationByPolicy ? 'pnf' : 'vnf'; var configNodeTemplateFields = DataService.getPortMirroningConfigFields(); - if (service.name == "collectorInstanceName" && $scope.configurationByPolicy) { + if (service.name === 'collectorInstanceName' && $scope.configurationByPolicy) { var configurationModel = DataService.getModelInfo(COMPONENT.VNF); AaiService.getPnfInstancesList( DataService.getGlobalCustomerId(), @@ -294,7 +303,7 @@ appDS2.controller("ServiceProxyConfigController", ["COMPONENT", "$log", "FIELD", }) .catch(function (error) { $scope[service.noResults] = true; - $log.error("No pnf instance found for " + service.name, error); + $log.error('No pnf instance found for ' + service.name, error); }); } else { AaiService.getVnfInstancesList( diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/VidApp.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/VidApp.js index e30bd385..ce8eb637 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/VidApp.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/VidApp.js @@ -73,7 +73,7 @@ controller: 'ServiceProxyConfigController', templateUrl: 'app/vid/scripts/view-models/serviceProxyConfig.htm' }) - .when('/servicePlanning', { + .when('/servicePlanning/:mode?', { controller: 'iframeController', templateUrl: 'app/vid/scripts/view-models/iframe.htm' }) diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js index 164c71c7..ec4799b1 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/aaiSubscriberController.js @@ -225,8 +225,9 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", $scope.createType = "a la carte"; var broadcastType = "createComponent"; + DataService.setShouldIncludeInAsyncInstantiationFlow(AsdcService.shouldTakeTheAsyncInstantiationFlow(serviceModel)); + if (AsdcService.isMacro(serviceModel)) { - DataService.setShouldExcludeMacroFromAsyncInstatiationFlow(AsdcService.shouldExcludeMacroFromAsyncInstatiationFlow(serviceModel)); DataService.setALaCarte(false); $scope.createType = "Macro"; var convertedAsdcModel = UtilityService.convertModel(serviceModel); @@ -250,7 +251,6 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", "serviceRole": serviceModel.service.serviceRole }); } - ; $scope.$broadcast(broadcastType, { componentId: COMPONENT.SERVICE, @@ -445,9 +445,6 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", var polls = PropertyService.retrieveMsoMaxPolls(); PropertyService.setMsoMaxPolls(polls); - //PropertyService.setMsoBaseUrl("testmso"); - PropertyService.setServerResponseTimeoutMsec(); - /* * Common parameters that would typically be set when the page is * displayed for a specific service instance id. @@ -521,6 +518,8 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", return deferred.promise; } + var serviceNetworkVlans = []; + var vnfNetworksAndVlans = []; $scope.getComponentList = function (event, request) { @@ -542,6 +541,9 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", //$scope.getAsdcModel($location.search().modelUuid); + //make sure view/edit don't open new deploy service popup + DataService.setShouldIncludeInAsyncInstantiationFlow(false); + return getModelVersionIdForServiceInstance({ globalCustomerId: $location.search().subscriberId, serviceInstanceId: $location.search().serviceInstanceId, @@ -550,10 +552,16 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", .then(resolveModelDataIfMissing) .then($scope.prepareScopeWithModel) .then(function () { - + return AaiService.getVlansByNetworksMapping($scope.globalCustomerId, $scope.serviceType, $scope.serviceInstanceId, $scope.service.model.service.uuid); + }) + .then(function (vlanByNetwork) { + serviceNetworkVlans = vlanByNetwork.serviceNetworks ? vlanByNetwork.serviceNetworks : []; + vnfNetworksAndVlans = vlanByNetwork.vnfNetworks ? vlanByNetwork.vnfNetworks : []; + $log.debug('vlanByNetwork', vlanByNetwork); $scope.namedQueryId = VIDCONFIGURATION.COMPONENT_LIST_NAMED_QUERY_ID; $scope.status = FIELD.STATUS.FETCHING_SERVICE_INST_DATA + $scope.serviceInstanceId; + $scope.hasFabricConfigurations = !UtilityService.isObjectEmpty($scope.service.model.fabricConfigurations); return AaiService.runNamedQuery($scope.namedQueryId, $scope.globalCustomerId, $scope.serviceType, $scope.serviceInstanceId, function (response) { //success $scope.handleInitialResponseInventoryItems(response); @@ -567,13 +575,13 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", $scope.errorMsg = FIELD.ERROR.FETCHING_SERVICE_INSTANCE_DATA + response.status; $scope.errorDetails = response.data; } - ) - }) + ); + }); }; $scope.handleServerError = function (response, status) { alert(response.statusText); - } + }; function handleGetRelatedInstanceGroupsResponseForVnf(response, genericVnf) { _.forEach(response.data, function (instanceGroup) { @@ -582,7 +590,7 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", type: instanceGroup.type }; genericVnf.instanceGroups.push(newInstanceGroup); - }) + }); } @@ -618,14 +626,26 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", function navigateToViewEditPage() { - window.location.href = - COMPONENT.INSTANTIATE_ROOT_PATH + disData.globalCustomerId + + window.location.href = AsdcService.shouldTakeTheDrawingBoardViewEdit(vidService.getModel()) ? + drawingBoardViewEditUrl() : oldViewEditUrl(); + } + + function oldViewEditUrl() { + return COMPONENT.INSTANTIATE_ROOT_PATH + disData.globalCustomerId + COMPONENT.SUBSCRIBERNAME_SUB_PATH + disData.subscriberName + COMPONENT.SERVICETYPE_SUB_PATH + disData.serviceType + COMPONENT.SERVICEINSTANCEID_SUB_PATH + disData.serviceInstanceId + COMPONENT.MODELVERSIONID_SUB_PATH + disData.aaiModelVersionId + COMPONENT.IS_PERMITTED_SUB_PATH + disData.isPermitted; } + + function drawingBoardViewEditUrl() { + return 'serviceModels.htm#/servicePlanning/EDIT?' + + 'serviceModelId=' + disData.aaiModelVersionId + + '&subscriberId=' + disData.globalCustomerId + + '&serviceType=' + disData.serviceType + + '&serviceInstanceId=' + disData.serviceInstanceId; + } }; function handleErrorGettingModelVersion(err) { @@ -751,6 +771,16 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", return false; }; + $scope.isActivateFabricConfiguration = function () { + + if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_FABRIC_CONFIGURATION_ASSIGNMENTS) && $scope.hasFabricConfigurations) { + if ($scope.serviceOrchestrationStatus) { + return $scope.serviceOrchestrationStatus.toLowerCase() === 'assigned'; + } + } + return false; + }; + $scope.isResumeShown = function (status) { var vfModuleStatus = status.toLowerCase(); var serviceStatus = $scope.serviceOrchestrationStatus && $scope.serviceOrchestrationStatus.toLowerCase(); @@ -768,12 +798,16 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", $scope.counter = 100; $scope.subscriberName = ""; + + $scope.allConfigurationsAssigned = true; // just look up the subscriber name in A&AI here... AaiService.getSubscriberName($scope.globalCustomerId, function (response) { $scope.subscriberName = response.subscriberName; DataService.setSubscriberName($scope.subscriberName); $scope.serviceOrchestrationStatus = returnMatchingServiceSubscription(response.serviceSubscriptions[FIELD.ID.SERVICE_SUBSCRIPTION], $scope.serviceInstanceId); - + if ($scope.serviceOrchestrationStatus.toLowerCase() !== FIELD.STATUS.ASSIGNED.toLowerCase()) { + $scope.allConfigurationsAssigned = false; + } angular.forEach($scope.inventoryResponseItemList, function (inventoryResponseItem, key) { $scope.inventoryResponseItem = inventoryResponseItem; @@ -820,7 +854,8 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", "nodeStatus": l3NetworkObject[FIELD.ID.ORCHESTRATION_STATUS], "object": l3NetworkObject, "nodes": [], - "subnets": [] + "subnets": [], + "vlans": [] }; if (subInventoryResponseItem[FIELD.ID.INVENTORY_RESPONSE_ITEMS] != null) { //console.log ("subInventoryResponseItem[FIELD.ID.INVENTORY_RESPONSE_ITEMS]="); @@ -842,6 +877,12 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", } }); } + + + var networkObj = _.find(serviceNetworkVlans, { 'networkId': l3Network.nodeId}); + if (networkObj !== undefined && networkObj.vlans !== undefined) { + l3Network["vlans"] = networkObj.vlans; + } $scope.service.instance[FIELD.ID.NETWORKS].push(l3Network); } @@ -860,14 +901,15 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", "vfModules": [], "volumeGroups": [], "instanceGroups": [], - "availableVolumeGroups": [] + "availableVolumeGroups": [], + "networks": [] }; - if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_VLAN_TAGGING_VIEW_EDIT)) { - - //TODO should be changed after integration - genericVnf["instanceGroups"] = [{"name":"a2"}]; + var vnfNetworkObj = _.find(vnfNetworksAndVlans, { 'vnfId': genericVnf.nodeId}); + if (vnfNetworkObj !== undefined && vnfNetworkObj.networks !== undefined) { + genericVnf["networks"] = vnfNetworkObj.networks; } + $scope.service.instance[FIELD.ID.VNFS].push(genericVnf); getRelatedInstanceGroupsByVnfId(genericVnf); @@ -977,18 +1019,25 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", "ports": [], "configData" : null }; + if( !$scope.hasFabricConfigurations ) { portMirroringConfigurationIds.push(configObject[FIELD.ID.CONFIGURATION_ID]); - + $scope.service.instance[FIELD.ID.CONFIGURATIONS].push(config); $scope.allowConfigurationActions = [FIELD.STATUS.AAI_ACTIVE, FIELD.STATUS.AAI_INACTIVE, FIELD.STATUS.AAI_CREATED].indexOf(config.nodeStatus) != -1; - - $scope.service.instance[FIELD.ID.CONFIGURATIONS].push(config); + } else { + if (config.nodeStatus.toLowerCase() !== FIELD.STATUS.ASSIGNED.toLowerCase()) { + $scope.allConfigurationsAssigned = false; + if ($scope.isActivateFabricConfiguration()) { + $scope.errorMsg = "Activate fabric configuration button is not available as some of the configuration objects are not in Assigned status. Check MSO logs for the reasons for this abnormal case."; + } + } + } } }); AaiService.getPortMirroringData(portMirroringConfigurationIds).then(function(result){ angular.forEach($scope.service.instance[FIELD.ID.CONFIGURATIONS], function(config){ - config['configData'] = result.data[config['nodeId']] + config['configData'] = result.data[config['nodeId']]; if (config.configData && config.configData.errorDescription) { $scope.errorMsg = ($scope.errorMsg ? $scope.errorMsg + "\n" : "") + @@ -1019,11 +1068,15 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", } }); - }); - - + var aaiNetworkIds = _.map(serviceNetworkVlans, 'networkId'); + var serviceInstanceNetworkIds = _.map($scope.service.instance[FIELD.ID.NETWORKS], 'nodeId'); + var isContains = aaiNetworkIds.every(function(val) { return serviceInstanceNetworkIds.indexOf(val) >= 0; }); + if (aaiNetworkIds.length && !isContains) { + $log.error("vlansByNetworks contain network that not found in service instance", aaiNetworkIds, serviceInstanceNetworkIds); + } - } + }); + }; @@ -1195,6 +1248,27 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", } }; + + var activateFabricConfigurationInstance = function (msoType) { + var requestParams = { + model: $scope.service.model, + service: $scope.service, + serviceInstanceId: $scope.serviceInstanceId + }; + + if (DataService.getLoggedInUserId()) { + requestParams.userId = DataService.getLoggedInUserId(); + openMsoModal(COMPONENT.MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ, requestParams); + } else { + AaiService.getLoggedInUserID(function (response) { + var userID = response.data; + DataService.setLoggedInUserId(userID); + requestParams.userId = userID; + openMsoModal(COMPONENT.MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ, requestParams); + }); + } + }; + $scope.showAssignmentsSDNC = function () { if ($scope.service && $scope.service.instance) { @@ -1203,6 +1277,10 @@ appDS2.controller("aaiSubscriberController", ["COMPONENT", "FIELD", "PARAMETER", return null; }; + $scope.activateFabricConfigurationMSO = function () { + activateFabricConfigurationInstance(COMPONENT.MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ); + }; + $scope.activateMSOInstance = function () { activateDeactivateServiceInstance(COMPONENT.MSO_ACTIVATE_SERVICE_REQ); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js index e8fa529f..63411708 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/creationDialogController.js @@ -31,7 +31,7 @@ var creationDialogController = function (COMPONENT, FIELD, PARAMETER, $scope, $h var componentId = undefined; $scope.shouldShowOldPopup = function () { - return DataService.getALaCarte() || DataService.getShouldExcludeMacroFromAsyncInstatiationFlow() + return !DataService.getShouldIncludeInAsyncInstantiationFlow(); }; function receiveMessage(event) { diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/msoCommitModalController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/msoCommitModalController.js index 631d0122..ae36ecde 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/msoCommitModalController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/msoCommitModalController.js @@ -155,7 +155,7 @@ var msoCommitModalController = function(COMPONENT, FIELD, $scope, $http, $timeou switch(msoType) { case COMPONENT.MSO_DELETE_CONFIGURATION_REQ : return MsoService.deleteConfiguration(requestParams, configuration); - case COMPONENT.MSO_CREATE_REQ: + case COMPONENT.MSO_CREATE_CONFIGURATION_REQ: return MsoService.createConfigurationInstance(requestParams); case COMPONENT.MSO_CHANGE_CONFIG_STATUS_REQ: return MsoService.toggleConfigurationStatus(requestParams, configuration); @@ -169,6 +169,13 @@ var msoCommitModalController = function(COMPONENT, FIELD, $scope, $http, $timeou return MsoService.activateInstance(requestParams); case COMPONENT.MSO_DEACTIVATE_SERVICE_REQ: return MsoService.deactivateInstance(requestParams); + case COMPONENT.MSO_ACTIVATE_FABRIC_CONFIGURATION_REQ: + return MsoService.activateFabricConfiguration(requestParams); + case COMPONENT.MSO_DEACTIVATE_AND_CLOUD_DELETE: + return MsoService.deactivateAndCloudDelete(requestParams); + case COMPONENT.MSO_CREATE_REQ: + case COMPONENT.MSO_DELETE_REQ: + return MsoService.createAndDeleteInstance(requestParams); } }; diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/statusDialogController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/statusDialogController.js index 0d067ff1..befe7c43 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/statusDialogController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/statusDialogController.js @@ -130,8 +130,6 @@ var statusDialogController = function(COMPONENT, FIELD, $scope, $http, $timeout, var polls = PropertyService.retrieveMsoMaxPolls(); PropertyService.setMsoMaxPolls(polls); - PropertyService.setServerResponseTimeoutMsec(30000); - $scope.isSpinnerVisible = true; diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/subscriberSearch.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/subscriberSearch.js index 029860f8..89768f83 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/subscriberSearch.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/subscriberSearch.js @@ -64,14 +64,12 @@ appDS2.controller("aaiSubscriberSearchController", [ "$scope", "$timeout", "$log var polls = PropertyService.retrieveMsoMaxPolls(); PropertyService.setMsoMaxPolls(polls); - PropertyService.setServerResponseTimeoutMsec(30000); - - // These two properties only added for testing + // These two properties only added for testing properties.msoDefaultBaseUrl = $scope.baseUrl; properties.responseTimeoutMsec = $scope.responseTimeoutMsec; UtilityService.setProperties(properties); - } + }; $scope.autoGetSubs = function() { /* diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/directives/parameterBlockDirective.js b/vid-app-common/src/main/webapp/app/vid/scripts/directives/parameterBlockDirective.js index d36b3823..32c34e9a 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/directives/parameterBlockDirective.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/directives/parameterBlockDirective.js @@ -375,7 +375,8 @@ var parameterBlockDirective = function($log, PARAMETER, UtilityService, $compile } element.replaceWith($compile(element.html(html))(scope)); - element.find("input, select").bind("change", function() { + element.find("input, select").unbind("change.namespace1"); + element.find("input, select").bind("change.namespace1", function() { callback(this, scope); }); } @@ -391,7 +392,8 @@ var parameterBlockDirective = function($log, PARAMETER, UtilityService, $compile } } }); - element.find("input, select").bind("change", function() { + element.find("input, select").unbind("change.namespace2"); + element.find("input, select").bind("change.namespace2", function() { callback(this, scope); }); } diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js index c6c9edf6..9a758cc7 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/new-change-management/new-change-management.controller.js @@ -121,13 +121,19 @@ }; var extractVNFModel = function (csarVNF, sdcService, selectionVNF) { + /** + @param selectionVNF A vnf *instance* selected in "available VNF" drop-down box + @param csarVNF A VNF *MODEL* that has an invariantUuid same as selectionVNF (might be + a different version; i.e. selectionVNF.modelVersionId <> csarVNF.uuid) + @param sdcService The Service *MODEL* which has the related VNF `csarVNF`. + */ var versionCsarData = { vnfInstanceId: "", vnfName: csarVNF.name, modelInfo: { modelType: "vnf", modelInvariantId: csarVNF.invariantUuid, - modelVersionId: selectionVNF.modelVersionId, + modelVersionId: csarVNF.uuid, modelName: csarVNF.name, modelVersion: csarVNF.version, modelCustomizationName: csarVNF.modelCustomizationName, @@ -145,12 +151,10 @@ instanceId: selectionVNF["service-instance-node"]["0"].properties['service-instance-id'], modelInfo: { modelType: "service", - modelInvariantId: selectionVNF["service-instance-node"]["0"].properties['model-invariant-id'], - modelVersionId: selectionVNF.modelVersionId, + modelInvariantId: sdcService.invariantUuid, + modelVersionId: sdcService.uuid, modelName: sdcService.name, - modelVersion: sdcService.version, - modelCustomizationName: selectionVNF["service-instance-node"]["0"].properties['model-customization-name'], //TODO: Missing - modelCustomizationId: selectionVNF["service-instance-node"]["0"].properties['model-customization-id'] + modelVersion: sdcService.version } } } diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.controller.js b/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.controller.js new file mode 100644 index 00000000..00f175e0 --- /dev/null +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.controller.js @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * 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========================================================= + */ + +"use strict"; + +var vfModuleActionModalController = function(COMPONENT, $scope, $uibModal, CreationService, + MsoService, AaiService, DeleteResumeService, DataService, $uibModalInstance, action, vfModule, featureFlags) { + + + var _this = this; + + $scope.action = action; + $scope.vfModuleName = vfModule.name; + $scope.lcpAndTenant = null; + $scope.regionSelection = {lcpRegion: null, legacyRegion: null, tenant: null}; + $scope.lcpRegionList = null; + $scope.isHomingData = false; + $scope.megaRegion = ['AAIAIC25', 'rdm3', 'rdm5a']; + $scope.isSoftDeleteEnabled = vfModule.nodeStatus.toLowerCase() !== 'assigned' && action === COMPONENT.DELETE; + + $scope.isResumeEnabled = action === COMPONENT.RESUME; + if ($scope.isResumeEnabled) { + $scope.action = 'Instantiate'; + } + + initHomingData(); + + function getLcpCloudRegionTenantList() { + AaiService.getLcpCloudRegionTenantList(DataService + .getGlobalCustomerId(), DataService.getServiceType(), function( + response) { + $scope.lcpAndTenant = response; + $scope.isFeatureFlagCloudOwner = featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST); + $scope.lcpRegionList = _.uniqBy(response, 'cloudRegionId'); + }); + } + + function initHomingData() { + AaiService.getHomingData(DataService.getVnfInstanceId(), DataService.getVfModuleInstanceId()) + .then(function (res) { + if (res && res.data) { + $scope.regionSelection = { + lcpRegion: (res.data[COMPONENT.CLOUD_REGION_ID]) ? res.data[COMPONENT.CLOUD_REGION_ID] : null, + legacyRegion: null, + tenant: (res.data[COMPONENT.TENANT_ID]) ? res.data[COMPONENT.TENANT_ID] : null + }; + $scope.isHomingData = $scope.regionSelection.lcpRegion !== null && res.data.tenant !== null; + $scope.isHomingData = $scope.isHomingData && (($scope.megaRegion).indexOf($scope.regionSelection.lcpRegion) === -1); + } + + if (!$scope.isHomingData) { + getLcpCloudRegionTenantList(); + } + }) + .catch(function (error) { + getLcpCloudRegionTenantList(); + }); + }; + + function getLcpRegionId() { + if(_.isEmpty($scope.regionSelection.legacyRegion)) { + return $scope.regionSelection.lcpRegion + } + return $scope.regionSelection.legacyRegion; + } + + $scope.deleteOrResume = function() { + + var regionSelectionList = [({id: "lcpRegion", value: getLcpRegionId()})]; + regionSelectionList.push({id: "tenant", value: $scope.regionSelection.tenant}); + + var requestParams = {}; + var requestDetails; + var msoType; + if ($scope.isResumeEnabled) { + CreationService.initializeComponent(COMPONENT.VF_MODULE); + CreationService.setInventoryInfo(); + + requestDetails = CreationService.getMsoRequestDetails(regionSelectionList); + requestParams.url = CreationService.getMsoUrl(); + msoType = COMPONENT.MSO_CREATE_REQ; + } + else { + DeleteResumeService.initializeComponent(COMPONENT.VF_MODULE); + + requestDetails = DeleteResumeService.getMsoRequestDetails(regionSelectionList); + if(DeleteResumeService.isMacro === true) { + requestDetails.requestParameters.aLaCarte = false; + } + requestParams.url = DeleteResumeService.getMsoUrl(); + msoType = COMPONENT.MSO_DELETE_REQ; + } + + requestParams.requestDetails = requestDetails; + requestParams.userId = DataService.getLoggedInUserId(); + $uibModalInstance.close({requestParams: requestParams, msoType: msoType}); + }; + + $scope.softDelete = function() { + + var requestParams = { + tenantId: $scope.regionSelection.tenant, + lcpCloudRegionId: getLcpRegionId(), + serviceInstanceId: DataService.getServiceInstanceId(), + vnfInstanceId: DataService.getVnfInstanceId(), + vfModuleInstanceId: DataService.getVfModuleInstanceId() + }; + + requestParams.userId = DataService.getLoggedInUserId(); + $uibModalInstance.close({requestParams : requestParams, msoType: COMPONENT.MSO_DEACTIVATE_AND_CLOUD_DELETE}); + }; + + $scope.cancel = function() { + $uibModalInstance.dismiss('cancel'); + }; + +}; + +appDS2.controller("vfModuleActionModalController", [ "COMPONENT", "$scope", "$uibModal", "CreationService", + "MsoService", "AaiService", "DeleteResumeService", "DataService", "$uibModalInstance", "action", "vfModule", "featureFlags", + vfModuleActionModalController ]); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.css b/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.css new file mode 100644 index 00000000..8193bd35 --- /dev/null +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.css @@ -0,0 +1,62 @@ +.modal-dialog * { + font-family: OpenSans-Regular, sans-serif; +} +.modal-dialog { + width: 540px; +} +.modal-body { + width: 95%; + margin: auto; +} +.modal-body label:after{ + color: red; + content: "*"; + padding-left: 5px; +} +.modal-dialog .modal-x { + float: right; + margin-top: 10px; + height: 15px; + cursor:pointer; +} +.modal-body .user-explanation span { + line-height: 25px; +} +.modal-body .user-explanation h4{ + line-height: 30px; +} +.region-section .field{ + margin-top: 15px; + display: flex; +} +.region-section .field label{ + width: 30%; + line-height: 35px; +} +.region-section .field select{ + height: auto; +} +.region-section span{ + margin-top: 20px; +} +.spinner{ + display: none; +} +.region-section.is-loading .spinner{ + display: block; + margin: 20px; + text-align: center; +} +.region-section.is-loading .region-user-selection{ + display: none; +} +.modal-footer button{ + width: 110px; +} +.modal-footer .cancel-btn{ + margin-right: 15px; + margin-left: 15px; +} +.modal-footer .soft-delete-btn { + margin-right: 15px; +} \ No newline at end of file diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.html b/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.html new file mode 100644 index 00000000..bb90ce1f --- /dev/null +++ b/vid-app-common/src/main/webapp/app/vid/scripts/modals/vf-module-homing-data-action/vf-module-homing-data-action.html @@ -0,0 +1,78 @@ + + + + + +

+ +
+ + + +
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/aaiService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/aaiService.js index ceb5a754..6ede6ef3 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/aaiService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/aaiService.js @@ -76,8 +76,8 @@ var AaiService = function ($http, $log, PropertyService, UtilityService, COMPONE }]; } return {displayData: displayData}; - }) - } + }); + }; function getJoinedQueryString(queries) { return queries.filter(function (val) {return val;}).join("&"); @@ -347,27 +347,16 @@ var AaiService = function ($http, $log, PropertyService, UtilityService, COMPONE }); }, - getPortMirroringData : function (ids) { + getPortMirroringData: function (ids) { var defer = $q.defer(); - if(featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_REGION_ID_FROM_REMOTE)){ - var url = COMPONENT.AAI_GET_PORT_MIRRORING_CONFIGS_DATA +'?configurationIds=' + ids.join(','); - $http.get(url).then(function(res){ - defer.resolve(res); - }).catch(function(err) { - $log.error(err); - defer.resolve({}); - }); - }else { - var staticConfigurationData = {}; - angular.forEach(ids, function(id) { - staticConfigurationData[id] = { - "cloudRegionId": "mdt1" - } - }); - defer.resolve({ - "data": staticConfigurationData - }); - } + + var url = COMPONENT.AAI_GET_PORT_MIRRORING_CONFIGS_DATA + '?configurationIds=' + ids.join(','); + $http.get(url).then(function (res) { + defer.resolve(res); + }).catch(function (err) { + $log.error(err); + defer.resolve({}); + }); return defer.promise; @@ -385,6 +374,29 @@ var AaiService = function ($http, $log, PropertyService, UtilityService, COMPONE return defer.promise; }, + getVlansByNetworksMapping : function (globalCustomerId, serviceType, serviceInstanceId, sdcModelUuid) { + var defer = $q.defer(); + if (featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)) { + var url = COMPONENT.AAI_GET_PROVIDER_NETWORKS_ASSOCIATIONS + '?' + + 'globalCustomerId=' + globalCustomerId + + '&serviceType=' + serviceType + + '&serviceInstanceId=' + serviceInstanceId + + '&sdcModelUuid=' + sdcModelUuid + ; + + $http.get(url).then(function(res){ + defer.resolve(res.data); + }).catch(function(err) { + $log.error(err); + defer.resolve({}); + }); + + } else { + defer.resolve({}); + } + return defer.promise; + }, + getSubscriptionServiceTypeList : function(globalCustomerId, successCallbackFunction) { $log @@ -434,8 +446,8 @@ var AaiService = function ($http, $log, PropertyService, UtilityService, COMPONE for (var i = 0; i < aaiLcpCloudRegionTenants.length; i++) { lcpCloudRegionTenants.push({ - "cloudOwner": aaiLcpCloudRegionTenants[i][COMPONENT.CLOUD_OWNER], "cloudRegionId": aaiLcpCloudRegionTenants[i][COMPONENT.CLOUD_REGION_ID], + "cloudOwner": aaiLcpCloudRegionTenants[i][COMPONENT.CLOUD_OWNER], "tenantName": aaiLcpCloudRegionTenants[i][COMPONENT.TENANT_NAME], "tenantId": aaiLcpCloudRegionTenants[i][COMPONENT.TENANT_ID], "isPermitted": aaiLcpCloudRegionTenants[i][COMPONENT.IS_PERMITTED]}); @@ -741,8 +753,25 @@ var AaiService = function ($http, $log, PropertyService, UtilityService, COMPONE "headers: " + header + "config: " + config); }); + }, + + getHomingData: function(vnfInstanceId, vfModuleId) { + var url = COMPONENT.AAI_GET_HOMING_DATA.replace('@vnfInstanceId', vnfInstanceId) + .replace('@vfModuleId', vfModuleId); + + var deferred = $q.defer(); + + $http.get(url) + .success(function (response) { + deferred.resolve({data: response}); + }).error(function (data, status, headers, config) { + deferred.reject({message: data, status: status}); + }); + + return deferred.promise; + } - } + }; }; appDS2.factory("AaiService", ["$http", "$log", "PropertyService", diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/asdcService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/asdcService.js index 6bdc0ae9..52adcc94 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/asdcService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/asdcService.js @@ -21,6 +21,22 @@ "use strict"; var AsdcService = function ($http, $log, PropertyService, UtilityService, VIDCONFIGURATION, COMPONENT, DataService, featureFlags) { + var shouldExcludeMacroFromAsyncInstantiationFlow = function(serviceModel){ + if (!featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_ASYNC_INSTANTIATION)) + return true; + if (DataService.getE2EService()) + return true; + if (!_.isEmpty(serviceModel.pnfs)) + return true; + if (!_.isEmpty(serviceModel.collectionResource)) + return true; + if (!_.isEmpty(serviceModel.networks) && !featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)) + return true; + if(serviceModel.service.instantiationType === "ClientConfig") + return true; + return false; + }; + return { getModel: function (modelId, successCallbackFunction) { $log.debug("AsdcService:getModel: modelId: " + modelId); @@ -34,19 +50,30 @@ var AsdcService = function ($http, $log, PropertyService, UtilityService, VIDCON (UtilityService.runHttpErrorHandler); }, - shouldExcludeMacroFromAsyncInstatiationFlow: function(serviceModel){ - if (!featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_ASYNC_INSTANTIATION)) - return true; - if (DataService.getE2EService()) - return true; - if (!_.isEmpty(serviceModel.pnfs)) - return true; - if (!_.isEmpty(serviceModel.collectionResource)) - return true; - if (!_.isEmpty(serviceModel.networks) && !featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)) - return true; - if(serviceModel.service.instantiationType === "ClientConfig") - return true; + shouldTakeTheDrawingBoardViewEdit: function(serviceModel) { + if (serviceModel.service.vidNotions + && serviceModel.service.vidNotions.viewEditUI + && serviceModel.service.vidNotions.viewEditUI !== 'legacy' + ) return true; + + return false; + }, + + shouldTakeTheAsyncInstantiationFlow: function(serviceModel) { + // First of all, respect serviceModel.service.vidNotions.instantiationUI + if (serviceModel.service.vidNotions + && serviceModel.service.vidNotions.instantiationUI + && serviceModel.service.vidNotions.instantiationUI !== 'legacy' + ) return true; + + // If defined 'legacy' or not defined, other client-side + // logic still apply: + + if (this.isMacro(serviceModel) + && !shouldExcludeMacroFromAsyncInstantiationFlow(serviceModel) + ) return true; + + // otherwise... return false; }, @@ -63,15 +90,15 @@ var AsdcService = function ($http, $log, PropertyService, UtilityService, VIDCON return UtilityService.arrayContains(VIDCONFIGURATION.MACRO_SERVICES, serviceModel.service.invariantUuid); default: console.debug("Unexpected serviceModel.service.instantiationType: " + serviceModel.service.instantiationType); - return true; + return UtilityService.arrayContains(VIDCONFIGURATION.MACRO_SERVICES, serviceModel.service.invariantUuid); } } else { $log.debug("isMscro=false, because serviceModel.service is undefined"); return false; } } - } -} + }; +}; appDS2.factory("AsdcService", ["$http", "$log", "PropertyService", "UtilityService", "VIDCONFIGURATION","COMPONENT", "DataService", "featureFlags", AsdcService]); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/creationService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/creationService.js index b896847d..7d07714d 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/creationService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/creationService.js @@ -1117,8 +1117,14 @@ var CreationService = function($log, AaiService, AsdcService, DataService,VIDCON if (j < parameter.optionList.length) { continue; } + + var optionName = featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST) && cloudRegionTenantList[i].cloudOwner ? + cloudRegionTenantList[i].cloudRegionId + " (" + cloudRegionTenantList[i].cloudOwner.trim().toLowerCase().replace(/^att-/, "").toUpperCase() + ")" : + cloudRegionTenantList[i].cloudRegionId; + parameter.optionList.push({ id : cloudRegionTenantList[i].cloudRegionId, + name: optionName, isPermitted : cloudRegionTenantList[i].isPermitted }); } diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/dataService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/dataService.js index 0e163551..6cc71b41 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/dataService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/dataService.js @@ -270,15 +270,15 @@ var DataService = function($log, DataService) { } return _this.aLaCarte; }, - setShouldExcludeMacroFromAsyncInstatiationFlow: function (val) { - _this.shouldExcludeMacroFromAsyncInstatiationFlow = val; + setShouldIncludeInAsyncInstantiationFlow: function (val) { + _this.shouldIncludeInAsyncInstantiationFlow = val; }, - getShouldExcludeMacroFromAsyncInstatiationFlow: function(){ - if (_this.shouldExcludeMacroFromAsyncInstatiationFlow === undefined) { + getShouldIncludeInAsyncInstantiationFlow: function(){ + if (_this.shouldIncludeInAsyncInstantiationFlow === undefined) { return false; } - return _this.shouldExcludeMacroFromAsyncInstatiationFlow; - }, + return _this.shouldIncludeInAsyncInstantiationFlow; + }, setMacro : function(aval) { _this.macro = aval; }, diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/deleteResumeService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/deleteResumeService.js index 416096a1..a8db5214 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/deleteResumeService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/deleteResumeService.js @@ -422,8 +422,14 @@ var DeleteResumeService = function($log, AaiService, AsdcService, DataService, if (j < parameter.optionList.length) { continue; } + + var optionName = featureFlags.isOn(COMPONENT.FEATURE_FLAGS.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST) && cloudRegionTenantList[i].cloudOwner ? + cloudRegionTenantList[i].cloudRegionId + " (" + cloudRegionTenantList[i].cloudOwner.trim().toLowerCase().replace(/^att-/, "").toUpperCase() + ")" : + cloudRegionTenantList[i].cloudRegionId; + parameter.optionList.push({ id : cloudRegionTenantList[i].cloudRegionId, + name: optionName, isPermitted : cloudRegionTenantList[i].isPermitted }); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/msoService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/msoService.js index 273f8e9e..790f7988 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/msoService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/msoService.js @@ -80,6 +80,30 @@ var MsoService = function($http, $log, $q, PropertyService, AaiService, UtilityS }; + var buildPayloadForActivateFabricConfiguration = function (model, userId) { + var requestDetails = { + "modelInfo": { + "modelType": "service", + "modelInvariantId": model.service.invariantUuid, + "modelVersionId": model.service.uuid, + "modelName": model.service.name, + "modelVersion": model.service.version + }, + "requestInfo": { + "source": "VID", + "requestorId": userId + }, + "requestParameters": { + "aLaCarte": false + } + }; + + $log.debug("Service Activate Fabric Configuration payload", requestDetails); + + return requestDetails; + + }; + var activateInstance = function(requestParams) { var requestDetails = buildPayloadForServiceActivateDeactivate(requestParams.model, requestParams.userId); @@ -94,12 +118,10 @@ var MsoService = function($http, $log, $q, PropertyService, AaiService, UtilityS requestDetails); }; - var sendPostRequest = function(url, requestDetails) { + var sendPostRequestWithBody = function(url, requestBody) { var deferred = $q.defer(); if (url) { - $http.post(url, { - requestDetails: requestDetails - }, { + $http.post(url, requestBody, { timeout: PropertyService.getServerResponseTimeoutMsec() }).success(function (response) { deferred.resolve({data: response}); @@ -111,9 +133,16 @@ var MsoService = function($http, $log, $q, PropertyService, AaiService, UtilityS return deferred.promise; }; + var sendPostRequest = function(url, requestDetails) { + return sendPostRequestWithBody(url, {requestDetails: requestDetails}); + }; + return { createInstance : requestInstanceUpdate, deleteInstance : requestInstanceUpdate, + createAndDeleteInstance: function(requestParams) { + return sendPostRequest("mso/" + requestParams.url, requestParams.requestDetails); + }, getOrchestrationRequest : function(requestId, successCallbackFunction) { $log.debug("MsoService:getOrchestrationRequest: requestId: " + requestId); @@ -312,7 +341,6 @@ var MsoService = function($http, $log, $q, PropertyService, AaiService, UtilityS "modelCustomizationName": requestParams.configurationModelInfo.modelCustomizationName }, "cloudConfiguration": { - // "tenantId": ???? "lcpCloudRegionId": requestParams.portMirroringConfigFields.lcpRegion.value }, "requestInfo": { diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/services/propertyService.js b/vid-app-common/src/main/webapp/app/vid/scripts/services/propertyService.js index ad9bf7df..b576b29e 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/services/propertyService.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/services/propertyService.js @@ -29,7 +29,6 @@ var PropertyService = function($location, $http, VIDCONFIGURATION ) { var DEFAULT_MSO_MAX_POLLING_INTERVAL_MSEC = 60000; var DEFAULT_MSO_MAX_POLLS = 10; var DEFAULT_MSO_BASE_URL = "/" + BASE_PATH + "/mso"; - var DEFAULT_SERVER_RESPONSE_TIMEOUT_MSEC = 60000; var MSO_POLLING_INTERVAL_MSECS = "mso_polling_interval_msecs"; var MSO_MAX_POLLS = "mso_max_polls"; @@ -40,7 +39,6 @@ var PropertyService = function($location, $http, VIDCONFIGURATION ) { _this.msoMaxPollingIntervalMsec = DEFAULT_MSO_MAX_POLLING_INTERVAL_MSEC; _this.msoMaxPolls = DEFAULT_MSO_MAX_POLLS; _this.msoBaseUrl = DEFAULT_MSO_BASE_URL; - _this.serverResponseTimeoutMsec = DEFAULT_SERVER_RESPONSE_TIMEOUT_MSEC; return { @@ -78,12 +76,9 @@ var PropertyService = function($location, $http, VIDCONFIGURATION ) { _this.msoBaseUrl = msoBaseUrl; }, getServerResponseTimeoutMsec : function() { - return _this.serverResponseTimeoutMsec; - }, - setServerResponseTimeoutMsec : function(serverResponseTimeoutMsec) { - _this.serverResponseTimeoutMsec = serverResponseTimeoutMsec; + return VIDCONFIGURATION.SERVER_RESPONSE_TIMEOUT_MSECS; } }; -} +}; appDS2.factory("PropertyService", PropertyService); diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/aaiGetSubs.htm b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/aaiGetSubs.htm index 233bab1c..37289f69 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/aaiGetSubs.htm +++ b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/aaiGetSubs.htm @@ -68,7 +68,8 @@
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html index 65422663..abc5b166 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html +++ b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html @@ -47,7 +47,7 @@ - + {{ changeManagement.vnfNameFromScheduler || changeManagement.instanceReferences.vnfInstanceId || @@ -140,8 +140,8 @@ - - {{ + + {{ changeManagement.vnfNameFromScheduler || changeManagement.instanceReferences.vnfInstanceId || 'No-Instance-Name' diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/instantiate.htm b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/instantiate.htm index 64f71325..d9a29e03 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/instantiate.htm +++ b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/instantiate.htm @@ -34,7 +34,7 @@ {{status}} -
{{errorMsg}} +
{{errorMsg}}
{{errorDetails | json}}
@@ -181,12 +181,17 @@ style="margin-right: 8px;"> Deactivate - Activate - + Activate Fabric Configuration + + Show Assignments @@ -377,6 +382,25 @@
+ +
    +
  1. +
    + NETWORK: {{network.name}} | TYPE: {{network.nodeType}} | ORCH + STATUS: {{network.nodeStatus}} +
    +
      +
    1. +
      + VLAN: {{vlan.vlanIdInner}} | TYPE: VLAN +
      + +
    2. +
    +
  2. +
@@ -400,6 +424,16 @@
+ +
    +
  1. +
    + VLAN: {{vlan.vlanIdInner}} | TYPE: VLAN +
    + +
  2. +
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceModels.htm b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceModels.htm index 44638759..1158f404 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceModels.htm +++ b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceModels.htm @@ -80,9 +80,9 @@ Jump to page: - Results per page: 10 - | 25 - | 50 + Results per page: 10 + | 25 + | 50 diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceProxyConfig.htm b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceProxyConfig.htm index e2261dc1..ec5cbdf4 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceProxyConfig.htm +++ b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/serviceProxyConfig.htm @@ -82,8 +82,8 @@ limitations under the License.
-
Collector Service Type
- diff --git a/vid-app-common/src/main/webapp/app/vid/test/testMso.js b/vid-app-common/src/main/webapp/app/vid/test/testMso.js index f6ebed46..487988dc 100755 --- a/vid-app-common/src/main/webapp/app/vid/test/testMso.js +++ b/vid-app-common/src/main/webapp/app/vid/test/testMso.js @@ -41,7 +41,6 @@ app.controller("testController", [ "$scope", "$timeout", "$cookieStore", "$log", setTestMsoMode($cookieStore.get(TEST_MODE_COOKIE)); PropertyService.setMsoMaxPollingIntervalMsec(1000); PropertyService.setMsoMaxPolls(7); - PropertyService.setServerResponseTimeoutMsec(30000); }; $scope.testMsoModeChanged = function() { diff --git a/vid-app-common/src/main/webapp/app/vid/test/testViewEdit.js b/vid-app-common/src/main/webapp/app/vid/test/testViewEdit.js index 7ddc3dec..50162bfd 100755 --- a/vid-app-common/src/main/webapp/app/vid/test/testViewEdit.js +++ b/vid-app-common/src/main/webapp/app/vid/test/testViewEdit.js @@ -90,7 +90,6 @@ var testViewEditController = function(COMPONENT, DataService, PropertyService, PropertyService.setAsdcBaseUrl("testasdc"); PropertyService.setMsoMaxPollingIntervalMsec(1000); PropertyService.setMsoMaxPolls(7); - PropertyService.setServerResponseTimeoutMsec(30000); }; $scope.testMsoModeChanged = function() { diff --git a/vid-app-common/src/main/webapp/test.jsp b/vid-app-common/src/main/webapp/test.jsp deleted file mode 100755 index aca22939..00000000 --- a/vid-app-common/src/main/webapp/test.jsp +++ /dev/null @@ -1,29 +0,0 @@ - -Test VID Properties related to MSO - - -<%@ page import="org.onap.portalsdk.core.util.SystemProperties" %> -<%@ page import="org.onap.vid.controller.MsoController" %> -<%@ page import="org.onap.vid.mso.rest.Request" %> -<%@ page import="org.onap.vid.mso.rest.RequestDetails" %> -<%@ page import="org.onap.vid.mso.rest.RelatedModel" %> -<%@ page import="org.onap.vid.domain.mso.SubscriberInfo" %> -<%@ page import="org.onap.vid.domain.mso.Response" %> -<%@ page import="org.onap.vid.domain.mso.ModelInfo" %> -<%@ page import="org.onap.vid.domain.mso.RequestInfo" %> -<%@ page import="org.onap.vid.domain.mso.CloudConfiguration" %> -<%@ page import="org.onap.vid.mso.MsoProperties" %> -<%@ page import="java.net.URI" %> -<%@ page import="com.sun.jersey.api.client.ClientResponse" %> - <% - String url = SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL); - String max_polls = SystemProperties.getProperty(MsoProperties.MSO_MAX_POLLS); - String max_polling_interval_msecs = SystemProperties.getProperty(MsoProperties.MSO_POLLING_INTERVAL_MSECS); - %> -

VID properties related to MSO:

-

MSO server URL:

"<%= url %>"

-

MSO max number of polls:

"<%= max_polls %>"

-

MSO polling interval (msecs):

"<%= max_polling_interval_msecs %>"

-

Try Again

- - diff --git a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java b/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java deleted file mode 100644 index d0da08c5..00000000 --- a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/FirstClass.java +++ /dev/null @@ -1,606 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.ecomp.vid.selenium; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - - -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.ie.InternetExplorerDriver; -import org.openqa.selenium.support.ui.Select; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.apache.log4j.Logger; -import org.testng.Assert; -import org.testng.asserts.*; - -/** - * The Class FirstClass. - */ -public class FirstClass { - - /** The login button. */ - WebElement loginButton; - - /** The eg. */ - String eg; - - /** The login. */ - WebElement login; - - /** The pwd. */ - WebElement pwd; - - /** The log. */ - Logger log; - - /** The errormessage. */ - WebElement errormessage; - - - /** The driver. */ - WebDriver driver=new FirefoxDriver(); - - - - /** The config prop. */ - private final Properties configProp = new Properties(); - - - /** - * Instantiates a new first class. - */ - private FirstClass() { - // TODO Auto-generated constructor stub - // - try{ - // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties"); - //FileInputStream input1 = new FileInputStream("objectmap.properties"); - - InputStream input =new FileInputStream("objectconfig.properties"); - System.out.println("Read all properties from file"); - configProp.load(input); - System.out.println("Read all properties from file completed"); - } - catch(IOException e) { - - e.printStackTrace(); - } - } - - - /* - - - @BeforeClass - public void setUp() { - System.out.println("*******************"); - System.out.println("launching IE browser"); - System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe"); - driver = new InternetExplorerDriver(); - driver.findElement(By.className()); - driver.manage().window().maximize(); - - - login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']")); - pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']")); - loginButton = driver.findElement(By.id("loginBtn")); - } - - - */ - /** - * Sets the up. - */ - // TODO Auto-generated method stub - @BeforeClass - public void setUp() - { - - - //WebDriver driver=new FirefoxDriver(); - - log = Logger.getLogger(FirstClass.class.getName()); - - - - // Get url - driver.get(configProp.getProperty("baseURL")); - driver.manage().window().maximize(); - - - login = driver.findElement(By.xpath(configProp.getProperty("login"))); - - pwd = driver.findElement(By.xpath(configProp.getProperty("pwd"))); - loginButton = driver.findElement(By.id(configProp.getProperty("loginButton"))); - } - - - /** - * Empty username password. - */ - @Test(priority=1) - public void emptyUsernamePassword() - { - - - //User Name and Password field is empty - log.info("-----VID-11 TC-8----Username and password empty"); - loginButton.click(); - errormessage=driver.findElement(By.xpath("//*[@id='errorInfo']/span")); - String errmsg= errormessage.getText(); - //System.out.println("Error message is"+errmsg); - //String expected = "Invaild username or password, Please try again"; - - //Assert.assertEquals(errmsg,expected); - - Boolean str = driver.getPageSource().contains("Invalid username or password, Please try again"); - System.out.println(driver.getPageSource().contains("Invalid username or password, Please try again")); - - if(str==true) - { - log.info("Error message validated"); - log.info("VID-11 TC-8 PASSED"); - - }else - log.error("Failed validation"); - - } - - - - /** - * Invalid user name. - */ - @Test(priority=2) - public void invalidUserName() - { - - log.info("-----VID-11 TC-6----Invalid Username and Valid Password"); - - - login.sendKeys("xxx"); - pwd.sendKeys("abc123"); - loginButton.click(); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - String errmsg= errormessage.getText(); - String expected = "Invalid username or password, Please try again"; - Assert.assertEquals(errmsg,expected); - //Boolean str1 = driver.getPageSource().contains("Invalid username or password, Please try again"); - //System.out.print(str1); - - log.info("VID-11 TC-6 PASSED"); - - } - - - /** - * Invalid password. - */ - @Test(priority=3) - public void invalidPassword() - { - log.info("-----VID-11 TC-7----Valid Username and Invalid Password"); - // Valid user name and Invalid password. - login.clear(); - pwd.clear(); - login.sendKeys("testuser"); - pwd.sendKeys("xxx"); - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - - String errmsg= errormessage.getText(); - String expected = "Invalid username or password, Please try again"; - Assert.assertEquals(errmsg,expected); - - //Boolean str2 = driver.getPageSource().contains("Invaild username or password, Please try again"); - //System.out.print(str2); - - log.info("VID-11 TC-7 PASSED"); - } - - - /** - * Login successful. - */ - @Test(priority=4) - public void loginSuccessful() - { - log.info("-----VID-11 TC-1----Valid Username and Valid Password"); - //Login with valid user name and password. - login.clear(); - login.sendKeys("su"); - pwd.clear(); - pwd.sendKeys("fusion"); - - - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - try { - Thread.sleep(6000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances")); - log.info("VID-11 TC-1 PASSED"); - - } - - - /** - * Verify home page elements left pane. - */ - @Test(priority=5) - public void verifyHomePageElementsLeftPane() - - { - - - log.info("VID-10 TC 1 "); - //VID Home - log.info("VID 11 TC-2"); - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[1]/a/span")).isDisplayed(); - //Create New Service Instance - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[2]/a/span")).isDisplayed(); - - //Browse Service Type - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[3]/a/span")).isDisplayed(); - //View Log - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[4]/a/span")).isDisplayed(); - - //Profile - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[5]/a/span")).isDisplayed(); - //Admin - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).isDisplayed(); - //Logout - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a/span")).isDisplayed(); - - //Infrastructure Subscriber Name - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[1]/div/label")).isDisplayed(); - //Infrastructure Subscriber Name Select Drop down - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")).isDisplayed(); - //Infrastructure Service Type - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[1]/div/label")).isDisplayed(); - //Infrastructure Service Type Select Drop down - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")).isDisplayed(); - //Submit button - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).isDisplayed(); - - //Login Snippet Icon - driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).isDisplayed(); - - - //String bodyText = driver.findElement(By.tagName("body")).getText(); - //Assert.assertTrue("Text not found!", bodyText.contains("Search Existing Service Instances")); - //Assert.IsTrue(driver.getPageSource.Contains("Search Existing Service Instances")); - - log.info("VID-12 TC-1"); - Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances")); - Assert.assertTrue(driver.getPageSource().contains("Please search by the Subscriber name or Service Type from below:")); - log.info("VID-12 TC-1 PASSED"); - log.info("VID-10 TC 1 PASSED"); - log.info("VID-11 TC-2 PASSED"); - } - - - /** - * Disabled submit button. - */ - @Test(priority=6) - public void disabledSubmitButton() - { - log.info("VID-12 TC-13"); - //Assert submit button disabled. - Assert.assertFalse(driver.findElement(By.xpath(configProp.getProperty("submitButton"))).isEnabled()); - log.info("VID-12 TC-13 PASSED"); - - } - - /** - * Default list box value. - */ - @Test(priority=7) - public void defaultListBoxValue() - { - log.info("VID-12 TC-2"); - - - //WebElement subscribername =driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")); - - Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))); - Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown")))); - - - WebElement ielement=iSelect.getFirstSelectedOption(); - WebElement oelement=oSelect.getFirstSelectedOption(); - String defaultsubscribername=oelement.getText(); - String defaultservicetype=ielement.getText(); - - Assert.assertEquals(defaultsubscribername,"Select Subscriber Name"); - Assert.assertEquals(defaultservicetype,"Select Service Type"); - - - - - //Verify Select Subscriber Name isDisplayed. - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select/option[1]")).isSelected(); - - //Verify Select Service Type isDisplayed. - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select/option[1]")).isSelected(); - - - log.info("VID-12 TC-2 PASSED"); - - } - - - - /** - * Select subscriber name drop down. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=8) - public void selectSubscriberNameDropDown() throws InterruptedException - { - log.info("------------------VID-10 TC-2,VID-12 TC-11, VID-12 TC-9, VID 12 TC-10,VID-12 TC-6, VID 12 TC-5--------------------"); - - - driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown"))); - - driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown"))); - Thread.sleep(5000); - - //Infrastructure Subscriber Name - Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))); - - List elementCount = oSelect.getOptions(); - log.info("Select Element Count of Service Name"); - System.out.println(elementCount.size()); - - - //Verifying getInfrastructureSubscribersList - log.info("VID-29 TC-1"); - Assert.assertTrue(elementCount.size()>0); - log.info("VID-29 TC-1 PASSED"); - - oSelect.selectByIndex(2); - String selectedOption = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))).getFirstSelectedOption().getText(); - - System.out.println("Service Name selected is " +selectedOption); - log.info("VID-10 TC-2 PASSED"); - - //Submit button is clicked - driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click(); - - - //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed(); - //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:")) - - - //Verify whether the page header is displayed "Global Customer ID" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed(); - Assert.assertTrue(driver.getPageSource().contains("Global Customer ID")); - Assert.assertTrue(driver.getPageSource().contains("Subscriber Name")); - Assert.assertTrue(driver.getPageSource().contains("Service Type")); - Assert.assertTrue(driver.getPageSource().contains("Service Instance ID")); - - log.info("VID-12 TC-5 PASSED"); - log.info("VID-12 TC-11 PASSED"); - - WebElement serviceinstancetable =driver.findElement(By.xpath("//table[@class='tablesorter tablesorter-default ng-isolate-scope']")); - - List rows_table = serviceinstancetable.findElements(By.tagName("tr")); - //To calculate no of rows In table. - int rows_count = rows_table.size(); - - //Loop will execute till the last row of table. - for (int row=0; row Columns_row = rows_table.get(row).findElements(By.tagName("td")); - //To calculate no of columns(cells) In that specific row. - int columns_count = Columns_row.size(); - //System.out.println("Number of cells In Row "+row+" are "+columns_count); - - //Loop will execute till the last cell of that specific row. - for (int column=0; column exx= rows_table.get(1).findElements(By.tagName("td")); - eg=Columns_row.get(2).getText(); - // System.out.println("Cell value of row 1 and column 2 is" +eg); - } - } - - - - - //Verify View/Edit isDisplayed and Click - - driver.findElement(By.xpath("//a[@alt='View/Edit']")).isDisplayed(); - - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/tbody/tr[1]/td[1]/div/a")).click(); - - log.info("User clicked View/Edit"); - - //Verify the Subscriber Name displayed. - String header= driver.findElement(By.xpath("//h1[@class='heading1 ng-binding']")).getText(); - //System.out.println(header); - - - if(header.contains(eg)) - { - System.out.println("Header contains the subscriber name"); - }else - System.out.println("Header does not contain the subscriber name"); - - - - Assert.assertTrue(driver.getPageSource().contains("PerfTest Subscriber00020021")); - log.info("VID-12 TC-6 PASSED"); - - - - driver.navigate().back(); - //Cancel button isDisplayed - driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).isDisplayed(); - log.info("VID-12 TC-9 PASSED"); - - //Cancel button is clicked - driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).click(); - log.info("Cancel button is clicked"); - - //Verifying VID Home page is displayed - Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances")); - log.info("VID-12 TC-10 PASSED"); - - } - - - /** - * Refresh subscriber name. - */ - @Test(priority=9) - public void refreshSubscriberName() - { - log.info("VID-10 TC-4"); - - - driver.findElement(By.xpath(configProp.getProperty("refreshButtonSubscriberName"))).isDisplayed(); - - log.info("VID-10 TC-4 PASSED"); - - - } - - - /** - * Select subscriber type drop down. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=9) - public void selectSubscriberTypeDropDown() throws InterruptedException - { - Thread.sleep(5000); - log.info("------------------VID-10 TC-3, VID-12 TC-12,--------------------"); - //Infrastructure Subscriber Type - Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown")))); - - List ielementCount = iSelect.getOptions(); - log.info("Select Element Count of Service type"); - System.out.println(ielementCount.size()); - iSelect.selectByIndex(1); - - log.info("VID-10 TC-3 PASSED"); - - - //Submit button is clicked - driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click(); - - //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed(); - //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:")) - log.info("Page Header: Selected Subscriber's Service Instance Details"); - - - //Verify whether the page header is displayed "Global Customer ID" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed(); - - //Assert.assertTrue(driver.getPageSource().contains("Global Customer ID")); - log.info("Table is displayed"); - - log.info("VID-12 TC-12 PASSED"); - - } - - - - /** - * Logout under profile. - */ - @Test(priority=10) - public void logoutUnderProfile() - { - - log.info("-----------VID-11 TC-5---------------------"); - //driver.findElement(By.partialLinkText("Click here to login")).click(); - //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - - driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).click(); - driver.findElement(By.xpath(".//*[@id='reg-logout-div']/a")).click(); - //Validate that the user has logged out of VID. Displays "Portal" - Assert.assertTrue(driver.getPageSource().contains("Portal")); - - log.info("VID-11 TC-5 PASSED"); - - } - - - - /** - * Tear down. - */ - @AfterClass - public void tearDown() - { - driver.close(); - - } - - - - } - - - - diff --git a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java b/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java deleted file mode 100644 index fdd5ea38..00000000 --- a/vid-app-common/src/test/java/org/onap/ecomp/vid/selenium/LogOutLeftPane.java +++ /dev/null @@ -1,242 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.ecomp.vid.selenium; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.apache.log4j.Logger; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.support.ui.Select; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -/** - * The Class LogOutLeftPane. - */ -@Test(enabled=false) -public class LogOutLeftPane { - - /** The login button. */ - WebElement loginButton; - - /** The login. */ - WebElement login; - - /** The pwd. */ - WebElement pwd; - - /** The log. */ - Logger log; - - /** The errormessage. */ - WebElement errormessage; - - /** The driver. */ - WebDriver driver=new FirefoxDriver(); - - - /** The config prop. */ - private final Properties configProp = new Properties(); - - - /** - * Instantiates a new log out left pane. - */ - private LogOutLeftPane() { - // TODO Auto-generated constructor stub - // - try{ - // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties"); - //FileInputStream input1 = new FileInputStream("objectmap.properties"); - - InputStream input =new FileInputStream("objectconfig.properties"); - System.out.println("Read all properties from file"); - configProp.load(input); - System.out.println("Read all properties from file completed"); - } - catch(IOException e) { - - e.printStackTrace(); - } - } - - - - - /** - * Do before test. - */ - // TODO Auto-generated method stub - @BeforeTest - public void doBeforeTest() - { - //WebDriver driver=new FirefoxDriver(); - - log = Logger.getLogger(LogOutLeftPane.class.getName()); - - - - // Get url - driver.get("http://vid.onap.org:9080/vid/login_external.htm"); - driver.manage().window().maximize(); - - - login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']")); - pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']")); - loginButton = driver.findElement(By.id("loginBtn")); - } - - - /** - * Expand collapse panel. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=1) - public void expandCollapsePanel() throws InterruptedException - { - - - - login.clear(); - login.sendKeys("su"); - pwd.clear(); - pwd.sendKeys("fusion"); - //driver.findElement(By.partialLinkText("Click here to login")).click(); - //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - - log.info("Clicking Profile link from left pane"); - Thread.sleep(3000); - System.out.println("properties file details --->"+configProp.getProperty("profilelink")); - driver.findElement(By.xpath(configProp.getProperty("profilelink"))).click(); - Thread.sleep(3000); - - //Verify whether the sub panel is displayed - //To verify the following :Search import from webphone and Self - driver.findElement(By.xpath(".//*[@id='panel4']")).isDisplayed(); - log.info("Expand and collapse passed for Profile link"); - - //For Admin - //Verify expand and collapse working for ADMIN - log.info("Clicking Admin link from left pane"); - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).click(); - //To verify the following: Roles, Roles Functions, Usages - driver.findElement(By.xpath(".//*[@id='panel5']")).isDisplayed(); - - - log.info("Expand and collapse passed for ADMIN link"); - - log.info("VID-11 TC-3 PASSED"); - - } - - - /** - * Drop down list. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=2) - public void dropDownList() throws InterruptedException - { - //VID-12 TC-3 - log.info("VID-12 TC-3"); - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")); - - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")); - Thread.sleep(5000); - - //Infrastructure Subscriber Name - Select oSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"))); - Select iSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select"))); - - List elementCount = oSelect.getOptions(); - log.info("Subscriber Name Drop Down"); - System.out.println(elementCount.size()); - oSelect.selectByIndex(1); - log.info("Subscriber name selected"); - //String selectedOption = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"))).getFirstSelectedOption().getText(); - - - List count = iSelect.getOptions(); - log.info("Subscriber type drop down"); - System.out.println(count.size()); - oSelect.selectByIndex(1); - log.info("Subscriber type selected"); - - - - //Submit button is clicked - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).click(); - - - //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed(); - log.info("VID-12 TC-3 PASSED"); - } - - - - - /** - * Logout left pane. - */ - @Test(priority=3) - public void logoutLeftPane() - { - //To Verify if the logout link redirects to Login page when clicked. - - - /*log.info("----------------VID-11 TC-4----------------"); - login.clear(); - login.sendKeys("testuser"); - pwd.clear(); - pwd.sendKeys("abc123"); - //driver.findElement(By.partialLinkText("Click here to login")).click(); - //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);*/ - log.info("----------------VID-11 TC-4----------------"); - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a")).click(); - //Validate that the user has logged out of VID. Displays "Portal" - Assert.assertTrue(driver.getPageSource().contains("Portal")); - - log.info("VID 11 TC-4 PASSED"); - - driver.close(); - - } - -} diff --git a/vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java b/vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java deleted file mode 100644 index 1d61340e..00000000 --- a/vid-app-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java +++ /dev/null @@ -1,177 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.fusion.core; - -import java.io.IOException; - -import org.junit.Before; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.testng.annotations.Test; -import org.onap.portalsdk.core.conf.AppConfig; -import org.onap.portalsdk.core.objectcache.AbstractCacheManager; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.portalsdk.core.util.CacheManager; - -/** - * - * - * - * In order to write a unit test, - * 1. inherit this class - See SanityTest.java - * 2. place the "war" folder on your test class's classpath - * 3. run the test with the following VM argument; This is important because when starting the application from Container, the System Properties file (SystemProperties.java) can have the direct path - * but, when running from the Mock Junit container, the path should be prefixed with "classpath" to enable the mock container to search for the file in the classpath - * -Dcontainer.classpath="classpath:" - * - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = {MockAppConfig.class}) -@ActiveProfiles(value="test") -@Test(enabled=false) -public class MockApplicationContextTestSuite { - - /** The wac. */ - @Autowired - public WebApplicationContext wac; - - /** The mock mvc. */ - private MockMvc mockMvc; - - /** - * Setup. - */ - @Before - public void setup() { - if(mockMvc == null) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - - } - } - - /** - * Gets the bean. - * - * @param name the name - * @return the bean - */ - public Object getBean(String name) { - return this.wac.getBean(name); - } - - - /** - * Gets the mock mvc. - * - * @return the mock mvc - */ - public MockMvc getMockMvc() { - return mockMvc; - } - - /** - * Sets the mock mvc. - * - * @param mockMvc the new mock mvc - */ - public void setMockMvc(MockMvc mockMvc) { - this.mockMvc = mockMvc; - } - - /** - * Gets the web application context. - * - * @return the web application context - */ - public WebApplicationContext getWebApplicationContext() { - return wac; - } - - - - -} - - - @Configuration - @ComponentScan(basePackages = "org.onap", - excludeFilters = { - // the following source configurations should not be scanned; instead of using Exclusion filter, we can use the @Profile annotation to exclude them - // see AppConfig class - //@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalsdk.core.*AppConfig*")//, - //@ComponentScan.Filter(type = FilterType.REGEX, pattern = org.onap.*.*AppConfig*") - } - ) - @Profile("test") - class MockAppConfig extends AppConfig { - - @Bean - public SystemProperties systemProperties(){ - return new MockSystemProperties(); - } - - @Bean - public AbstractCacheManager cacheManager() { - return new CacheManager() { - - public void configure() throws IOException { - - } - }; - } - - protected String[] tileDefinitions() { - return new String[] {"classpath:/WEB-INF/fusion/defs/definitions.xml", "classpath:/WEB-INF/defs/definitions.xml"}; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - //registry.addInterceptor(new SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); - //registry.addInterceptor(resourceInterceptor()); - } - - public static class MockSystemProperties extends SystemProperties { - - public MockSystemProperties() { - } - - } - - } - - - - diff --git a/vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java b/vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java deleted file mode 100644 index 7a4c5601..00000000 --- a/vid-app-common/src/test/java/org/onap/fusionapp/controller/NetMapTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.fusionapp.controller; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -import org.onap.fusion.core.MockApplicationContextTestSuite; - -/** - * The Class NetMapTest. - */ - -public class NetMapTest extends MockApplicationContextTestSuite { - - /** - * Test get net map. - * - * @throws Exception the exception - */ -// @Test - public void testGetNetMap() throws Exception { - ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/net_map")); - //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass()); - Assert.assertEquals("net_map_int",ra.andReturn().getModelAndView().getModel().get("frame_int")); - } - - -} diff --git a/vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java b/vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java deleted file mode 100644 index c486e7b0..00000000 --- a/vid-app-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.fusionapp.service; - -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import org.onap.fusion.core.MockApplicationContextTestSuite; -import org.onap.portalsdk.core.domain.Profile; -import org.onap.portalsdk.core.domain.User; -import org.onap.portalsdk.core.service.ProfileService; -import org.onap.portalsdk.core.service.UserProfileService; - - -/** - * The Class ProfileServiceTest. - */ - -public class ProfileServiceTest extends MockApplicationContextTestSuite { - - /** The service. */ - @Autowired - ProfileService service; - - /** The user profile service. */ - @Autowired - UserProfileService userProfileService; - - /** - * Test find all. - */ - //@Test - public void testFindAll() { - try { - List profiles = service.findAll(); - Assert.assertTrue(profiles.size() > 0); - - } - catch (Exception e) { - // TODO: handle exception - } - } - - /** - * Test find all active. - */ -// @Test - public void testFindAllActive() { - - List users = userProfileService.findAllActive(); - List activeUsers = userProfileService.findAllActive(); - Assert.assertTrue(users.size() - activeUsers.size() >= 0); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java b/vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java deleted file mode 100644 index ca4ac1b8..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/RelatedToTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.onap.vid; - -import java.util.Map; - -import org.junit.Test; -import org.onap.vid.RelatedTo; - - -public class RelatedToTest { - - private RelatedTo createTestSubject() { - return new RelatedTo(); - } - - - @Test - public void testGetAdditionalProperties() throws Exception { - RelatedTo testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAdditionalProperties(); - } - - - @Test - public void testSetAdditionalProperty() throws Exception { - RelatedTo testSubject; - String name = ""; - Object value = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAdditionalProperty(name, value); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java index 201ec098..2656532f 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java @@ -1,26 +1,6 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.aai; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; @@ -28,18 +8,15 @@ import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.commons.lang3.tuple.Pair; +import org.apache.http.HttpStatus; import org.mockito.Mockito; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelatedToProperty; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; -import org.onap.vid.aai.model.AaiNodeQueryResponse; -import org.onap.vid.aai.model.PortDetailsTranslator; -import org.onap.vid.aai.model.ResourceType; -import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.vid.aai.util.HttpsAuthClient; -import org.onap.vid.aai.util.ServletRequestHelper; -import org.onap.vid.aai.util.SystemPropertyHelper; -import org.onap.vid.controllers.LocalWebConfig; +import org.onap.vid.aai.model.*; +import org.onap.vid.aai.util.*; +import org.onap.vid.controller.LocalWebConfig; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.Subscriber; import org.onap.vid.model.SubscriberList; @@ -47,6 +24,7 @@ import org.onap.vid.model.probes.ExternalComponentStatus; import org.onap.vid.model.probes.HttpRequestMetadata; import org.onap.vid.model.probes.StatusMetadata; import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.Unchecked; import org.springframework.http.HttpMethod; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; @@ -65,42 +43,53 @@ import javax.ws.rs.client.Client; import javax.ws.rs.core.Response; import java.io.FileNotFoundException; import java.io.IOException; +import java.net.URI; import java.security.cert.CertificateException; import java.util.ArrayList; +import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; -import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.*; +import static org.hamcrest.Matchers.*; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.*; +import static org.onap.vid.utils.Unchecked.toURI; import static org.testng.Assert.*; @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) @WebAppConfiguration public class AaiClientTest { + private final String NO_LCP_REGION_AND_TENANTS_MSG = "A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'"; private AaiClient aaiClientMock; private ServletContext servletContext; @BeforeMethod - public void initMocks() { + public void initMocks(){ aaiClientMock = mock(AaiClient.class); aaiClientMock.logger = mock(EELFLoggerDelegate.class); + aaiClientMock.objectMapper = new ObjectMapper(); servletContext = mock(ServletContext.class); when(servletContext.getRealPath(any(String.class))).thenReturn(""); - when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(null); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null); + when(aaiClientMock.doAaiGet(any(URI.class), anyBoolean(), anyBoolean())).thenReturn(null); } @DataProvider public static Object[][] logicalLinkData() { - return new Object[][]{ + return new Object[][] { {"", "network/logical-links/logical-link/"}, {"link", "network/logical-links/logical-link/link"} }; @@ -111,26 +100,21 @@ public class AaiClientTest { when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod(); aaiClientMock.getLogicalLink(link); - Mockito.verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)), any(Boolean.class)); + verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class)); } @DataProvider public static Object[][] subscribersResults() { - return new Object[][]{ - {new SubscriberList(new ArrayList() {{ - add(new Subscriber()); - add(new Subscriber()); - }}), true}, - {new SubscriberList(new ArrayList() {{ - add(new Subscriber()); - }}), true}, + return new Object[][] { + {new SubscriberList(new ArrayList() {{ add(new Subscriber()); add(new Subscriber()); }}), true}, + {new SubscriberList(new ArrayList() {{ add(new Subscriber()); }}), true}, {new SubscriberList(new ArrayList()), false} }; } @Test(dataProvider = "subscribersResults") - public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable) { - ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, new HttpRequestMetadata( + public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){ + ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata( HttpMethod.GET, 200, "url", @@ -143,9 +127,79 @@ public class AaiClientTest { HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200), "rawData")); Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod(); - ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); - assertThat(statusDataReflected(result), is(statusDataReflected(expectedStatus))); - assertThat(requestMetadataReflected(result.getMetadata()), is(requestMetadataReflected(expectedStatus.getMetadata()))); + ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); + assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus))); + assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata()))); + } + + @Test(expectedExceptions = Exception.class) + public void typedAaiGet_aaiRestInterfaceRestGetReturnsError_exceptionIsThrown() { + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR, "entity"); + mockForGetRequest(aaiRestInterface, responseWithRequestInfo); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + try { + + aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class); + + } catch (Exception e) { + assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class)); + ExceptionWithRequestInfo e2 = ((ExceptionWithRequestInfo) e); + assertThat(e2.getHttpCode(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + assertThat(e2.getRawData(), is("entity")); + assertThat(e2.getHttpMethod(), is(HttpMethod.GET)); + assertThat(e2.getRequestedUrl(), is("/my/mocked/url")); + + throw e; + } + } + + @Test(expectedExceptions = Exception.class) + public void typedAaiGet_aaiRestInterfaceRestGetReturnsInparsableResponse_exceptionIsThrown() { + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "entity"); + mockForGetRequest(aaiRestInterface, responseWithRequestInfo); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + try { + + aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class); + + } catch (Exception e) { + assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class)); + assertThat(e.getCause(), + hasProperty("cause", is(instanceOf(com.fasterxml.jackson.core.JsonParseException.class))) + ); + throw e; + } + } + + @Test + public void typedAaiGet_aaiRestInterfaceRestGetReturns_objectIsFine() { + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, + "{ \"property-key\": \"foo\", \"property-value\": \"bar\" }"); + mockForGetRequest(aaiRestInterface, responseWithRequestInfo); + + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class); + + assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo")); + assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar")); + } + + private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) { + return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET); + } + + private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) { + final Response mockResponse = mock(Response.class); + when(mockResponse.getStatus()).thenReturn(status.getStatusCode()); + when(mockResponse.getStatusInfo()).thenReturn(status); + when(mockResponse.readEntity(String.class)).thenReturn(entity); + return new ResponseWithRequestInfo(mockResponse, requestUrl, method); } //serialize fields except of fields we cannot know ahead of time @@ -164,12 +218,12 @@ public class AaiClientTest { @DataProvider public static Object[][] rawData() { return new Object[][]{ - {"errorMessage",}, {""}, {null} + {"errorMessage", }, {""}, {null} }; } @Test(dataProvider = "rawData") - public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData) { + public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){ Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn( new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null, rawData)); @@ -180,7 +234,7 @@ public class AaiClientTest { @DataProvider public static Object[][] exceptions() { - return new Object[][]{ + return new Object[][] { {"NullPointerException", "errorMessage", new ExceptionWithRequestInfo(HttpMethod.GET, "url", "errorMessage", null, new NullPointerException())}, @@ -193,7 +247,7 @@ public class AaiClientTest { } @Test(dataProvider = "exceptions") - public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception) { + public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){ Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception); ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable(); if (exception instanceof ExceptionWithRequestInfo) { @@ -205,7 +259,7 @@ public class AaiClientTest { private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() { Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod(); - ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); + ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); assertFalse(result.isAvailable()); return result; } @@ -226,56 +280,55 @@ public class AaiClientTest { assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}"); } - @Test + @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG) public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() { - when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); + when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod(); Response generalEmptyResponse = mock(Response.class); - when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(generalEmptyResponse); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse); - AaiResponse response = aaiClientMock.getTenants("subscriberId", "serviceType"); - - assertEquals(response.getErrorMessage(), "{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'\"}"); + aaiClientMock.getTenantsNonCached("subscriberId", "serviceType"); + } + @Test + public void whenCacheThrowException_thenGetTenantReturnAaiResponse() { + CacheProvider mockCacheProvider = mock(CacheProvider.class); + CacheProvider.Cache mockCache = mock(CacheProvider.Cache.class); + AaiClient aaiClientUnderTest = new AaiClient(null, null, mockCacheProvider); + + when(mockCacheProvider.aaiClientCacheFor(any(), any())).thenReturn(mockCache); + when(mockCache.get(any())).thenThrow(new AaiClient.ParsingGetTenantsResponseFailure(NO_LCP_REGION_AND_TENANTS_MSG)); + AaiResponse aaiResponse = aaiClientUnderTest.getTenants("subscriberId", "serviceType"); + assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, aaiResponse.getHttpCode()); + assertEquals("{\"statusText\":\""+NO_LCP_REGION_AND_TENANTS_MSG+"\"}", aaiResponse.getErrorMessage()); } @Test public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() { - when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); + when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod(); Response generalEmptyResponse = mock(Response.class); when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw); when(generalEmptyResponse.getStatus()).thenReturn(200); - when(generalEmptyResponse.getStatusInfo()).thenReturn(new Response.StatusType() { - @Override - public int getStatusCode() { - return 200; - } + when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK); - @Override - public Response.Status.Family getFamily() { - return Response.Status.Family.SUCCESSFUL; - } - @Override - public String getReasonPhrase() { - return null; - } - }); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse); + AaiResponse response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType"); - when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(generalEmptyResponse); + GetTenantsResponse[] tenants = response.getT(); - AaiResponse response = aaiClientMock.getTenants("subscriberId", "serviceType"); + Assert.assertTrue(response.t.length> 0); - Assert.assertTrue(response.t.length > 0); + Assert.assertEquals(tenants[0].cloudOwner,"att-aic-cloud-owner"); } - final String tenantResponseRaw = "" + + final String tenantResponseRaw ="" + "{" + "\"service-type\": \"VIRTUAL USP\"," + "\"resource-version\": \"1494001841964\"," + @@ -285,7 +338,7 @@ public class AaiClientTest { "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," + "\"relationship-data\": [{" + "\"relationship-key\": \"cloud-region.cloud-owner\"," + - "\"relationship-value\": \"att-aic\"" + + "\"relationship-value\": \"att-aic-cloud-owner\"" + "}," + "{" + "\"relationship-key\": \"cloud-region.cloud-region-id\"," + @@ -304,51 +357,179 @@ public class AaiClientTest { "}" + "}"; + final String vfModuleHomingResponseRaw ="{" + + " \"vf-module-id\": \"ed02354a-3217-45ce-a1cd-e0b69b7a8cea\"," + + " \"vf-module-name\": \"apndns_az_02_module_1\"," + + " \"heat-stack-id\": \"apndns_az_02_module_1/97a319f3-b095-4fff-befa-c657508ecaf8\"," + + " \"orchestration-status\": \"active\"," + + " \"is-base-vf-module\": false," + + " \"resource-version\": \"1530559380383\"," + + " \"model-invariant-id\": \"74450b48-0aa0-4743-8314-9163e92b7862\"," + + " \"model-version-id\": \"6bc01a2b-bc48-4991-b9fe-e22c2215d801\"," + + " \"model-customization-id\": \"74f638c2-0368-4212-8f73-e961005af17c\"," + + " \"module-index\": 0," + + " \"relationship-list\": {" + + " \"relationship\": [" + + " {" + + " \"related-to\": \"l3-network\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/335e62be-73a3-41e8-930b-1a677bcafea5\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"l3-network.network-id\"," + + " \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" + + " }" + + " ]," + + " \"related-to-property\": [" + + " {" + + " \"property-key\": \"l3-network.network-name\"," + + " \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" + + " }" + + " ]" + + " }," + + " {" + + " \"related-to\": \"l3-network\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"l3-network.network-id\"," + + " \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" + + " }" + + " ]," + + " \"related-to-property\": [" + + " {" + + " \"property-key\": \"l3-network.network-name\"," + + " \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" + + " }" + + " ]" + + " }," + + " {" + + " \"related-to\": \"volume-group\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"cloud-region.cloud-owner\"," + + " \"relationship-value\": \"att-aic\"" + + " }," + + " {" + + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + + " \"relationship-value\": \"rdm5b\"" + + " }," + + " {" + + " \"relationship-key\": \"volume-group.volume-group-id\"," + + " \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" + + " }" + + " ]" + + " }," + + " {" + + " \"related-to\": \"vserver\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"cloud-region.cloud-owner\"," + + " \"relationship-value\": \"att-aic\"" + + " }," + + " {" + + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + + " \"relationship-value\": \"rdm5b\"" + + " }," + + " {" + + " \"relationship-key\": \"tenant.tenant-id\"," + + " \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" + + " }," + + " {" + + " \"relationship-key\": \"vserver.vserver-id\"," + + " \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" + + " }" + + " ]," + + " \"related-to-property\": [" + + " {" + + " \"property-key\": \"vserver.vserver-name\"," + + " \"property-value\": \"zrdm5bfapn01dns002\"" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + "}"; + @Test + public void get_homingDataForVfModule() { + when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod(); + + Response homingResponse = mock(Response.class); + + when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw); + when(homingResponse.getStatus()).thenReturn(200); + when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK); + + + when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse); + + GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId"); + + Assert.assertEquals(tenant.cloudOwner,"att-aic"); + Assert.assertEquals(tenant.cloudRegionID,"rdm5b"); + Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91"); + + } + @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "A&AI has no homing data associated to vfModule 'vfModuleId' of vnf 'vnfInstanceId'") + public void getVfMoudule_Homing_Arguments_Are_Valid_But_Not_Exists() { + when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod(); + + Response generalEmptyResponse = mock(Response.class); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse); + + aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId"); + } + @DataProvider - public static Object[][] resourceTypesProvider() { - return new Object[][]{ - {"service-instance", ResourceType.SERVICE_INSTANCE}, - {"generic-vnf", ResourceType.GENERIC_VNF}, - {"vf-module", ResourceType.VF_MODULE} + public static Object[][] invalidDataId() { + return new String[][] { + {""}, + {null} }; } - @Test(dataProvider = "resourceTypesProvider") - public void aaiNodeQueryResponseDeserializationTest(String resourceType, ResourceType expectedResourceType) throws IOException { - String link = "/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/Nimbus/service-instances/service-instance/7131d483-b450-406f-8e30-0c650645fc67"; - String json = - "{\"result-data\": [{" + - "\"resource-type\": \"" + resourceType + "\"," + - "\"resource-link\": \"" + link + "\"" + - "}]}"; - - AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class); - assertThat(nodeQueryResponse.resultData.get(0).resourceLink, equalTo(link)); - assertThat(nodeQueryResponse.resultData.get(0).resourceType, is(expectedResourceType)); + @Test(dataProvider = "invalidDataId", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.") + public void getVfMoudule_Homing_Arguments_Are_Empty_Or_Null(String data) { + when(aaiClientMock.getHomingDataByVfModule(any(), any())).thenCallRealMethod(); + aaiClientMock.getHomingDataByVfModule(data, data); } - @Test - public void aaiNodeQueryEmptyResponseDeserializationTest() throws IOException { - String json = "{}"; - AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class); - assertNull(nodeQueryResponse.resultData); + @DataProvider + public static Object[][] resourceTypesProvider() { + return new Object[][] { + {"service-instance", ResourceType.SERVICE_INSTANCE}, + {"generic-vnf", ResourceType.GENERIC_VNF}, + {"vf-module", ResourceType.VF_MODULE} + }; } @DataProvider public static Object[][] nameAndResourceTypeProvider() { - return new Object[][]{ - {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:SRIOV_SVC"}, - {"b1707vidnf", ResourceType.GENERIC_VNF, "search/nodes-query?search-node-type=generic-vnf&filter=vnf-name:EQUALS:b1707vidnf"}, - {"connectivity_test", ResourceType.VF_MODULE, "search/nodes-query?search-node-type=vf-module&filter=vf-module-name:EQUALS:connectivity_test"}, - {"MjVg1234", ResourceType.VOLUME_GROUP, "search/nodes-query?search-node-type=volume-group&filter=volume-group-name:EQUALS:MjVg1234"} + return new Object[][] { + {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "nodes/service-instances?service-instance-name=SRIOV_SVC"}, + {"b1707vidnf", ResourceType.GENERIC_VNF, "nodes/generic-vnfs?vnf-name=b1707vidnf"}, + {"connectivity_test", ResourceType.VF_MODULE, "nodes/vf-modules?vf-module-name=connectivity_test"}, + {"ByronPace", ResourceType.INSTANCE_GROUP, "nodes/instance-groups?instance-group-name=ByronPace"}, + {"MjVg1234", ResourceType.VOLUME_GROUP, "nodes/volume-groups?volume-group-name=MjVg1234"} }; } @Test(dataProvider = "nameAndResourceTypeProvider") public void whenSearchNodeTypeByName_callRightAaiPath(String name, ResourceType type, String expectedUrl) { - when(aaiClientMock.searchNodeTypeByName(any(String.class), any(ResourceType.class))).thenCallRealMethod(); - aaiClientMock.searchNodeTypeByName(name, type); - Mockito.verify(aaiClientMock).doAaiGet(eq(expectedUrl), eq(false)); + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "{}"); + + when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + + AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + aaiClient.isNodeTypeExistsByName(name, type); } @DataProvider @@ -381,20 +562,20 @@ public class AaiClientTest { // Exception out of javax's Client Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> { - when(javaxClientMock.target(anyString())).thenThrow( + when(javaxClientMock.target(nullable(String.class))).thenThrow( new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired")) ); }), Pair.of(SunCertPathBuilderException.class, (httpsAuthClientMock, javaxClientMock) -> { SunCertPathBuilderException e0 = new SunCertPathBuilderException("unable to find valid certification path to requested target"); - when(javaxClientMock.target(anyString())).thenThrow( + when(javaxClientMock.target(nullable(String.class))).thenThrow( new ProcessingException(new ValidatorException("PKIX path building failed: " + e0.toString(), e0)) ); }), Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) -> - when(javaxClientMock.target(anyString())).thenThrow(new GenericUncheckedException("basa"))) + when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa"))) ).flatMap(l -> Stream.of( // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work @@ -426,8 +607,8 @@ public class AaiClientTest { Response responseMock = mocks.getFakeResponse(); // prepare real AAIRestInterface and AaiClient, and wire mocks - AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, new ServletRequestHelper(), new SystemPropertyHelper()); - final AaiClient aaiClient = new AaiClient(aaiRestInterface, null); + AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, mock(ServletRequestHelper.class), mock(SystemPropertyHelper.class)); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock); // define atomic method under test, including reset of "aaiRestInterface.client" @@ -465,6 +646,121 @@ public class AaiClientTest { assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)"); } + @DataProvider + public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() { + + final String cloudRegion = "{" + + " \"cloud-owner\": \"mure-royo-ru22\"," + + " \"cloud-region-id\": \"ravitu\"," + + " \"cloud-type\": \"openstack\"," + + " \"resource-version\": \"1523631256125\"," + + " \"relationship-list\": {" + + " \"relationship\": [{" + + " \"related-to\": \"pserver\"" + + " }" + + " ]" + + " }" + + " }"; + + String bodyWith0 = "{ \"cloud-region\": [" + " ]}"; + String bodyWith1 = "{ \"cloud-region\": [" + cloudRegion + " ]}"; + String bodyWith2 = "{ \"cloud-region\": [" + cloudRegion + ", " + cloudRegion + " ]}"; + String bodyWithDifferent2 = "{ \"cloud-region\": [" + cloudRegion + ", " + + cloudRegion.replace("mure-royo-ru22", "nolay-umaxo") + + "]}"; + + return new Object[][] { + { "regular single result", bodyWith1, false }, + { "exceptional empty result", bodyWith0, true }, + { "two same results", bodyWith2, false }, + { "two incoherent results", bodyWithDifferent2, true }, + }; + } + + @Test(dataProvider = "aaiClientGetCloudOwnerByCloudRegionId") + public void getCloudOwnerByCloudRegionIdNonCached(String desc, String body, boolean expectingException) { + final String cloudRegion = "ravitu"; + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, body); + when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("cloud-infrastructure/cloud-regions?cloud-region-id=" + cloudRegion)), + isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + try { + final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion); + if (expectingException) fail("expected failure on " + desc + ", got " + result); + else { + assertThat(result, is("mure-royo-ru22")); + } + } catch (Exception e) { + if (!expectingException) throw e; + else { + assertThat(e.toString(), either( + containsString("No cloud-owner found for " + cloudRegion)) + .or(containsString("Conflicting cloud-owner found for " + cloudRegion))); + } + } + } + + @DataProvider + public static Object[][] cloudRegionAndTenantDataProvider() { + return new Object[][] { + { "APPC-24595-T-IST-02C", "mtn23b" }, + { "APPC-24595-T-IST-02C", null }, + { null, "mtn23b" }, + { null, null }, + }; + } + + @Test(dataProvider = "cloudRegionAndTenantDataProvider") + public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException { + SimpleResult tenant = new SimpleResult(); + if (tenantName != null) { + tenant.setJsonNodeType("tenant"); + Properties tenantProps = new Properties(); + tenantProps.setTenantName(tenantName); + tenant.setJsonProperties(tenantProps); + } + + SimpleResult cloudRegion = new SimpleResult(); + if (cloudRegionId != null) { + cloudRegion.setJsonNodeType("cloud-region"); + Properties cloudRegionProps = new Properties(); + cloudRegionProps.setCloudRegionId(cloudRegionId); + cloudRegion.setJsonProperties(cloudRegionProps); + } + + CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion)); + String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult); + + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, mockedBody, "query?format=simple", HttpMethod.PUT); + when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("query?format=simple")), + any(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + Map result = aaiClient.getCloudRegionAndTenantByVnfId("anyVnfId"); + if (tenantName != null) { + assertEquals(result.get("tenant").getTenantName(), tenantName); + } else { + assertNull(result.get("tenant")); + } + + if (cloudRegionId != null) { + assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId); + } else { + assertNull(result.get("cloud-region")); + } + } + + protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) { + when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET) ,anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + } + @Test public void shouldProperlyReadResponseOnceWhenSubscribersAreNotPresent() { AAIRestInterface restInterface = mock(AAIRestInterface.class); @@ -475,8 +771,8 @@ public class AaiClientTest { when(response.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND); ResponseWithRequestInfo responseWithRequestInfo = new ResponseWithRequestInfo(response, "test", HttpMethod.GET); when(restInterface.RestGet(eq("VidAaiController"), any(String.class), - eq("business/customers?subscriber-type=INFRA&depth=0"), eq(false), eq(true))).thenReturn(responseWithRequestInfo); - AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator); + eq(Unchecked.toURI("business/customers?subscriber-type=INFRA&depth=0")), eq(false), eq(true))).thenReturn(responseWithRequestInfo); + AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator, null); aaiClient.getAllSubscribers(true); @@ -497,4 +793,5 @@ public class AaiClientTest { void acceptThrows(T t, U u) throws Exception; } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java index d4f59e7d..da08ed86 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java @@ -34,7 +34,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.aai.model.AaiNodeQueryResponse; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.SubscriberList; @@ -50,31 +49,15 @@ public class AaiOverTLSClientServerTest { private static StubServerUtil serverUtil; - private String searchNodesQueryResponsePayload = - "{\n" - + "\"result-data\": [\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6eac8e69-c98d-4ac5-ab90-69fe0cabda76\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/e3766bc5-40a7-4dbe-9d4a-1d8c8f284913\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6aa153ee-6637-4b49-beb5-a5e756e00393\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/5a981c30-de25-4ea9-98fa-ed398f13ea41\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/b0ef2271-8ac0-4268-b9a5-09cb50c20c85\"\n" - + "}\n" - + "],\n" - + "}"; + private String searchNodesQueryResponsePayload = "" + + "{" + + "\"result-data\": [" + + " {" + + " \"resource-type\": \"generic-vnf\"," + + " \"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6eac8e69-c98d-4ac5-ab90-69fe0cabda76\"" + + " }" + + " ]" + + "}"; private String subscribersResponsePayload = "{\n" @@ -122,19 +105,17 @@ public class AaiOverTLSClientServerTest { ObjectMapper objectMapper = getFasterXmlObjectMapper(); AaiOverTLSClient aaiOverTLSClient = new AaiOverTLSClient(new SyncRestClient(objectMapper), propertySupplier, serverUtil.constructTargetUrl("http", "")); - serverUtil.prepareGetCall("/search/nodes-query", new JSONParser().parse(searchNodesQueryResponsePayload), Action.status(HttpStatus.OK_200)); + serverUtil.prepareGetCall("/nodes/generic-vnfs", new JSONParser().parse(searchNodesQueryResponsePayload), Action.status(HttpStatus.OK_200)); - HttpResponse aaiNodeQueryResponseHttpResponse = aaiOverTLSClient - .searchNodeTypeByName("any", ResourceType.GENERIC_VNF); + boolean aaiNodeQueryResponseHttpResponse = aaiOverTLSClient + .isNodeTypeExistsByName("any", ResourceType.GENERIC_VNF); - AaiNodeQueryResponse body = aaiNodeQueryResponseHttpResponse.getBody(); - Assertions.assertThat(body.resultData.size()).isEqualTo(5); - Assertions.assertThat(aaiNodeQueryResponseHttpResponse.getStatus()).isEqualTo(200); + Assertions.assertThat(aaiNodeQueryResponseHttpResponse).isEqualTo(true); } @Test public void shouldGetSubscribers() throws ParseException, JsonProcessingException { - ObjectMapper objectMapper = getCodehausObjectMapper(); + ObjectMapper objectMapper = getFasterXmlObjectMapper(); AaiOverTLSClient aaiOverTLSClient = new AaiOverTLSClient(new SyncRestClient(objectMapper), propertySupplier, serverUtil.constructTargetUrl("http", "")); serverUtil.prepareGetCall("/business/customers", new JSONParser().parse(subscribersResponsePayload), Action.status(HttpStatus.OK_200)); @@ -146,31 +127,6 @@ public class AaiOverTLSClientServerTest { Assertions.assertThat(allSubscribers.getStatus()).isEqualTo(200); } - private ObjectMapper getCodehausObjectMapper() { - return new ObjectMapper() { - - org.codehaus.jackson.map.ObjectMapper om = new org.codehaus.jackson.map.ObjectMapper(); - - @Override - public T readValue(String s, Class aClass) { - try { - return om.readValue(s, aClass); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public String writeValue(Object o) { - try { - return om.writeValueAsString(o); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - } - private ObjectMapper getFasterXmlObjectMapper() { return new ObjectMapper() { diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java index f281e84b..52556a1a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java @@ -24,10 +24,10 @@ import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Answers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.aai.model.AaiNodeQueryResponse; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.SubscriberList; @@ -41,11 +41,11 @@ import static org.mockito.ArgumentMatchers.eq; @RunWith(MockitoJUnitRunner.class) public class AaiOverTLSClientTest { - private static final String SEARCH_NODES_QUERY_SEARCH_NODE_TYPE = "search/nodes-query?search-node-type=generic-vnf&filter=vnf-name:EQUALS:name"; + private static final String SEARCH_NODES_QUERY_SEARCH_NODE_TYPE = "nodes/generic-vnfs?vnf-name=name"; private static final String SUBSCRIBERS = "business/customers?subscriber-type=INFRA&depth=0"; private AaiOverTLSClient aaiRestClient; - @Mock + @Mock(answer = Answers.RETURNS_MOCKS) private SyncRestClient syncRestClient; @Mock private AaiOverTLSPropertySupplier propertySupplier; @@ -56,12 +56,12 @@ public class AaiOverTLSClientTest { } @Test - public void testSearchNodeTypeByName() { + public void testIsNodeTypeExistsByName() { mockPropertyReader(); - aaiRestClient.searchNodeTypeByName("name", ResourceType.GENERIC_VNF); + aaiRestClient.isNodeTypeExistsByName("name", ResourceType.GENERIC_VNF); Mockito.verify(syncRestClient).get(contains(SEARCH_NODES_QUERY_SEARCH_NODE_TYPE), - eq(getHeaders()), eq(Collections.emptyMap()), eq(AaiNodeQueryResponse.class)); + eq(getHeaders()), eq(Collections.emptyMap())); } @Test diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java index c2ccec00..3d649bb6 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java @@ -2,8 +2,6 @@ package org.onap.vid.aai; import org.junit.Test; import org.onap.vid.aai.model.RelationshipList; -import java.util.*; -import org.junit.Assert; public class OperationalEnvironmentTest { @@ -28,7 +26,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentId(operationalEnvironmentId); + testSubject.setJsonOperationalEnvironmentId(operationalEnvironmentId); } @Test @@ -48,7 +46,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentName(operationalEnvironmentName); + testSubject.setJsonOperationalEnvironmentName(operationalEnvironmentName); } @Test @@ -68,7 +66,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentType(operationalEnvironmentType); + testSubject.setJsonOperationalEnvironmentType(operationalEnvironmentType); } @Test @@ -88,7 +86,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentStatus(operationalEnvironmentStatus); + testSubject.setJsonOperationalEnvironmentStatus(operationalEnvironmentStatus); } @Test @@ -108,7 +106,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setTenantContext(tenantContext); + testSubject.setJsonTenantContext(tenantContext); } @Test @@ -128,7 +126,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setWorkloadContext(workloadContext); + testSubject.setJsonWorkloadContext(workloadContext); } @Test @@ -148,7 +146,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setResourceVersion(resourceVersion); + testSubject.setJsonResourceVersion(resourceVersion); } @Test @@ -168,7 +166,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setRelationshipList(relationshipList); + testSubject.setJsonRelationshipList(relationshipList); } @Test diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java index 2b7a6042..72a5e193 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java @@ -1,10 +1,10 @@ package org.onap.vid.aai; -import java.util.Map; - import org.junit.Test; import org.onap.vid.aai.model.VnfResult; +import java.util.Map; + public class VnfResultTest { private VnfResult createTestSubject() { @@ -29,6 +29,5 @@ public class VnfResultTest { // default test testSubject = createTestSubject(); - testSubject.setAdditionalProperty(name, value); } } \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java index 7b5b8aa3..d7394632 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java @@ -1,15 +1,15 @@ package org.onap.vid.aai.model; -import java.io.IOException; -import java.util.ArrayList; - -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.util.ArrayList; + import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.StringContains.containsString; public class AaiGetPnfResponseTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java index e2a62c0e..a59b5207 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java @@ -1,13 +1,11 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import java.io.IOException; -import java.util.ArrayList; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java index 912eea9d..4f2762c3 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java @@ -1,11 +1,11 @@ package org.onap.vid.aai.model; -import java.io.IOException; - -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java new file mode 100644 index 00000000..1faaee3a --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java @@ -0,0 +1,32 @@ +package org.onap.vid.aai.util; + +import org.testng.annotations.Test; + +import static org.testng.AssertJUnit.assertEquals; + +public class CacheConfigTest { + + @Test + public void whenDeserializeJson_ValuesReadAsExpected() { + CacheConfigProvider cacheConfigProvider = new CacheConfigProviderImpl(); + CacheConfig cacheConfigA = cacheConfigProvider.getCacheConfig("a"); + assertEquals(true, cacheConfigA.isActive()); + assertEquals(6L, cacheConfigA.getExpireAfterWriteHours()); + assertEquals(9L, cacheConfigA.getRefreshAfterWriteSeconds()); + + //entry exist in configuration, but with no values + CacheConfig cacheConfigB = cacheConfigProvider.getCacheConfig("b"); + assertEquals(cacheConfigB.isActive(), CacheConfig.Companion.getDefaultCacheConfig().isActive()); + assertEquals(cacheConfigB.getExpireAfterWriteHours(), CacheConfig.Companion.getDefaultCacheConfig().getExpireAfterWriteHours()); + assertEquals(cacheConfigB.getRefreshAfterWriteSeconds(), CacheConfig.Companion.getDefaultCacheConfig().getRefreshAfterWriteSeconds()); + + + //entry doesn't exist in configuration + CacheConfig cacheConfigC = cacheConfigProvider.getCacheConfig("c"); + assertEquals(CacheConfig.Companion.getDefaultCacheConfig(), cacheConfigC); + + CacheConfig cacheConfigD = cacheConfigProvider.getCacheConfig("d"); + assertEquals(false, cacheConfigD.isActive()); + + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java new file mode 100644 index 00000000..95daf903 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java @@ -0,0 +1,41 @@ +package org.onap.vid.aai.util; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onap.vid.aai.util.CacheProvider.compileKey; +import static org.onap.vid.aai.util.CacheProvider.decompileKey; + +public class CacheProviderTest { + @Test(dataProvider = "aaiClientCompileDecompileKeySameData") + public void compileDecompileKeySameTest(List args) { + assertThat(decompileKey(compileKey(args)), is(args.toArray())); + } + + @Test(dataProvider = "aaiClientCompileDecompileKeyDifferentData") + public void compileDecompileKeyDifferentTest(List expectedResult, List args) { + assertThat(decompileKey(compileKey(args)), is(expectedResult.toArray())); + } + + @DataProvider + public static Object[][] aaiClientCompileDecompileKeySameData() { + return new Object[][] { + {Arrays.asList( "a", "b", "c")}, + {Arrays.asList("a")}, + {Arrays.asList("a!", "@#?b")}, + {Arrays.asList("a", "", "c")} + }; + } + + @DataProvider + public static Object[][] aaiClientCompileDecompileKeyDifferentData() { + return new Object[][] { + {Arrays.asList("a", "", "c"), Arrays.asList("a", null, "c")} + }; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java new file mode 100644 index 00000000..9a9b2890 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java @@ -0,0 +1,313 @@ +package org.onap.vid.aai.util; + +import com.google.common.cache.CacheBuilder; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.RandomUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.properties.Features; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Function; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.core.Is.is; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.*; +import static org.testng.AssertJUnit.assertEquals; + +public class CacheProviderWithLoadingCacheTest { + private final FeatureManager featureManager = mock(FeatureManager.class); + private final CacheConfigProvider cacheConfigProvider = mock(CacheConfigProvider.class); + + @BeforeMethod + public void activateCacheFeatureFlag() { + reset(featureManager); + when(featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true); + when(cacheConfigProvider.getCacheConfig(any())).thenReturn(CacheConfig.Companion.getDefaultCacheConfig()); + } + + private CacheProviderWithLoadingCache createNewCacheProvider() { + return new CacheProviderWithLoadingCache(featureManager, cacheConfigProvider); + } + + private String RAND() { + return randomAlphanumeric(5); + } + + @Test + public void cacheProvider_requestingCache_CreatesNewCache() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 4); + + assertThat(integerIntegerCache, notNullValue()); + assertThat(integerIntegerCache.get(5), is(9)); + } + + @Test + public void cacheProvider_requestingCacheSameNameTwice_ReturnsFirstCacheInstance() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final String name = RAND(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(name, (Integer i) -> i + 4); + final CacheProvider.Cache integerIntegerCache2 = provider.aaiClientCacheFor(name, (Integer i) -> i + 6); + + assertThat(integerIntegerCache2, sameInstance(integerIntegerCache)); + assertThat(integerIntegerCache.get(5), is(9)); // as the first one + } + + @Test + public void cacheProvider_requestingCacheSameNameTwiceOutOfSeveral_ReturnsFirstCacheInstance() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + + final String name = RAND(); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 2); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 3); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(name, (Integer i) -> i + 4); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 5); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 6); + final CacheProvider.Cache integerIntegerCache2 = provider.aaiClientCacheFor(name, (Integer i) -> i + 4); + + assertThat(integerIntegerCache2, sameInstance(integerIntegerCache)); + } + + @Test + public void cacheProvider_sameProviderSupportDifferentKV() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + + assertThat(provider.aaiClientCacheFor(RAND(), + (Integer i) -> i + 2).get(0), is(2)); + assertThat(provider.aaiClientCacheFor(RAND(), + (Integer i) -> i + 3).get(0), is(3)); + assertThat(provider.aaiClientCacheFor(RAND(), + (String s) -> s + 5).get("0"), is("05")); + assertThat(provider.aaiClientCacheFor(RAND(), + (Integer i) -> "0" + i).get(0), is("00")); + assertThat(provider.aaiClientCacheFor(RAND(), + (Pair p) -> ImmutableList.of(p.getLeft(), p.getRight())).get(Pair.of(7, "B")), contains(7, "B")); + } + + @Test + public void cache_callMultiTimesGetFromCahce_loaderCalledOncePairValue(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> RandomUtils.nextInt()); + int key = RandomUtils.nextInt(); + Integer result1 = integerIntegerCache.get(key); + Integer result2 = integerIntegerCache.get(key + 1); + Integer result3 = integerIntegerCache.get(key); + + Assert.assertNotEquals(result1,result2); + Assert.assertEquals(result1,result3); + } + + @Test + public void cache_callMultiTimesGetFromCahce_loaderCalledOnce(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> { + counter.increment(); + return i; + }); + + int key = RandomUtils.nextInt(); + Integer result1 = integerIntegerCache.get(key); + Integer result2 = integerIntegerCache.get(key); + Integer result3 = integerIntegerCache.get(key); + + Assert.assertEquals(result1.intValue(),key); + Assert.assertEquals(result2.intValue(),key); + Assert.assertEquals(result3.intValue(),key); + Assert.assertEquals(counter.intValue(),1); + } + + @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp ="boom" ) + public void cache_inCaseLoaderMethodThrowsException_cacheThrowsSameException(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache stringIntegerCache = provider.aaiClientCacheFor(RAND(), (String s) -> { throw new GenericUncheckedException("boom");}); + + stringIntegerCache.get("Whatever"); + } + + @Test + public void cache_inCaseLoaderMethodThrowsException_nextCallUseLoaderMethod(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), new Function() { + private boolean firstTime = true; + @Override + public Integer apply(Integer i) { + if (firstTime) { + firstTime = false; + throw new GenericUncheckedException("boom"); + } + else { + return i; + } + } + }); + + try { + integerIntegerCache.get(1); + } + catch (GenericUncheckedException e) {} + + assertEquals(new Integer(1), integerIntegerCache.get(1)); + } + + @Test + public void cache_getIsCalledMoreThanOnce_loaderNotCalledAgainForSameInputValue(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> { counter.increment(); return i; }); + + int key1 = RandomUtils.nextInt(); + int key2 = RandomUtils.nextInt(); + integerIntegerCache.get(key1); + Assert.assertEquals(counter.intValue(),1); + integerIntegerCache.get(key2); + Assert.assertEquals(counter.intValue(),2); + integerIntegerCache.get(key1); + Assert.assertEquals(counter.intValue(),2); + } + + @Test + public void cache_getIsCalledMoreThanOnce_loaderIsCalledAgainAfterReset(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + String cacheName = RAND(); + + int key1 = RandomUtils.nextInt(); + provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1); + Assert.assertEquals(counter.intValue(), 1); + provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1); + Assert.assertEquals(counter.intValue(), 1); + + provider.resetCache(cacheName); + provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1); + Assert.assertEquals(counter.intValue(), 2); + + } + + + public static class TestData { + public FeatureManager featureManager; + public String cacheName; + public CacheConfigProvider cacheConfigProvider; + + public TestData(FeatureManager featureManager, String cacheName, CacheConfigProvider cacheConfigProvider) { + this.featureManager = featureManager; + this.cacheName = cacheName; + this.cacheConfigProvider = cacheConfigProvider; + } + } + + + @DataProvider + public static Object[][] mockForCacheIsNotActive() { + + Consumer mockFeatureOff = (testData)->{ + when(testData.featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(false); + when(testData.cacheConfigProvider.getCacheConfig(testData.cacheName)).thenReturn(new CacheConfig(true, 10L, 10L)); + }; + Consumer mockFeatureOnCacheOff = (testData)->{ + when(testData.featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true); + when(testData.cacheConfigProvider.getCacheConfig(testData.cacheName)).thenReturn(new CacheConfig(false, 10L, 10L)); + }; + + + return new Object[][]{ + {mockFeatureOff}, + {mockFeatureOnCacheOff} + }; + } + + + @Test(dataProvider = "mockForCacheIsNotActive") + public void cache_featureFlagToggleIsOff_loaderIsCalledForEachGet(Consumer mocker){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + String cacheName = RAND(); + + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(cacheName, (Integer i) -> { + counter.increment(); + return i; + }); + + mocker.accept(new TestData(featureManager, cacheName, cacheConfigProvider)); + counter.setValue(0); + int key = RandomUtils.nextInt(); + integerIntegerCache.get(key); + integerIntegerCache.get(key); + + Assert.assertEquals(counter.intValue(),2); + } + + @Test + public void cache_loaderReturnsRandomValue_sameValueIsReturnedForSameKey() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final String name = RAND(); + final CacheProvider.Cache integerRandomStringCache = provider.aaiClientCacheFor(name, (Integer i) -> RAND()); + + String firstGet = integerRandomStringCache.get(1); + String secondGet = integerRandomStringCache.get(1); + + Assert.assertEquals(firstGet,secondGet); + } + + @Test(dataProvider = "mockForCacheIsNotActive") + public void cache_toggleFlagOff_ResetCache(Consumer mocker){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final String cacheName = RAND(); + final CacheProvider.Cache integerRandomStringCache = provider.aaiClientCacheFor(cacheName, (Integer i) -> RAND()); + int key = RandomUtils.nextInt(); + String result1 = integerRandomStringCache.get(key); + String result2 = integerRandomStringCache.get(key); + Assert.assertEquals(result1,result2); + + mocker.accept(new TestData(featureManager, cacheName, cacheConfigProvider)); + String result3 = integerRandomStringCache.get(key); + Assert.assertNotEquals(result1, result3); + } + + @DataProvider + public static Object[][] mockForCacheBuilderConfig() { + return new Object[][]{ + {2L, 2L, 3L, 3L}, + {null, 10L, null, 24L} //null meaning use the default, which is 10L,24L + }; + } + + @Test(dataProvider = "mockForCacheBuilderConfig") + public void cacheBuilderConfiguredWithValues_andWithDefaults( + Long refreshAfterWriteSeconds, + long expectedRefreshAfterWriteSeconds, + Long expireAfterWriteHours, + long expectedExpireAfterWriteHours + ) throws IllegalAccessException { + final String cacheName = RAND(); + when(cacheConfigProvider.getCacheConfig(cacheName)).thenReturn(new CacheConfig(true, expireAfterWriteHours, refreshAfterWriteSeconds)); + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + CacheBuilder cacheBuilder = provider.createCacheBuilder(cacheName); + + + //Unfortunately CacheBuilder doesn't expose public getters + //Since it's only unit test I let myself do some fouls and use reflection + Long actualRefreshNanos = (Long)FieldUtils.readDeclaredField(cacheBuilder, "refreshNanos", true); + assertThat(actualRefreshNanos, equalTo(TimeUnit.NANOSECONDS.convert(expectedRefreshAfterWriteSeconds, TimeUnit.SECONDS))); + + Long actualExpireAfterWriteNanos = (Long)FieldUtils.readDeclaredField(cacheBuilder, "expireAfterWriteNanos", true); + assertThat(actualExpireAfterWriteNanos, equalTo(TimeUnit.NANOSECONDS.convert(expectedExpireAfterWriteHours, TimeUnit.HOURS))); + + } +} + diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java index ce957ab6..44678ec2 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java @@ -21,11 +21,20 @@ package org.onap.vid.aai.util; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.aai.exceptions.HttpClientBuilderException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.togglz.core.manager.FeatureManager; import javax.net.ssl.SSLContext; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class HttpsAuthClientTest { @@ -38,47 +47,43 @@ public class HttpsAuthClientTest { public static final String CERT_FILE_PATH = "any_path"; - /* - TO BE IMPLEMENTED - private HttpsAuthClient createTestSubject() { - return new HttpsAuthClient(systemPropertyHelper, sslContextProvider); + return new HttpsAuthClient(CERT_FILE_PATH, systemPropertyHelper, sslContextProvider, mock(FeatureManager.class)); } @Before public void setUp() throws Exception { when(systemPropertyHelper.getAAITruststoreFilename()).thenReturn(Optional.of("filename")); - when(systemPropertyHelper.getEncodedTruststorePassword()).thenReturn("password"); + when(systemPropertyHelper.getDecryptedKeystorePassword()).thenReturn("password"); + when(systemPropertyHelper.getDecryptedTruststorePassword()).thenReturn("password"); } @Test(expected = HttpClientBuilderException.class) - public void testHttpClientBuilderExceptionOnGetClient() throws HttpClientBuilderException { + public void testHttpClientBuilderExceptionOnGetClient() throws Exception { //when - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("true")); - when(sslContextProvider.getSslContext(anyString(), anyString())).thenThrow(new HttpClientBuilderException()); - createTestSubject().getClient("nonExistingFile"); + when(systemPropertyHelper.isClientCertEnabled()).thenReturn(true); + when(sslContextProvider.getSslContext(anyString(), anyString(), any())).thenThrow(new HttpClientBuilderException(new GenericUncheckedException("msg"))); + createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE); } @Test public void testGetSecuredClient() throws Exception { // when - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("true")); - when(sslContextProvider.getSslContext(anyString(), anyString())).thenReturn(sslContext); - createTestSubject().getClient(CERT_FILE_PATH); + when(systemPropertyHelper.isClientCertEnabled()).thenReturn(true); + when(sslContextProvider.getSslContext(anyString(), anyString(), any())).thenReturn(sslContext); + createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE); //then - verify(sslContextProvider).getSslContext(anyString(), anyString()); + verify(sslContextProvider).getSslContext(anyString(), anyString(), any()); } @Test public void testGetUnsecuredClient() throws Exception { // when - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("false")); - when(sslContextProvider.getSslContext(anyString(), anyString())).thenReturn(sslContext); - createTestSubject().getClient(CERT_FILE_PATH); + when(systemPropertyHelper.isClientCertEnabled()).thenReturn(false); + createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE); //then - verify(sslContextProvider, never()).getSslContext(anyString(), anyString()); + verify(sslContextProvider, never()).getSslContext(anyString(), anyString(), any()); } - */ } \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java new file mode 100644 index 00000000..b4337076 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java @@ -0,0 +1,14 @@ +package org.onap.vid.aai.util; + +import java.util.function.Function; + +public class NonCachingCacheProvider implements CacheProvider { + + @Override + public Cache aaiClientCacheFor(String name, Function loader) { + return loader::apply; + } + + @Override + public void resetCache(String name) {} +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java new file mode 100644 index 00000000..99cd928c --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java @@ -0,0 +1,405 @@ +package org.onap.vid.aai.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vlan; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vnf; +import org.onap.vid.utils.Multival; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.net.URI; +import java.util.List; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.everyItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.onap.vid.utils.Unchecked.toURI; + + +public class ServiceInstanceStandardQueryTest { + private static final Logger logger = LogManager.getLogger(ServiceInstanceStandardQueryTest.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private final String serviceInstanceId = "9cdd1b2a-43a7-47bc-a88e-759ba2399f0b"; + private final String vnfInstanceId_1 = "c015cc0f-0f37-4488-aabf-53795fd93cd3"; + private final String vnfInstanceId_2 = "0846287b-65bf-45a6-88f6-6a1af4149fac"; + private final String networkInstanceId_1 = "7989a6d2-ba10-4a5d-8f15-4520bc833090"; + private final String networkInstanceId_2 = "82373aaa-c561-4e2b-96f1-7ef6f7f7b0e9"; + private final String vlanTagInstanceId_1 = "701edbb2-37e4-4473-a2a6-405cb3ab2e37"; + private final String vlanTagInstanceId_2 = "531571f4-e133-4780-8ba8-d79e63804084"; + private final String vlanTagInstanceId_3 = "df674e8c-1773-4d39-a9e9-bddd2b339d0a"; + private final String SERVICE_TYPE = "service"; + private final String VNF_TYPE = "vnf"; + + @Mock + AaiClientInterface aaiClient; + @InjectMocks + private ServiceInstanceStandardQuery serviceInstanceStandardQuery; + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + + when(aaiClient.typedAaiGet(any(URI.class), any(Class.class))) + .thenAnswer(invocationOnMock -> { + final URI uri = (URI) invocationOnMock.getArguments()[0]; + final String lastPart = uri.toString().replaceAll(".*/", ""); + switch (lastPart) { + case serviceInstanceId: + return getAaiObject(ServiceInstance.class); + case vnfInstanceId_1: + case vnfInstanceId_2: + return getAaiObject(Vnf.class); + case networkInstanceId_1: + case networkInstanceId_2: + return getAaiObject(Network.class); + case vlanTagInstanceId_1: + case vlanTagInstanceId_2: + case vlanTagInstanceId_3: + return getAaiObject(Vlan.class); + default: + throw new ExceptionWithRequestInfo(HttpMethod.GET, uri.toASCIIString(), getAaiObjectString(true), 404, + new HttpClientErrorException(HttpStatus.NOT_FOUND)); + } + }); + } + + @Test + public void pathToObject_serviceInstanceUri_yieldsAaiObject() { + final ServiceInstance serviceInstance = serviceInstanceStandardQuery.objectByUri(ServiceInstance.class, toURI("/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/" + serviceInstanceId)); + assertThat(serviceInstance.getServiceInstanceId(), is(serviceInstanceId)); + assertThat(serviceInstance.getServiceInstanceName(), is("Network_repl_vMOG_rk")); + } + + @Test + public void pathToObject_networkUri_yieldsAaiObject() { + final Network network = serviceInstanceStandardQuery.objectByUri(Network.class, toURI("/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_1 + "")); + assertThat(network.getNetworkId(), is(networkInstanceId_1)); + assertThat(network.getNetworkName(), is("APPC-24595-T-IST-02AShared_cor_direct_net_1")); + } + + @Test + public void pathToObject_vlanTagUri_yieldsAaiObject() { + final Vlan vlan = serviceInstanceStandardQuery.objectByUri(Vlan.class, toURI("/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_1 + "")); + assertThat(vlan.getVlanInterface(), is("US-10688-genvnf-vlan-interface1")); + assertThat(vlan.getVlanIdInner(), is("917")); + } + + @Test(expectedExceptions = Exception.class) + public void pathToObject_oneUnknownUri_throwsException() { + serviceInstanceStandardQuery.objectByUri(ServiceInstance.class, toURI("/aai/v12/non existing path")); + } + + @Test + public void vnfsForServiceInstance_noRelatedButManyOthers_emptyResult() { + final Multival vnfs = + serviceInstanceStandardQuery.fetchRelatedVnfs(getAaiObject(false, ServiceInstance.class)); + assertThat(vnfs.getValues(), is(empty())); + } + + @Test + public void vnfsForServiceInstance_2RelatedAndManyOthers_Result2CorrectPath2() { + final Multival vnfs = + serviceInstanceStandardQuery.fetchRelatedVnfs(getAaiObject(ServiceInstance.class)); + + assertThat(vnfs.getValues(), hasSize(2)); + } + + @Test + public void serviceInstanceToL3Networks_noRelatedButManyOthers_emptyResult() { + final Multival l3Networks = + serviceInstanceStandardQuery.fetchRelatedL3Networks(SERVICE_TYPE, getAaiObject(false, ServiceInstance.class)); + assertThat(l3Networks.getValues(), is(empty())); + } + + @Test + public void serviceInstanceToL3Networks_2RelatedAndManyOthers_Result2CorrectPath2() { + final Multival l3Networks = + serviceInstanceStandardQuery.fetchRelatedL3Networks(SERVICE_TYPE, getAaiObject(ServiceInstance.class)); + + assertThat(l3Networks.getValues(), hasSize(2)); + } + + @Test + public void l3NetworkToVlanTags_noRelatedButManyOthers_emptyResult() { + final Multival vlanTags = + serviceInstanceStandardQuery.fetchRelatedVlanTags(getAaiObject(false, Network.class)); + assertThat(vlanTags.getValues(), is(empty())); + } + + @Test + public void l3NetworkToVlanTags__2RelatedAndManyOthers_Result2CorrectPath() { + final Multival vlanTags = + serviceInstanceStandardQuery.fetchRelatedVlanTags(getAaiObject(Network.class)); + + assertThat(vlanTags.getValues(), hasSize(3)); + } + + private T getAaiObject(Class valueType) { + return getAaiObject(true, valueType); + } + + private T getAaiObject(boolean withRelated, Class valueType) { + try { + return MAPPER.readValue(getAaiObjectString(withRelated), valueType); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + public void integrativeUsageWithLinearInvocation() throws JsonProcessingException { + final ServiceInstanceStandardQuery srv = this.serviceInstanceStandardQuery; + final ServiceInstance service = srv.fetchServiceInstance(toURI("path of service/" + serviceInstanceId + "")); + final Network l3Network = ImmutableList.copyOf(srv.fetchRelatedL3Networks(SERVICE_TYPE, service).getValues()).get(0); + final Vlan vlanTag = ImmutableList.copyOf(srv.fetchRelatedVlanTags(l3Network).getValues()).get(0); + + assertThat(vlanTag.getVlanInterface(), is("US-10688-genvnf-vlan-interface1")); + assertThat(vlanTag.getVlanIdInner(), is("917")); + } + + @Test + public void integrativeUsageWithGenericAccessors() throws JsonProcessingException { + final ServiceInstanceStandardQuery srv = this.serviceInstanceStandardQuery; + + final ServiceInstance serviceInstance = srv.fetchServiceInstance(toURI("path of service/" + serviceInstanceId + "")); + + final Multival serviceToNetworks = + srv.fetchRelatedL3Networks(SERVICE_TYPE, serviceInstance); + + final Multival> serviceToNetworksToVlans = + serviceToNetworks.mapEachVal(srv::fetchRelatedVlanTags); + + logger.info(MAPPER.writeValueAsString(serviceToNetworksToVlans)); + + // check all tags are in place + final List vlanTags = serviceToNetworksToVlans + .getValues().stream() + .flatMap(networkVlanMultival -> networkVlanMultival.getValues().stream()) + .collect(Collectors.toList()); + + assertThat(vlanTags, hasSize(6)); // 2 networks, with 3 vlans each + assertThat(vlanTags, everyItem(hasProperty("vlanInterface", is("US-10688-genvnf-vlan-interface1")))); + assertThat(vlanTags, everyItem(hasProperty("vlanIdInner", is("917")))); + } + + private String getAaiObjectString(boolean withRelated) { + final String relatedToVnfs = "" + + " { " + + " \"related-to\": \"generic-vnf\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/generic-vnfs/generic-vnf/" + vnfInstanceId_1 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"generic-vnf.vnf-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_1 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"generic-vnf.vnf-name\", " + + " \"property-value\": \"\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"generic-vnf\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/generic-vnfs/generic-vnf/" + vnfInstanceId_2 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"generic-vnf.vnf-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_2 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"generic-vnf.vnf-name\", " + + " \"property-value\": \"\" " + + " } " + + " ] " + + " }, "; + + + final String relatedToL3Networks = "" + + " { " + + " \"related-to\": \"l3-network\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_1 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"l3-network.network-id\", " + + " \"relationship-value\": \"" + networkInstanceId_1 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"l3-network.network-name\", " + + " \"property-value\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"l3-network\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_2 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"l3-network.network-id\", " + + " \"relationship-value\": \"" + networkInstanceId_2 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"l3-network.network-name\", " + + " \"property-value\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\" " + + " } " + + " ] " + + " }, "; + + final String relatedToVlanTags = "" + + " { " + + " \"related-to\": \"vlan-tag\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_2 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"vlan-tag.vlan-tag-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_2 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"vlan-tag.vlan-tag-name\", " + + " \"property-value\": \"Behram_smeralda_56\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"vlan-tag\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_3 + "\" " + + " }, { " + + " \"related-to\": \"vlan-tag\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_1 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"vlan-tag.vlan-tag-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_1 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"vlan-tag.vlan-tag-name\", " + + " \"property-value\": \"Alexandra_Liron_3\" " + + " } " + + " ] " + + " }, "; + + return "" + + "{ " + + + // vlan props + " \"vlan-interface\": \"US-10688-genvnf-vlan-interface1\", " + + " \"vlan-id-inner\": 917, " + + " \"resource-version\": \"1518934744675\", " + + " \"in-maint\": false, " + + " \"is-ip-unnumbered\": false, " + + // imaginary vlan props + " \"vlan-tag-id\": \"" + vlanTagInstanceId_2 + "\", " + + " \"vlan-tag-name\": \"Alexandra_Liron_3\", " + + " \"vlan-tag-type\": \"SUNIWOBA\", " + + + // service-instance props + " \"service-instance-name\": \"Network_repl_vMOG_rk\", " + + " \"service-instance-id\": \"" + serviceInstanceId + "\", " + + " \"environment-context\": \"General_Revenue-Bearing\", " + + " \"workload-context\": \"Production\", " + + " \"model-invariant-id\": \"92a72881-0a97-4d16-8c29-4831062e7e9b\", " + + " \"model-version-id\": \"5a3ad576-c01d-4bed-8194-0e72b4a3d020\", " + + " \"resource-version\": \"1516045827731\", " + + " \"orchestration-status\": \"Active\", " + + + // network props + " \"network-id\": \"" + networkInstanceId_1 + "\", " + + " \"network-name\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\", " + + " \"network-type\": \"CONTRAIL30_BASIC\", " + + " \"network-role\": \"repl\", " + + " \"network-technology\": \"contrail\", " + + " \"neutron-network-id\": \"66ee6123-1c45-4e71-b6c0-a748ae0fee88\", " + + " \"is-bound-to-vpn\": true, " + + " \"service-id\": \"db171b8f-115c-4992-a2e3-ee04cae357e0\", " + + " \"network-role-instance\": 0, " + + " \"resource-version\": \"1516046029762\", " + + " \"heat-stack-id\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1/e8b256aa-8ce1-4384-9d99-6606eaca9eac\", " + + " \"contrail-network-fqdn\": \"default-domain:APPC-24595-T-IST-02C:APPC-24595-T-IST-02AShared_cor_direct_net_1\", " + + " \"physical-network-name\": \"FALSE\", " + + " \"is-provider-network\": false, " + + " \"is-shared-network\": true, " + + " \"is-external-network\": true, " + + + " \"relationship-list\": { " + + " \"relationship\": [{ " + + " \"related-to\": \"service-instance\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/" + serviceInstanceId + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"customer.global-customer-id\", " + + " \"relationship-value\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\" " + + " }, { " + + " \"relationship-key\": \"service-subscription.service-type\", " + + " \"relationship-value\": \"vMOG\" " + + " }, { " + + " \"relationship-key\": \"service-instance.service-instance-id\", " + + " \"relationship-value\": \"" + serviceInstanceId + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"service-instance.service-instance-name\", " + + " \"property-value\": \"Network_repl_vMOG_rk\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"vpn-binding\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\", " + + " \"related-link\": \"/aai/v12/network/vpn-bindings/vpn-binding/13e94b71-3ce1-4988-ab0e-61208fc91f1c\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"vpn-binding.vpn-id\", " + + " \"relationship-value\": \"13e94b71-3ce1-4988-ab0e-61208fc91f1c\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"vpn-binding.vpn-name\", " + + " \"property-value\": \"vMDNS\" " + + " }, { " + + " \"property-key\": \"vpn-binding.vpn-type\" " + + " } " + + " ] " + + " }, " + (withRelated ? relatedToVlanTags : "") + "{ " + + " \"related-to\": \"project\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\", " + + " \"related-link\": \"/aai/v12/business/projects/project/project1\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"project.project-name\", " + + " \"relationship-value\": \"project1\" " + + " } " + + " ] " + + " }, " + (withRelated ? relatedToL3Networks + relatedToVnfs : "") + "{ " + + " \"related-to\": \"owning-entity\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.BelongsTo\", " + + " \"related-link\": \"/aai/v12/business/owning-entities/owning-entity/589fe0db-26c4-45e5-9f4e-a246c74fce76\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"owning-entity.owning-entity-id\", " + + " \"relationship-value\": \"589fe0db-26c4-45e5-9f4e-a246c74fce76\" " + + " } " + + " ] " + + " } " + + " ] " + + " } " + + "} "; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java index 7fad9019..b5f8ff94 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java @@ -26,7 +26,11 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.exceptions.InvalidPropertyException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.utils.Unchecked; +import org.springframework.http.HttpMethod; import org.testng.Assert; import javax.servlet.http.HttpServletRequest; @@ -37,10 +41,14 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; +import java.net.URI; import java.util.Optional; import java.util.UUID; import static javax.ws.rs.core.Response.Status.*; +import static junit.framework.TestCase.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -56,6 +64,8 @@ public class SingleAAIRestInterfaceTest { @Mock private Invocation.Builder builder; @Mock + private Invocation invocation; + @Mock private ServletRequestHelper servletRequestHelper; @Mock private HttpsAuthClient httpsAuthClient; @@ -76,6 +86,9 @@ public class SingleAAIRestInterfaceTest { when(webTarget.request()).thenReturn(builder); when(builder.accept(Mockito.anyString())).thenReturn(builder); when(builder.header(Mockito.anyString(), Mockito.anyString())).thenReturn(builder); + when(builder.build(Mockito.anyString())).thenReturn(invocation); + when(builder.build(Mockito.anyString(), any(Entity.class))).thenReturn(invocation); + when(invocation.invoke()).thenReturn(response); when(servletRequestHelper.extractOrGenerateRequestId()).thenReturn(UUID.randomUUID().toString()); } @@ -90,70 +103,67 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testSetRestSrvrBaseURLWithNullValue() throws Exception { + public void testSetRestSrvrBaseURLWithNullValue() { testSubject.SetRestSrvrBaseURL(null); } @Test - public void testSetRestSrvrBaseURL() throws Exception { + public void testSetRestSrvrBaseURL() { String baseUrl = "anything"; testSubject.SetRestSrvrBaseURL(baseUrl); Assert.assertEquals(testSubject.getRestSrvrBaseURL(), baseUrl); } @Test - public void testRestJsonPutWithResponse200() throws Exception { + public void testRestJsonPutWithResponse200() { // given String methodName = "RestPut"; String payload = "{\"id\": 1}"; Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); // when - when(builder.put(Mockito.any(Entity.class))).thenReturn(response); when(response.getStatusInfo()).thenReturn(OK); - Response finalResponse = testSubject.RestPut("", PATH, payload, false); + Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse(); // then - verify(builder).put(entity); + verify(builder).build(HttpMethod.PUT.name(), entity); Assert.assertEquals(response, finalResponse); } - @Test - public void testFailedRestJsonPut() throws Exception { + @Test(expected = ExceptionWithRequestInfo.class) + public void testFailedRestJsonPut() { // given String methodName = "RestPut"; String payload = "{\"id\": 1}"; Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); // when - when(builder.put(Mockito.any(Entity.class))).thenThrow(new RuntimeException()); - Response finalResponse = testSubject.RestPut("", PATH, payload, false); + when(builder.build(eq(HttpMethod.PUT.name()), any(Entity.class))).thenThrow(new GenericUncheckedException("msg")); + Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse(); // then - verify(builder).put(entity); - Assert.assertEquals(finalResponse, null); + fail("expected unreachable: exception to be thrown"); } @Test - public void testRestJsonPutWithResponse400() throws Exception { + public void testRestJsonPutWithResponse400() { // given String methodName = "RestPut"; String payload = "{\"id\": 1}"; Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); // when - when(builder.put(Mockito.any(Entity.class))).thenReturn(response); when(response.getStatusInfo()).thenReturn(BAD_REQUEST); when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode()); - Response finalResponse = testSubject.RestPut("", PATH, payload, false); + Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse(); // then - verify(builder).put(entity); + verify(builder).build(HttpMethod.PUT.name(), entity); Assert.assertEquals(response, finalResponse); } @Test - public void testRestPostWithResponse200() throws Exception { + public void testRestPostWithResponse200() { // given String methodName = "RestPost"; String payload = "{\"id\": 1}"; @@ -170,7 +180,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestPostWithResponse400() throws Exception { + public void testRestPostWithResponse400() { // given String methodName = "RestPost"; String payload = "{\"id\": 1}"; @@ -188,7 +198,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testFailedRestPost() throws Exception { + public void testFailedRestPost() { // given String methodName = "RestPost"; String payload = "{\"id\": 1}"; @@ -204,7 +214,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestDeleteWithResponse400() throws Exception { + public void testRestDeleteWithResponse400() { // given String methodName = "Delete"; @@ -222,7 +232,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestDeleteWithResponse404() throws Exception { + public void testRestDeleteWithResponse404() { // given String methodName = "Delete"; @@ -240,7 +250,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testFailedRestDelete() throws Exception { + public void testFailedRestDelete() { // given String methodName = "Delete"; @@ -254,54 +264,49 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestJsonGetWithResponse200() throws Exception { + public void testRestJsonGetWithResponse200() { // given String methodName = "RestGet"; // when - when(builder.get()).thenReturn(response); when(response.getStatusInfo()).thenReturn(OK); - Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse(); + Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse(); // then Assert.assertEquals(response, finalResponse); } @Test - public void testRestJsonGetWithResponse400() throws Exception { + public void testRestJsonGetWithResponse400() { // given String methodName = "RestGet"; // when - when(builder.get()).thenReturn(response); when(response.getStatusInfo()).thenReturn(BAD_REQUEST); when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode()); - Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse(); + Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse(); // then Assert.assertEquals(response, finalResponse); } @Test - public void testFailedRestGet() throws Exception { + public void testFailedRestGet() { // given String methodName = "RestGet"; // when - when(builder.get()).thenThrow(new RuntimeException()); - Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse(); + when(builder.build(HttpMethod.GET.name())).thenThrow(new RuntimeException()); + Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse(); // then Assert.assertEquals(finalResponse, null); } private void mockSystemProperties() throws UnsupportedEncodingException, InvalidPropertyException { - when(systemPropertyHelper.getAAIServerUrl()).thenReturn(Optional.of(HTTP_LOCALHOST)); - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("cert")); - when(systemPropertyHelper.getAAIVIDPasswd()).thenReturn(Optional.of("passwd")); - when(systemPropertyHelper.getAAIVIDUsername()).thenReturn(Optional.of("user")); when(systemPropertyHelper.getEncodedCredentials()).thenReturn("someCredentials"); when(systemPropertyHelper.getFullServicePath(Mockito.anyString())).thenReturn("http://localhost/path"); + when(systemPropertyHelper.getFullServicePath(Mockito.any(URI.class))).thenReturn("http://localhost/path"); when(systemPropertyHelper.getServiceBasePath(Mockito.anyString())).thenReturn("http://localhost/path"); } diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java deleted file mode 100644 index cb68eac9..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.onap.vid.asdc.beans.tosca; - -import org.junit.Test; - -public class PropertyTest { - - private Property createTestSubject() { - return new Property(); - } - - @Test - public void testGetType() throws Exception { - Property testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getType(); - } - - @Test - public void testGetDescription() throws Exception { - Property testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDescription(); - } - - @Test - public void testGetEntry_schema() throws Exception { - Property testSubject; - Schema result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getEntry_schema(); - } - - - @Test - public void testSetType() throws Exception { - Property testSubject; - String type = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setType(type); - } - - @Test - public void testSetDescription() throws Exception { - Property testSubject; - String description = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDescription(description); - } - - @Test - public void testSetEntry_schema() throws Exception { - Property testSubject; - Schema entry_schema = null; - - // default test - testSubject = createTestSubject(); - testSubject.setEntry_schema(entry_schema); - } - - - @Test - public void testGetDefault() throws Exception { - Property testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDefault(); - } - - @Test - public void testIsRequired() throws Exception { - Property testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isRequired(); - } - - @Test - public void testSetDefault() throws Exception { - Property testSubject; - String _default = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDefault(_default); - } - - @Test - public void testSetRequired() throws Exception { - Property testSubject; - boolean required = false; - - // default test - testSubject = createTestSubject(); - testSubject.setRequired(required); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java index e1c5e923..40c0f609 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java @@ -4,46 +4,64 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import net.javacrumbs.jsonunit.JsonAssert; import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.json.JSONObject; import org.json.JSONTokener; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.toscaparser.api.Group; import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Property; +import org.onap.sdc.toscaparser.api.elements.Metadata; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.local.LocalAsdcClient; -import org.onap.vid.controllers.ToscaParserMockHelper; +import org.onap.vid.controller.ToscaParserMockHelper; import org.onap.vid.model.*; +import org.onap.vid.properties.Features; import org.testng.Assert; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import static com.google.common.collect.Lists.newArrayList; import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.ECOMP_GENERATED_NAMING_PROPERTY; import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls; -@Test public class ToscaParserImpl2Test { private final String myUUID = "myUUID"; - private static final Logger log = Logger.getLogger(ToscaParserImpl2Test.class); + private static final Logger log = LogManager.getLogger(ToscaParserImpl2Test.class); - private ToscaParserImpl2 toscaParserImpl2 = new ToscaParserImpl2(); + @InjectMocks + private ToscaParserImpl2 toscaParserImpl2; private AsdcClient asdcClient; private ObjectMapper om = new ObjectMapper(); + @Mock + private VidNotionsBuilder vidNotionsBuilder; + @BeforeClass void init() throws IOException { @@ -56,60 +74,56 @@ public class ToscaParserImpl2Test { } - //@Test - public void assertEqualsBetweenServices() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Service expectedService = mockHelper.getNewServiceModel().getService(); - Service actualService = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService(); - assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService)); - } + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); } - //@Test - public void assertEqualBetweenObjects() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - final Path csarPath = getCsarPath(mockHelper.getUuid()); - System.out.println("Comparing for csar " + csarPath); - ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid())); - assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel)); - } + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenServices(String uuid, ToscaParserMockHelper mockHelper) throws Exception { + Service expectedService = mockHelper.getNewServiceModel().getService(); + Service actualService = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService(); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService)); } - //@Test - public void assertEqualsBetweenNetworkNodes() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks(); - Map actualNetworksMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks(); - for (Map.Entry entry : expectedNetworksMap.entrySet()) { - Network expectedNetwork = entry.getValue(); - Network actualNetwork = actualNetworksMap.get(entry.getKey()); - Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName()); - verifyBaseNodeProperties(expectedNetwork, actualNetwork); - compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties()); - } + @Test(dataProvider = "expectedServiceModel") + public void assertEqualBetweenObjects(String uuid, ToscaParserMockHelper mockHelper) throws Exception { + final Path csarPath = getCsarPath(mockHelper.getUuid()); + log.info("Comparing for csar " + csarPath); + ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid())); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel)); + } + + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenNetworkNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception { + Map expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks(); + Map actualNetworksMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks(); + for (Map.Entry entry : expectedNetworksMap.entrySet()) { + Network expectedNetwork = entry.getValue(); + Network actualNetwork = actualNetworksMap.get(entry.getKey()); + Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName()); + verifyBaseNodeMetadata(expectedNetwork, actualNetwork); + compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties()); } } //Because we are not supporting the old flow, the JSON are different by definition. - //@Test - public void assertEqualsBetweenVnfsOfTosca() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs(); - Map actualVnfsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs(); - for (Map.Entry entry : expectedVnfsMap.entrySet()) { - VNF expectedVnf = entry.getValue(); - VNF actualVnf = actualVnfsMap.get(entry.getKey()); - verifyBaseNodeProperties(expectedVnf, actualVnf); - Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName()); - compareProperties(expectedVnf.getProperties(), actualVnf.getProperties()); - assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf)); - } + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenVnfsOfTosca(String uuid, ToscaParserMockHelper mockHelper) throws Exception { + Map expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs(); + Map actualVnfsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs(); + for (Map.Entry entry : expectedVnfsMap.entrySet()) { + VNF expectedVnf = entry.getValue(); + VNF actualVnf = actualVnfsMap.get(entry.getKey()); + verifyBaseNodeMetadata(expectedVnf, actualVnf); + Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName()); + compareProperties(expectedVnf.getProperties(), actualVnf.getProperties()); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf)); } } - //@Test - public void assertEqualsBetweenCollectionResourcesOfTosca() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenCollectionResourcesOfTosca(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map expectedVnfsMap = mockHelper.getNewServiceModel().getCollectionResource(); Map actualCRsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getCollectionResource(); if(!actualCRsMap.isEmpty()) { @@ -122,11 +136,20 @@ public class ToscaParserImpl2Test { assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedCR), om.writeValueAsString(actualCR)); } } - } } +// @Test +// public void verifyFabricConfiguration() throws Exception { +// ToscaParserMockHelper toscaParserMockHelper = Arrays.stream(getExpectedServiceModel()).filter(x -> x.getUuid().equals(Constants.fabricConfigurationUuid)).findFirst().get(); +// ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(getCsarPath(Constants.fabricConfigurationUuid), getServiceByUuid(Constants.fabricConfigurationUuid)); +// final Map fabricConfigurations = actualServiceModel.getFabricConfigurations(); +// String fabricConfigName = "Fabric Configuration 0"; +// Map expectedFC = toscaParserMockHelper.getNewServiceModel().getFabricConfigurations(); +// verifyBaseNodeMetadata(expectedFC.get(fabricConfigName), fabricConfigurations.get(fabricConfigName)); +// } + private void verifyCollectionResource(CR expectedCR, CR actualCR) { - verifyBaseNodeProperties(expectedCR, actualCR); + verifyBaseNodeMetadata(expectedCR, actualCR); Assert.assertEquals(expectedCR.getCategory(), actualCR.getCategory()); Assert.assertEquals(expectedCR.getSubcategory(), actualCR.getSubcategory()); Assert.assertEquals(expectedCR.getResourceVendor(), actualCR.getResourceVendor()); @@ -155,39 +178,30 @@ public class ToscaParserImpl2Test { } - //@Test - public void assertEqualsBetweenVolumeGroups() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenVolumeGroups(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualVolumeGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVolumeGroups(); Map expectedVolumeGroups = mockHelper.getNewServiceModel().getVolumeGroups(); assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVolumeGroups), om.writeValueAsString(actualVolumeGroups)); - } } - //@Test - public void assertEqualsBetweenVfModules() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenVfModules(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualVfModules = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVfModules(); Map expectedVfModules = mockHelper.getNewServiceModel().getVfModules(); assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVfModules), om.writeValueAsString(actualVfModules)); - } } - //@Test - public void assertEqualsBetweenPolicyConfigurationNodes() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenPolicyConfigurationNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); Map expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); JsonAssert.assertJsonEquals(actualConfigurations, expectedConfigurations); - } } - //@Test + + @Test public void assertEqualsBetweenPolicyConfigurationByPolicyFalse() throws Exception { ToscaParserMockHelper mockHelper = new ToscaParserMockHelper(Constants.configurationByPolicyFalseUuid, Constants.configurationByPolicyFalseFilePath); - InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(mockHelper.getFilePath()); - String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); - NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class); - mockHelper.setNewServiceModel(newServiceModel1); Map expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); Map actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); @@ -196,12 +210,27 @@ public class ToscaParserImpl2Test { JsonAssert.assertJsonEquals(expectedConfigurations, actualConfigurations); } + @Test + public void once5GInNewInstantiationFlagIsActive_vidNotionsIsAppended() throws Exception { + FeatureManager featureManager = mock(FeatureManager.class); + when(featureManager.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true); + + ToscaParserImpl2 toscaParserImpl2_local = new ToscaParserImpl2(new VidNotionsBuilder(featureManager)); + + final ToscaParserMockHelper mockHelper = new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath); + final ServiceModel serviceModel = toscaParserImpl2_local.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())); + + assertThat(serviceModel.getService().getVidNotions().getInstantiationUI(), is(VidNotions.InstantiationUI.LEGACY)); + assertThat(serviceModel.getService().getVidNotions().getModelCategory(), is(VidNotions.ModelCategory.OTHER)); + assertJsonStringEqualsIgnoreNulls("{ service: { vidNotions: { instantiationUI: \"legacy\", modelCategory: \"other\" } } }", om.writeValueAsString(serviceModel)); + } + @Test public void modelWithAnnotatedInputWithTwoProperties_vfModuleGetsTheInput() throws Exception { final ToscaParserMockHelper mockHelper = new ToscaParserMockHelper("90fe6842-aa76-4b68-8329-5c86ff564407", "empty.json"); final ServiceModel serviceModel = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())); - assertJsonStringEqualsIgnoreNulls("{ vfModules: { 201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1: { inputs: { 201712488_adiodvpe10_availability_zone_0: { } } } } }", om.writeValueAsString(serviceModel)); + assertJsonStringEqualsIgnoreNulls("{ vfModules: { 201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1: { inputs: { availability_zone_0: { } } } } }", om.writeValueAsString(serviceModel)); } @Test @@ -226,16 +255,21 @@ public class ToscaParserImpl2Test { pmconfig.setCollectorNodes(new ArrayList<>(Arrays.asList("pprobeservice_proxy 4"))); } - //@Test - public void assertEqualsBetweenServiceProxyNodes() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenServiceProxyNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualServiceProxies = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getServiceProxies(); Map expectedServiceProxies = mockHelper.getNewServiceModel().getServiceProxies(); JsonAssert.assertJsonEquals(actualServiceProxies, expectedServiceProxies); - } } - private void verifyBaseNodeProperties(Node expectedNode, Node actualNode) { + @Test(dataProvider = "expectedServiceModel") + public void assertEqualsBetweenVnfGroups(String uuid, ToscaParserMockHelper mockHelper) throws Exception { + Map actualVnfGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfGroups(); + Map expectedVnfGroups = mockHelper.getNewServiceModel().getVnfGroups(); + JsonAssert.assertJsonEquals(actualVnfGroups, expectedVnfGroups); + } + + private void verifyBaseNodeMetadata(Node expectedNode, Node actualNode) { Assert.assertEquals(expectedNode.getName(), actualNode.getName()); Assert.assertEquals(expectedNode.getCustomizationUuid(), actualNode.getCustomizationUuid()); Assert.assertEquals(expectedNode.getDescription(), actualNode.getDescription()); @@ -245,14 +279,16 @@ public class ToscaParserImpl2Test { } private void compareProperties(Map expectedProperties, Map actualProperties) { - for (Map.Entry property : expectedProperties.entrySet()) { - String expectedValue = property.getValue(); - String key = property.getKey(); - String actualValue = actualProperties.get(key); - Assert.assertEquals(expectedValue, actualValue); - } + JsonAssert.assertJsonEquals(expectedProperties, actualProperties); } + @DataProvider + public Object[][] expectedServiceModel() throws IOException { + return Stream.of(getExpectedServiceModel()) + .map(l -> ImmutableList.of(l.getUuid(), l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + private ToscaParserMockHelper[] getExpectedServiceModel() throws IOException { ToscaParserMockHelper[] mockHelpers = { new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath), @@ -260,15 +296,12 @@ public class ToscaParserImpl2Test { new ToscaParserMockHelper(Constants.crUuid, Constants.crFilePath), new ToscaParserMockHelper(Constants.vfWithAnnotationUuid, Constants.vfWithAnnotationFilePath), new ToscaParserMockHelper(Constants.vfWithVfcGroup, Constants.vfWithVfcGroupFilePath), - new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath) + new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath), +// new ToscaParserMockHelper(Constants.fabricConfigurationUuid, Constants.fabricConfigurationFilePath), +// new ToscaParserMockHelper(Constants.vlanTaggingUuid, Constants.vlanTaggingFilePath), +// new ToscaParserMockHelper(Constants.vnfGroupingUuid, Constants.vnfGroupingFilePath) }; - for (ToscaParserMockHelper mockHelper : mockHelpers) { - InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(mockHelper.getFilePath()); - System.out.println(jsonFile); - String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); - NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class); - mockHelper.setNewServiceModel(newServiceModel1); - } + return mockHelpers; } @@ -284,11 +317,11 @@ public class ToscaParserImpl2Test { public class Constants { public static final String configurationUuid = "ee6d61be-4841-4f98-8f23-5de9da846ca7"; public static final String configurationFilePath = "policy-configuration-csar.JSON"; - static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931"; + static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931"; //service-vf-csar.zip static final String vfWithAnnotationUuid = "f4d84bb4-a416-4b4e-997e-0059973630b9"; static final String vlUuid = "cb49608f-5a24-4789-b0f7-2595473cb997"; static final String crUuid = "76f27dfe-33e5-472f-8e0b-acf524adc4f0"; - static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca"; + static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca"; //service-VdbeSrv-csar.zip // public static final String PNFUuid = "68101369-6f08-4e99-9a28-fa6327d344f3"; static final String vfFilePath = "vf-csar.JSON"; static final String vlFilePath = "vl-csar.JSON"; @@ -297,7 +330,12 @@ public class ToscaParserImpl2Test { static final String vfWithVfcGroupFilePath = "vf-with-vfcInstanceGroups.json"; public static final String configurationByPolicyFalseUuid = "ee6d61be-4841-4f98-8f23-5de9da845544"; public static final String configurationByPolicyFalseFilePath = "policy-configuration-by-policy-false.JSON"; - + //public static final String fabricConfigurationUuid = "12344bb4-a416-4b4e-997e-0059973630b9"; + //public static final String fabricConfigurationFilePath = "fabric-configuration.json"; + //public static final String vlanTaggingUuid = "1837481c-fa7d-4362-8ce1-d05fafc87bd1"; + //public static final String vlanTaggingFilePath = "vlan-tagging.json"; + //public static final String vnfGroupingUuid = "4117a0b6-e234-467d-b5b9-fe2f68c8b0fc"; + //public static final String vnfGroupingFilePath = "vnf-grouping-csar.json"; } @@ -305,7 +343,7 @@ public class ToscaParserImpl2Test { @Test public void testGetNFModuleFromVf() { - ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(); + ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(myUUID); Map vfModulesFromVF = toscaParserImpl2.getVfModulesFromVF(csarHelper, myUUID); @@ -318,7 +356,7 @@ public class ToscaParserImpl2Test { @Test public void testGetVolumeGroupsFromVF() { - ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(); + ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(myUUID); Map volumeGroupsFromVF = toscaParserImpl2.getVolumeGroupsFromVF(csarHelper, myUUID); @@ -328,12 +366,67 @@ public class ToscaParserImpl2Test { )); } - private ISdcCsarHelper getMockedSdcCsarHelper() { +// @DataProvider +// public Object[][] expectedPoliciesTargets() { +// return new Object[][] { +// {Constants.vnfGroupingUuid, newArrayList("groupingservicefortest..ResourceInstanceGroup..0", "groupingservicefortest..ResourceInstanceGroup..1")}, +// {Constants.vfUuid, newArrayList()}, +// {Constants.vlanTaggingUuid, newArrayList()} +// }; +// } +// +// @Test(dataProvider = "expectedPoliciesTargets") +// public void testExtractNamingPoliciesTargets(String uuid, ArrayList expectedTargets) throws AsdcCatalogException, SdcToscaParserException { +// ISdcCsarHelper sdcCsarHelper = toscaParserImpl2.getSdcCsarHelper(getCsarPath(uuid)); +// List policiesTargets = toscaParserImpl2.extractNamingPoliciesTargets(sdcCsarHelper); +// +// assertEquals(expectedTargets, policiesTargets); +// } + + @DataProvider + public Object[][] expectedEcompGeneratedNaming() { + return new Object[][] { + {"nf_naming property false", "nf_naming", "false", "false"}, + {"nf_naming property true", "nf_naming", "true", "true"}, + {"nf_naming property doesn't exist", "nf_naming", null, "false"}, + {"exVL_naming property false", "exVL_naming", "false", "false"}, + {"exVL_naming property true", "exVL_naming", "true", "true"}, + {"exVL_naming property doesn't exist", "exVL_naming", null, "false"}, + }; + } + + @Test(dataProvider = "expectedEcompGeneratedNaming") + public void testEcompGeneratedNamingForNode(String description, String parentProperty, String ecompNamingProperty, String expectedResult) { + Property property = mock(Property.class); + when(property.getName()).thenReturn("any_key"); + when(property.getValue()).thenReturn("any_value"); + ArrayList properties = newArrayList(property); + + if (ecompNamingProperty != null) { + Property nfNamingProperty = mock(Property.class); + when(nfNamingProperty.getName()).thenReturn(parentProperty); + when(nfNamingProperty.getValue()).thenReturn(ImmutableMap.of(ECOMP_GENERATED_NAMING_PROPERTY, ecompNamingProperty)); + properties.add(nfNamingProperty); + } + + NodeTemplate node = mock(NodeTemplate.class); + when(node.getName()).thenReturn("node_name"); + when(node.getPropertiesObjects()).thenReturn(properties); + + String result = ToscaNamingPolicy.getEcompNamingValueForNode(node, parentProperty); + assertEquals(expectedResult, result); + } + + public static ISdcCsarHelper getMockedSdcCsarHelper(String myUUID) { ISdcCsarHelper csarHelper = mock(ISdcCsarHelper.class); Group withVol = createMinimalGroup("withVol", true); Group withoutVol = createMinimalGroup("withoutVol", false); + when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( + "instantiationType", "A-La-Carte" + ))); + when(csarHelper.getVfModulesByVf(myUUID)) .thenReturn(ImmutableList.of(withVol, withoutVol)); @@ -379,7 +472,7 @@ public class ToscaParserImpl2Test { try { log.info(String.format("Built a group: %s", - (new com.fasterxml.jackson.databind.ObjectMapper()) + (new ObjectMapper()) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .writeValueAsString(group) )); diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java new file mode 100644 index 00000000..af9029e5 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java @@ -0,0 +1,120 @@ +package org.onap.vid.asdc.parser; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.jetbrains.annotations.NotNull; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.AsdcClient; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.asdc.local.LocalAsdcClient; +import org.onap.vid.asdc.parser.ServiceModelInflator.Names; +import org.onap.vid.model.ServiceModel; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; + +import static java.util.Collections.emptyMap; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +public class ToscaParserInflatorTest { + + private static final Logger log = LogManager.getLogger(ToscaParserInflatorTest.class); + + @InjectMocks + private ToscaParserImpl2 toscaParserImpl2; + + @Mock + private VidNotionsBuilder vidNotionsBuilder; + + private AsdcClient asdcClient; + + @BeforeClass + void init() throws IOException { + + final InputStream asdcServicesFile = this.getClass().getClassLoader().getResourceAsStream("sdcservices.json"); + + final JSONTokener jsonTokener = new JSONTokener(IOUtils.toString(asdcServicesFile)); + final JSONObject sdcServicesCatalog = new JSONObject(jsonTokener); + + asdcClient = new LocalAsdcClient.Builder().catalog(sdcServicesCatalog).build(); + + } + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + + @Test + public void inflateFabricConfigurationModel_allIdsAreGiven() throws Exception { + final String fabricConfigurationUuid = "90fe6842-aa76-4b68-8329-5c86ff564407"; + final Map inflated = inflateModelByUuid(fabricConfigurationUuid); + + // see vf-with-annotation-csar.json + assertThat(inflated, is(ImmutableMap.of( + "8df1892c-377d-460b-8a8d-fc8a116e9d92", doubleName("201712-488_ADIOD-vPE-1 0"), + "8d521692-7661-4296-b77e-a2058bb62e87", new Names("201712488AdiodVpe1..ADIOD_vRE_BV..module-1", "201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1"), + "79fbee20-7fba-4166-ae4b-b94c869e7d8b", new Names("201712488AdiodVpe1..ADIOD_vPFE_BV..module-2","201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vPFE_BV..module-2"), + "806505b8-7a7c-47a2-acef-b4d26fe95a92", new Names("201712488AdiodVpe1..ADIOD_base_vPE_BV..module-0","201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_base_vPE_BV..module-0") + ))); + } + + + @Test + public void inflateVlModel_allIdsAreGiven() throws Exception { + final String fabricConfigurationUuid = "cb49608f-5a24-4789-b0f7-2595473cb997"; + final Map inflated = inflateModelByUuid(fabricConfigurationUuid); + + // see vl-csar.json + assertThat(inflated, is(ImmutableMap.of( + "af584529-d7f0-420e-a6f3-c38b689c030f", doubleName("ExtVL 0") + ))); + } + + @NotNull + private Names doubleName(String modelCustomizationName) { + return new Names(modelCustomizationName, modelCustomizationName); + } + + @Test + public void inflateConfigurationByPolicyFalseUuid_allIdsAreGiven() throws Exception { + final String configurationByPolicyFalseUuid = "ee6d61be-4841-4f98-8f23-5de9da845544"; + final Map inflated = inflateModelByUuid(configurationByPolicyFalseUuid); + + // see policy-configuration-by-policy-false.json + // no relevant model here + assertThat(inflated, is(emptyMap())); + } + + private Map inflateModelByUuid(String fabricConfigurationUuid) throws SdcToscaParserException, AsdcCatalogException { + ServiceModel actualServiceModel = serviceModelByUuid(fabricConfigurationUuid); + + ServiceModelInflator serviceModelInflator = new ServiceModelInflator(); + return serviceModelInflator.toNamesByVersionId(actualServiceModel); + } + + private ServiceModel serviceModelByUuid(String uuid) throws SdcToscaParserException, AsdcCatalogException { + final Path modelPath = asdcClient.getServiceToscaModel(UUID.fromString(uuid)); + final Service modelMetadata = asdcClient.getService(UUID.fromString(uuid)); + + return toscaParserImpl2.makeServiceModel(modelPath, modelMetadata); + } + + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java new file mode 100644 index 00000000..26fb2cf1 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java @@ -0,0 +1,290 @@ +package org.onap.vid.asdc.parser; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Property; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.vid.model.*; +import org.onap.vid.properties.Features; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.LinkedHashMap; +import java.util.UUID; +import java.util.function.BiConsumer; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; + +public class VidNotionsBuilderTest { + + @InjectMocks + VidNotionsBuilder vidNotionsBuilder; + + @Mock + private FeatureManager featureManagerMock; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @AfterMethod + public void reset() { + Mockito.reset(featureManagerMock); + } + + @Test + public void VLNetworkWithPropertyNetworkTechnologyOVS_UIHintIsPositive() { + ISdcCsarHelper csarHelper = mockForNonLegacyInstantiationUI(); + + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS)); + assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper) , is(VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL)); + } + + @NotNull + protected ISdcCsarHelper mockForNonLegacyInstantiationUI() { + ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + + NodeTemplate nodeTemplate = mock(NodeTemplate.class); + + when(nodeTemplate.getProperties()).thenReturn(new LinkedHashMap<>(ImmutableMap.of( + "dummy_val", mock(Property.class), + "network_technology", new Property(Pair.of("network_technology","ovs")) + ))); + + when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); + when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true); + return csarHelper; + } + + @DataProvider + public static Object[][] anyAlacarteDataProvider() { + return new Object[][] { + {"A-La-Carte", VidNotions.InstantiationUI.ANY_ALACARTE_NEW_UI}, + {"Macro", VidNotions.InstantiationUI.LEGACY}, + }; + } + + @Test(dataProvider = "anyAlacarteDataProvider") + public void FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI_is_active_UIHintIsPositive(String instantiationType, VidNotions.InstantiationUI expectedInstantiationUI) { + when(featureManagerMock.isActive(Features.FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI)).thenReturn(true); + ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( + "instantiationType", instantiationType + ))); + NodeTemplate nodeTemplate = mock(NodeTemplate.class); + + when(nodeTemplate.getProperties()).thenReturn(new LinkedHashMap<>(ImmutableMap.of( + "dummy_val", mock(Property.class), + "network_technology", new Property(Pair.of("network_technology","ovs")) + ))); + + when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); + + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(expectedInstantiationUI)); + } + + @Test + public void VLNetworkWithPropertyNetworkTechnologyNot5G_UIHintIsNegative() { + ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + + NodeTemplate nodeTemplate = mock(NodeTemplate.class); + + when(nodeTemplate.getProperties()).thenReturn(new LinkedHashMap<>(ImmutableMap.of( + "dummy_val", mock(Property.class), + "network_technology", new Property(Pair.of("network_technology","old_value")) + ))); + + when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); + + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper) , is(VidNotions.ModelCategory.OTHER)); + } + + @Test + public void withoutMocks_givenZippedToscaFile_hasAnyNetworkWithPropertyEqualsToAnyOfYieldsTrue() throws SdcToscaParserException { + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(getClass().getClassLoader().getResource("service-vl-csar.zip").getPath(),false); + + assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); + assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "unexpected_property_name"), is(false)); + assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "network_technology","Standard-SR-IOV"), is(true)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY)); + } + + //@Test + //public void withoutMocks_givenZippedToscaFile_hasFabricConfigurationYieldsTrue() throws SdcToscaParserException { + // SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + // ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(getClass().getClassLoader().getResource("service-fabric-configuration.zip").getPath(),false); + // + // assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); + // assertThat(vidNotionsBuilder.hasFabricConfiguration(csarHelper), is(true)); + // assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY)); + //} + + + @Test + public void uuidIsExactly1ffce89fEtc_UIHintIsPositive() { + ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + + when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( + "UUID", "95eb2c44-bff2-4e8b-ad5d-8266870b7717" + ))); + when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de)); + } + + + @DataProvider + public static Object[][] trueAndFalse() { + return new Object[][] {{true}, {false}}; + } + + @Test(dataProvider = "trueAndFalse") + public void buildVidNotions_nullByFlag(boolean flagValue) { + ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + + when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(flagValue); + assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, null), hasProperty("instantiationUI", is(VidNotions.InstantiationUI.LEGACY))); + } + + @DataProvider + public static Object[][] ServiceRoleTypesDataProvider() { + return new Object[][] { + {"gROUPING", VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING}, + {"", VidNotions.InstantiationUI.LEGACY}, + }; + } + + @Test(dataProvider = "ServiceRoleTypesDataProvider") + public void testGetViewEditUITypeForResourceGroup(String serviceRole, VidNotions.InstantiationUI expectedViewEditUI) { + when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(true); + when(featureManagerMock.isActive(Features.FLAG_1902_VNF_GROUPING)).thenReturn(true); + ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( + "serviceRole", serviceRole + ))); + + assertThat(vidNotionsBuilder.suggestViewEditUI(csarHelper, null), is(expectedViewEditUI)); + } + + @DataProvider + public static Object[][] macroToViewEditDataProvider() { + return new Object[][] { + {"macro service + not excluded + needed flags are open", true, false, true, true, VidNotions.InstantiationUI.MACRO_SERVICE}, + {"not macro service", false, false, true, true, VidNotions.InstantiationUI.LEGACY}, + {"macro that shall be excluded because it has pnf", true, true, true, true, VidNotions.InstantiationUI.LEGACY}, + {"macro service + FLAG_ASYNC_INSTANTIATION off", true, false, false, true, VidNotions.InstantiationUI.LEGACY}, + {"macro service + FLAG_1902_NEW_VIEW_EDIT off", true, false, true, false, VidNotions.InstantiationUI.LEGACY}, + }; + } + + @Test(dataProvider="macroToViewEditDataProvider") + public void whenServiceIsMacro_viewEditIsRight( + String testDescription, + boolean isMacro, + boolean isExcluded, + boolean isFlagAsyncInstantiationActive, + boolean isFlag1902NewViewEdit, + VidNotions.InstantiationUI expectedViewEditUi) { + + ISdcCsarHelper csarHelper = mock(ISdcCsarHelper.class); + ServiceModel serviceModel = mock(ServiceModel.class); + + //mock for is Macro + String instantiationType = isMacro ? ToscaParserImpl2.Constants.MACRO : ToscaParserImpl2.Constants.A_LA_CARTE; + Service service = mock(Service.class); + when(serviceModel.getService()).thenReturn(service); + when(service.getInstantiationType()).thenReturn(instantiationType); + when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(isFlagAsyncInstantiationActive); + when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit); + + //mock for isExcluded + if (isExcluded) { + when(serviceModel.getPnfs()).thenReturn(ImmutableMap.of("a", mock(Node.class))); + } + + VidNotions.InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); + assertEquals(expectedViewEditUi, result); + } + + @DataProvider + public static Object[][] instantiationUIToViewEditDataProvider() { + return new Object[][] { + {"network cloud(5G) service + needed flags are open", true, true, true, VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS}, + {"mocked service + needed flags are open", false, true, true, VidNotions.InstantiationUI.LEGACY}, + {"network cloud(5G) service + FLAG_ASYNC_INSTANTIATION is off", true, false, true, VidNotions.InstantiationUI.LEGACY}, + {"network cloud(5G) service + FLAG_1902_NEW_VIEW_EDIT is off", true, true, false, VidNotions.InstantiationUI.LEGACY}, + }; + } + + + @Test(dataProvider="instantiationUIToViewEditDataProvider") + public void whenInstantiationUIIsNotLegacy_viewEditIsRight( + String testDescription, + boolean isInstantiationUINotLegacy, + boolean isFlagAsyncInstantiationActive, + boolean isFlag1902NewViewEdit, + VidNotions.InstantiationUI expectedViewEditUi) { + + ISdcCsarHelper csarHelper = isInstantiationUINotLegacy ? mockForNonLegacyInstantiationUI() : mock(ISdcCsarHelper.class); + when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(isFlagAsyncInstantiationActive); + when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit); + + ServiceModel serviceModel = mock(ServiceModel.class); + Service service = mock(Service.class); + when(serviceModel.getService()).thenReturn(service); + when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.A_LA_CARTE); + + VidNotions.InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); + assertEquals(expectedViewEditUi, result); + } + + @DataProvider + public static Object[][] mockerForMacroExcluded() { + return new Object[][] { + {"service with pnfs", (BiConsumer) (serviceModel, fm)->when(serviceModel.getPnfs()).thenReturn(ImmutableMap.of("a", mock(Node.class))), true}, + {"service with collection resource", (BiConsumer) (serviceModel, fm)->when(serviceModel.getCollectionResource()).thenReturn(ImmutableMap.of("a", mock(CR.class))), true}, + {"service with network + FLAG_NETWORK_TO_ASYNC_INSTANTIATION false ", (BiConsumer) (serviceModel, fm)->{ + when(serviceModel.getNetworks()).thenReturn(ImmutableMap.of("a", mock(Network.class))); + when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(false);} + , true}, + {"service with network + FLAG_NETWORK_TO_ASYNC_INSTANTIATION true", (BiConsumer) (serviceModel, fm)->{ + when(serviceModel.getNetworks()).thenReturn(ImmutableMap.of("a", mock(Network.class))); + when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(true);} + , false}, + {"empty service + FLAG_NETWORK_TO_ASYNC_INSTANTIATION false", (BiConsumer) (serviceModel, fm)->when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(false), false}, + }; + } + + @Test(dataProvider="mockerForMacroExcluded") + public void testIsMacroExcludedFromAsyncFlow(String testDescription, BiConsumer mocker, boolean shallBeExcluded) { + ServiceModel serviceModel = mock(ServiceModel.class); + mocker.accept(serviceModel, featureManagerMock); + assertEquals(shallBeExcluded, vidNotionsBuilder.isMacroExcludedFromAsyncFlow(serviceModel)); + } + + + + + + +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java index 113b9f1f..11c02fe9 100644 --- a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java @@ -20,11 +20,11 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.equalTo; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; -import static org.hamcrest.MatcherAssert.assertThat; public class AaiServiceTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java b/vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java deleted file mode 100644 index 75bb0198..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/client/HttpsBasicClientTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.onap.vid.client; - -import org.junit.Test; - -public class HttpsBasicClientTest { - - private HttpsBasicClient createTestSubject() { - return new HttpsBasicClient(); - } - - @Test - public void testGetClient() throws Exception { - - // default test - HttpsBasicClient.getClient(); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java index eb9239e1..ba8060da 100644 --- a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java @@ -25,20 +25,19 @@ public class DataSourceConfig { public LocalSessionFactoryBean sessionFactory(DataSource dataSource) { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource); - //I used this class org.openecomp.portalsdk.core.conf.HibernateConfiguration to learn how to config the session factory + //I used this class org.onap.portalsdk.core.conf.HibernateConfiguration to learn how to config the session factory // and use the following url for actual h2 properties //https://github.com/levi-putna/Hibernate-H2-Example/blob/master/hibernate-h2-example/src/hibernate.cfg.xml Properties properties = getH2Properties(); - properties.put("hibernate.default_schema", "PUBLIC"); properties.put("connection.pool_size", 10); properties.put("cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider"); properties.put("hibernate.show_sql", false); properties.put("hbm2ddl.auto", "create"); properties.put("hibernate.hbm2ddl.auto", "create"); - sessionFactory.setHibernateProperties(properties); sessionFactory.setPackagesToScan("org.onap"); + sessionFactory.setHibernateProperties(properties); return sessionFactory; } @@ -55,6 +54,7 @@ public class DataSourceConfig { public Properties getH2Properties() { Properties properties = new Properties(); properties.put("dialect", "org.hibernate.dialect.H2Dialect"); + properties.put("hibernate.default_schema", "PUBLIC"); return properties; } @@ -64,6 +64,7 @@ public class DataSourceConfig { properties.put("connection.url", "jdbc:sqlite:memory:myDb"); properties.put("connection.username", "sa"); properties.put("connection.password", "sa"); + properties.put("hibernate.default_schema", "PUBLIC"); properties.put("dialect", "com.enigmabridge.hibernate.dialect.SQLiteDialect"); return properties; } diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java index c1ac6a21..9cb9b33d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java +++ b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java @@ -1,57 +1,27 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.config; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; import org.hibernate.SessionFactory; import org.mockito.Mockito; import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.vid.aai.AaiOverTLSClient; -import org.onap.vid.aai.AaiOverTLSClientInterface; -import org.onap.vid.aai.AaiOverTLSPropertySupplier; +import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.aai.util.SSLContextProvider; +import org.onap.vid.aai.util.ServletRequestHelper; import org.onap.vid.aai.util.SystemPropertyHelper; -import org.onap.vid.client.SyncRestClient; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobsBrokerService; -import org.onap.vid.job.command.InProgressStatusCommand; -import org.onap.vid.job.command.JobCommandFactory; -import org.onap.vid.job.command.ServiceInstantiationCommand; +import org.onap.vid.job.command.*; import org.onap.vid.job.impl.JobAdapterImpl; import org.onap.vid.job.impl.JobWorker; import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; import org.onap.vid.mso.RestMsoImplementation; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.services.AsyncInstantiationBusinessLogicImpl; -import org.onap.vid.services.AuditService; -import org.onap.vid.services.AuditServiceImpl; +import org.onap.vid.services.*; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; +import org.togglz.core.manager.FeatureManager; @Configuration public class JobCommandsConfigWithMockedMso { @@ -67,8 +37,23 @@ public class JobCommandsConfigWithMockedMso { } @Bean - public HttpsAuthClient httpsAuthClientFactory(){ - return new HttpsAuthClient("some random path", new SystemPropertyHelper(), new SSLContextProvider()); + public SSLContextProvider sslContextProvider() { + return new SSLContextProvider(); + } + + @Bean + public SystemPropertyHelper systemPropertyHelper() { + return new SystemPropertyHelper(); + } + + @Bean + public ServletRequestHelper servletRequestHelper() { + return new ServletRequestHelper(); + } + + @Bean + public HttpsAuthClient httpsAuthClientFactory(SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider, FeatureManager featureManager){ + return new HttpsAuthClient("some random path", systemPropertyHelper, sslContextProvider, featureManager); } @Bean @@ -90,31 +75,8 @@ public class JobCommandsConfigWithMockedMso { } @Bean - public AaiOverTLSClientInterface AaiOverTLSClient(){ - io.joshworks.restclient.http.mapper.ObjectMapper objectMapper = new io.joshworks.restclient.http.mapper.ObjectMapper() { - - ObjectMapper om = new ObjectMapper(); - - @Override - public T readValue(String s, Class aClass) { - try { - return om.readValue(s, aClass); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public String writeValue(Object o) { - try { - return om.writeValueAsString(o); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - } - }; - - return new AaiOverTLSClient(new SyncRestClient(objectMapper), new AaiOverTLSPropertySupplier()); + public FeatureManager featureManager() { + return Mockito.mock(FeatureManager.class); } @Bean @@ -122,25 +84,130 @@ public class JobCommandsConfigWithMockedMso { JobAdapter jobAdapter, JobsBrokerService jobsBrokerService, SessionFactory sessionFactory, - AaiOverTLSClientInterface aaiOverTLSClientInterface) { - return new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiOverTLSClientInterface); + AaiClientInterface aaiClient, + FeatureManager featureManager, + CloudOwnerService cloudOwnerService) { + return new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient, featureManager, cloudOwnerService); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public MacroServiceInstantiationCommand serviceInstantiationCommand() { + return new MacroServiceInstantiationCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public ServiceInProgressStatusCommand inProgressStatusCommand() { + return new ServiceInProgressStatusCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public ALaCarteServiceInstantiationCommand aLaCarteServiceInstantiationCommand() { + return new ALaCarteServiceInstantiationCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public ALaCarteServiceCommand aLaCarteServiceCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + JobsBrokerService jobsBrokerService, + MsoResultHandlerService msoResultHandlerService, + JobAdapter jobAdapter, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + RestMsoImplementation restMso) { + return new ALaCarteServiceCommand(inProgressStatusService, watchChildrenJobsBL, asyncInstantiationBusinessLogic, jobsBrokerService, msoResultHandlerService, jobAdapter, restMso); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public InstanceGroupCommand instanceGroupCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + MsoResultHandlerService msoResultHandlerService, InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + RestMsoImplementation restMso) { + return new InstanceGroupCommand(asyncInstantiationBusinessLogic, restMso, msoResultHandlerService, inProgressStatusService, watchChildrenJobsBL); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public VnfInstantiationCommand vnfInstantiationCommand() { + return new VnfInstantiationCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public VolumeGroupInstantiationCommand volumeGroupInstantiationCommand() { + return new VolumeGroupInstantiationCommand(); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public ServiceInstantiationCommand serviceInstantiationCommand() { - return new ServiceInstantiationCommand(); + public WatchingCommandBaseModule watchingCommandBaseModule() { + return new WatchingCommandBaseModule(); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public InProgressStatusCommand inProgressStatusCommand() { - return new InProgressStatusCommand(); + public VolumeGroupInProgressStatusCommand volumeGroupInProgressStatusCommand() { + return new VolumeGroupInProgressStatusCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public VfmoduleInstantiationCommand vfmoduleInstantiationCommand() { + return new VfmoduleInstantiationCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public WatchingCommand watchingCommandCommand() { + return new WatchingCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public ResourceInProgressStatusCommand resourceInProgressStatusCommand() { + return new ResourceInProgressStatusCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public VnfInProgressStatusCommand vnfInProgressStatusCommand() { + return new VnfInProgressStatusCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public InstanceGroupInstantiationCommand instanceGroupInstantiationCommand() { + return new InstanceGroupInstantiationCommand(); + } + + @Bean + public AuditService auditService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation msoClient) { + return new AuditServiceImpl(asyncInstantiationBL, msoClient); + } + + @Bean + public InProgressStatusService inProgressStatusService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation restMso, AuditService auditService) { + return new InProgressStatusService(asyncInstantiationBL, restMso, auditService); + } + + @Bean + public MsoResultHandlerService rootCommandService(AsyncInstantiationBusinessLogic asyncInstantiationBL, AuditService auditService) { + return new MsoResultHandlerService(asyncInstantiationBL, auditService); + } + + @Bean + public CommandUtils commandUtils() { + return Mockito.mock(CommandUtils.class); } @Bean - public AuditService auditService() { - return new AuditServiceImpl(); + public WatchChildrenJobsBL watchChildrenJobsService(DataAccessService dataAccessService) { + return new WatchChildrenJobsBL(dataAccessService); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java index 4076b3de..d86ab78a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java @@ -7,9 +7,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.vid.aai.AaiResponseTranslator; -import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; -import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk; -import org.onap.vid.controllers.AaiController; import org.onap.vid.services.AaiService; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -19,7 +16,6 @@ import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; - public class AaiControllerTest { @InjectMocks @@ -36,9 +32,9 @@ public class AaiControllerTest { @Test public void getPortMirroringConfigData_givenThreeIds_ReturnsThreeResults() { - final PortMirroringConfigDataOk toBeReturnedForA = new PortMirroringConfigDataOk("foobar"); - final PortMirroringConfigDataError toBeReturnedForB = new PortMirroringConfigDataError("foo", "{ baz: qux }"); - final PortMirroringConfigDataOk toBeReturnedForC = new PortMirroringConfigDataOk("corge"); + final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForA = new AaiResponseTranslator.PortMirroringConfigDataOk("foobar"); + final AaiResponseTranslator.PortMirroringConfigDataError toBeReturnedForB = new AaiResponseTranslator.PortMirroringConfigDataError("foo", "{ baz: qux }"); + final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForC = new AaiResponseTranslator.PortMirroringConfigDataOk("corge"); Mockito .doReturn(toBeReturnedForA) @@ -57,4 +53,4 @@ public class AaiControllerTest { -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java new file mode 100644 index 00000000..9a5ee3ec --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java @@ -0,0 +1,120 @@ +package org.onap.vid.controller; + +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.util.ServiceInstanceStandardQuery; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.model.Service; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.VidNotions; +import org.onap.vid.model.VidNotions.ModelCategory; +import org.onap.vid.properties.Features; +import org.onap.vid.services.VidService; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.UUID; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; + +public class AaiServiceInstanceStandardQueryControllerTest { + + @InjectMocks + private AaiServiceInstanceStandardQueryController aaiServiceInstanceStandardQueryController; + + @Mock + private FeatureManager featureManager; + + @Mock + private VidService sdcService; + + @Mock(answer = Answers.RETURNS_MOCKS) + private ServiceInstanceStandardQuery serviceInstanceStandardQuery; + + //Don't use initMocks with @BeforeMethod + //because AaiServiceInstanceStandardQueryController contains final members that can not be injected twice + //See https://stackoverflow.com/questions/20046210/mockito-injectmocks-strange-behaviour-with-final-fields?answertab=active#tab-top + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @AfterMethod + public void resetMocks() { + reset(sdcService, featureManager, serviceInstanceStandardQuery); + } + + @Test + public void getNetworksToVlansByServiceInstance_given5G_PROVIDER_NETWORK_aaiIsAccessed() throws AsdcCatalogException { + // - turn on FLAG_PRESENT_PROVIDER_NETWORKS + // - mock an model with 5G_PROVIDER_NETWORK + // - request it's AAI network->vlan mapping + // - assert that AAI was accessed + + when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true); + + final UUID randomModelUuid = UUID.randomUUID(); + mockServiceModel(ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL, randomModelUuid); + + doGetNetworksToVlansByServiceInstance(randomModelUuid); + + verify(serviceInstanceStandardQuery).fetchServiceInstance(any(), any(), any()); + } + + @Test + public void getNetworksToVlansByServiceInstance_givenNon5G_PROVIDER_NETWORK_aaiIsNotAccessed() throws AsdcCatalogException { + // - turn on FLAG_PRESENT_PROVIDER_NETWORKS + // - mock an model without 5G_PROVIDER_NETWORK (i.e. OTHER) + // - request it's AAI network->vlan mapping + // - assert that AAI was not accessed + // - empty result was responded + + when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true); + + final UUID randomModelUuid = UUID.randomUUID(); + mockServiceModel(ModelCategory.OTHER, randomModelUuid); + + assertThat(doGetNetworksToVlansByServiceInstance(randomModelUuid).serviceNetworks, hasSize(0)); + verifyZeroInteractions(serviceInstanceStandardQuery); + } + + @Test + public void isModelOf5g_givenServiceWithFabricConfiguration_returnTrue() throws AsdcCatalogException { + final UUID randomModelUuid = UUID.randomUUID(); + mockServiceModel(ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL, randomModelUuid, VidNotions.InstantiationUI.SERVICE_WITH_FABRIC_CONFIGURATION); + + assertTrue(aaiServiceInstanceStandardQueryController.isModelOf5g(randomModelUuid)); + } + + private void mockServiceModel(ModelCategory modelCategory, UUID randomModelUuid) throws AsdcCatalogException { + mockServiceModel(modelCategory, randomModelUuid, VidNotions.InstantiationUI.LEGACY); + } + + private void mockServiceModel(ModelCategory modelCategory, UUID randomModelUuid, VidNotions.InstantiationUI instantiationUI) throws AsdcCatalogException { + ServiceModel mockedModel = mock(ServiceModel.class); + Service mockedService = mock(Service.class); + when(mockedModel.getService()).thenReturn(mockedService); + when(mockedService.getVidNotions()).thenReturn( + new VidNotions(instantiationUI, modelCategory, VidNotions.InstantiationUI.LEGACY) + ); + + when(sdcService.getService(randomModelUuid.toString())).thenReturn(mockedModel); + } + + private AaiServiceInstanceStandardQueryController.VlansByNetworksHierarchy doGetNetworksToVlansByServiceInstance(UUID randomModelUuid) throws AsdcCatalogException { + return aaiServiceInstanceStandardQueryController.getNetworksToVlansByServiceInstance( + new MockHttpServletRequest(), + randomModelUuid, + "my global customer id", + "my service type", + "my instance id"); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java new file mode 100644 index 00000000..420b61ed --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java @@ -0,0 +1,448 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.vid.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.google.common.collect.ImmutableList; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.log4j.BasicConfigurator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.vid.changeManagement.*; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.mso.rest.InstanceIds; +import org.onap.vid.mso.rest.Request; +import org.onap.vid.mso.rest.RequestStatus; +import org.onap.vid.services.ChangeManagementService; +import org.onap.vid.services.WorkflowService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.multipart.MultipartFile; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.Scanner; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.isA; +import static org.onap.vid.controller.ChangeManagementController.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class ChangeManagementControllerTest { + + private static final String FILE_NAME = "file"; + private static final String GET_VNF_WORKFLOW_RELATION_URL = + "/" + CHANGE_MANAGEMENT + "/" + GET_VNF_WORKFLOW_RELATION; + private static final String WORKFLOW_URL = "/" + CHANGE_MANAGEMENT + "/workflow"; + private static final String WORKFLOW_NAME_URL = WORKFLOW_URL + "/{name}"; + private static final String MSO_URL = "/" + CHANGE_MANAGEMENT + "/mso"; + private static final String UPLOAD_CONFIG_UPDATE_FILE_URL = "/" + CHANGE_MANAGEMENT + "/uploadConfigUpdateFile"; + private static final String SCHEDULER_URL = "/" + CHANGE_MANAGEMENT + "/scheduler"; + private static final String SCHEDULER_BY_SCHEDULE_ID_URL = "/" + CHANGE_MANAGEMENT + SCHEDULER_BY_SCHEDULE_ID; + private static final String VNF_WORKFLOW_RELATION_URL = "/" + CHANGE_MANAGEMENT + "/" + VNF_WORKFLOW_RELATION; + private static final String VNFS = "vnfs"; + + private static final String FAILED_TO_GET_MSG = "Failed to get workflows for vnf"; + private static final String FAILED_TO_ADD_MSG = "Failed to add vnf to workflow relation"; + private static final String FAILED_TO_GET_ALL_MSG = "Failed to get all vnf to workflow relations"; + private static final String FAILED_TO_DELETE_MSG = "Failed to delete vnf from workflow relation"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private ChangeManagementController controller; + private MockMvc mockMvc; + @Mock + private WorkflowService workflowService; + @Mock + private ChangeManagementService changeManagementService; + @Mock + private Response mockResponse; + @Mock + private Response.StatusType statusType; + private ClassLoader classLoader = getClass().getClassLoader(); + private final String CHANGE_MANAGEMENT_REQUEST_JSON = getRequestContent("change-management-request.json"); + private final String GET_VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent( + "get-vnf-workflow-relation-request.json"); + private final String VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent("vnf-workflow-relation-request.json"); + + @Before + public void setUp() { + controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception { + + Collection givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3"); + Collection resultWorkflows = ImmutableList.of("workflow1", "workflow2"); + + given( + workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other)))) + .willReturn(resultWorkflows); + + mockMvc.perform(get(WORKFLOW_URL) + .param(VNFS, StringUtils.join(givenVnfs, ","))) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows))); + } + + @Test + public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue() + throws Exception { + + Collection requests = ImmutableList.of( + createRequest("network-instance-id-1", "status-message-1"), + createRequest("network-instance-id-2", "status-message-2")); + + given(changeManagementService.getMSOChangeManagements()).willReturn(requests); + + mockMvc.perform(get(MSO_URL)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(requests))); + } + + @Test + public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception { + + String vnfName = "vnfName1"; + String jsonBody = "{'param1': 'paramparam'}"; + + given(changeManagementService.doChangeManagement( + argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName))) + .willReturn(ResponseEntity.ok().body(jsonBody)); + + mockMvc.perform(post(WORKFLOW_NAME_URL, vnfName) + .contentType(MediaType.APPLICATION_JSON) + .content(CHANGE_MANAGEMENT_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(jsonBody)); + } + + @Test + public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception { + + String jsonString = "{'param1': 'paramparam'}"; + byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); + MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); + + given(changeManagementService + .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)))) + .willReturn(jsonString); + + mockMvc.perform(MockMvcRequestBuilders + .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) + .file(file)) + .andExpect(status().isOk()) + .andExpect(content().json(jsonString)); + } + + @Test + public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException() + throws Exception { + + byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); + MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); + + given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value()); + given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value()); + given(mockResponse.getStatusInfo()).willReturn(statusType); + + WebApplicationException exception = new WebApplicationException(mockResponse); + + willThrow(exception).given(changeManagementService) + .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))); + + mockMvc.perform(MockMvcRequestBuilders + .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) + .file(file)) + .andExpect(status().isNotFound()) + .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception)))); + } + + @Test + public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() + throws Exception { + + byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); + MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); + + RuntimeException exception = new RuntimeException("runtime exception message"); + + willThrow(exception).given(changeManagementService) + .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))); + + mockMvc.perform(MockMvcRequestBuilders + .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) + .file(file)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception)))); + } + + @Test + public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + ArrayNode array = mapper.createArrayNode(); + array.add("element1"); + array.add("element2"); + + given(changeManagementService.getSchedulerChangeManagements()).willReturn(array); + + mockMvc.perform(get(SCHEDULER_URL)) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(array))); + } + + @Test + public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + String id = "schedule-id-1"; + Pair pair = new ImmutablePair<>("myString", HttpStatus.OK.value()); + + given(changeManagementService.deleteSchedule(id)).willReturn(pair); + + mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id)) + .andExpect(status().isOk()); + } + + @Test + public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception { + + String id = "schedule-id-1"; + Pair pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value()); + + given(changeManagementService.deleteSchedule(id)).willReturn(pair); + + mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id)) + .andExpect(status().isNotFound()); + } + + @Test + public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + ImmutableList elements = ImmutableList.of("workflow1", "workflow2"); + GetWorkflowsResponse response = new GetWorkflowsResponse(); + response.setWorkflows(elements); + + given(changeManagementService + .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)))) + .willReturn(elements); + + mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception { + + String errorMsg = "not found"; + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg)); + + willThrow(new NotFoundException(errorMsg)) + .given(changeManagementService) + .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))); + + mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isNotFound()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class)); + + mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(); + + given(changeManagementService + .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON)))) + .willReturn(response); + + mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request, + VNF_WORKFLOW_RELATION_REQUEST_JSON))); + + mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows(); + workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2")); + VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows)); + + given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response); + + mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() + throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).getAllVnfWorkflowRelations(); + + mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc")); + + given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request, + VNF_WORKFLOW_RELATION_REQUEST_JSON)))) + .willReturn(response); + + mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() + throws Exception { + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request, + VNF_WORKFLOW_RELATION_REQUEST_JSON))); + + mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + private boolean matches(T request, String expectedJson) { + try { + return objectMapper.writeValueAsString(request).equals(expectedJson); + } catch (JsonProcessingException e) { + System.out.println("Exception occurred: " + e.getMessage()); + } + return false; + } + + private ArgumentMatcher multipartFileMatcher(MultipartFile otherFile) { + return other -> { + try { + return other.getName().equals(otherFile.getName()) + && other.getSize() == otherFile.getSize() + && Arrays.equals(other.getBytes(), otherFile.getBytes()); + } catch (IOException e) { + System.out.println("IOException occurred: " + e.getMessage()); + } + return false; + }; + } + + private Request createRequest(String networkInstanceId, String statusMessage) { + Request req = new Request(); + InstanceIds instanceIds = new InstanceIds(); + instanceIds.setNetworkInstanceId(networkInstanceId); + + RequestStatus requestStatus = new RequestStatus(); + requestStatus.setStatusMessage(statusMessage); + + req.setInstanceIds(instanceIds); + req.setRequestStatus(requestStatus); + + return req; + } + + private String getRequestContent(String filename) { + InputStream inputStream = classLoader.getResourceAsStream(filename); + return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", ""); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java index 113bf2bf..1b22d773 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java @@ -19,7 +19,6 @@ import static org.mockito.ArgumentMatchers.any; /** * Created by amichai on 16/05/2018. */ -@Test public class ClientCredentialsFilterTest { @DataProvider diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java new file mode 100644 index 00000000..4f915ec4 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java @@ -0,0 +1,101 @@ +package org.onap.vid.controller; + +import org.apache.log4j.BasicConfigurator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.dao.FnAppDoaImpl; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.sql.SQLException; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class HealthCheckControllerTest { + + private static final String ERROR_MESSAGE = "error message"; + private HealthCheckController testSubject; + private MockMvc mockMvc; + + @Mock + private FnAppDoaImpl fnAppDoa; + + @Before + public void setUp() { + testSubject = new HealthCheckController(fnAppDoa); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(testSubject).build(); + } + + @Test + public void getHealthCheckStatusForIDNS_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception { + databaseConnectionEstablished(); + mockMvc.perform(get("/healthCheck") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(OK.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check succeeded")); + } + + @Test + public void getHealthCheckStatusForIDNS_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception { + databaseNotAccessible(); + mockMvc.perform(get("/healthCheck") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE)); + } + + @Test + public void getHealthCheck_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception { + databaseConnectionEstablished(); + mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(OK.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check succeeded")) + .andExpect(jsonPath("$.date").isString()); + } + + @Test + public void getHealthCheck_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception { + databaseNotAccessible(); + mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE)); + } + + @Test + public void getCommitInfo_shouldReturnCommitData_whenCorrectPropertiesFileExists() throws Exception { + mockMvc.perform(get("/commitInfo") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.commitId").value("123")) + .andExpect(jsonPath("$.commitMessageShort").value("Test short commit message")) + .andExpect(jsonPath("$.commitTime").value("1999-09-12T13:48:55+0200")); + } + + private void databaseConnectionEstablished() throws SQLException { + given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString())) + .willReturn(0); + } + + private void databaseNotAccessible() throws SQLException { + given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString())) + .willThrow(new SQLException(ERROR_MESSAGE)); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java index f63580d2..e0ab34cd 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java @@ -29,6 +29,7 @@ import org.onap.vid.aai.model.PortDetailsTranslator; import org.onap.vid.aai.util.*; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.asdc.parser.VidNotionsBuilder; import org.onap.vid.services.AaiService; import org.onap.vid.services.AaiServiceImpl; import org.onap.vid.services.VidService; @@ -81,9 +82,14 @@ public class LocalWebConfig { } @Bean - public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider) { + public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider, FeatureManager featureManager) { final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath(); - return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider); + return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider, featureManager); + } + + @Bean + public CacheProvider cacheProvider() { + return new NonCachingCacheProvider(); } @Bean(name = "aaiRestInterface") @@ -92,13 +98,18 @@ public class LocalWebConfig { } @Bean - public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface")AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator) { - return new AaiClient(aaiRestInterface, portDetailsTranslator); + public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface") AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) { + return new AaiClient(aaiRestInterface, portDetailsTranslator, cacheProvider); + } + + @Bean + public VidNotionsBuilder vidNotionsBuilder(FeatureManager featureManager) { + return new VidNotionsBuilder(featureManager); } @Bean - public ToscaParserImpl2 getToscaParser() { - return new ToscaParserImpl2(); + public ToscaParserImpl2 getToscaParser(VidNotionsBuilder vidNotionsBuilder) { + return new ToscaParserImpl2(vidNotionsBuilder); } @Bean diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java new file mode 100644 index 00000000..b79f84ad --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java @@ -0,0 +1,49 @@ +package org.onap.vid.controller; + +import org.junit.Test; + +import javax.ws.rs.NotAuthorizedException; + + +public class LoggerControllerTest { + + private LoggerController createTestSubject() { + return new LoggerController(); + } + + /*@Test + public void testGetLog() throws Exception { + LoggerController testSubject; + String loggerName = ""; + HttpServletRequest request = null; + Integer limit = 0; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getLog(loggerName, request, limit); + }*/ + + + @Test + public void testNotAuthorizedHandler() throws Exception { + LoggerController testSubject; + NotAuthorizedException e = null; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.notAuthorizedHandler(e); + } + + /*@Test + public void testIoExceptionHandler() throws Exception { + LoggerController testSubject; + Exception e = null; + ExceptionResponse result; + + // default test + testSubject = createTestSubject(); + result = testSubject.ioExceptionHandler(e); + }*/ +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java new file mode 100644 index 00000000..6933a2f8 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java @@ -0,0 +1,339 @@ +package org.onap.vid.controller; + +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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========================================================= + */ + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.log4j.BasicConfigurator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.category.AddCategoryOptionResponse; +import org.onap.vid.category.AddCategoryOptionsRequest; +import org.onap.vid.category.CategoryParameterOptionRep; +import org.onap.vid.category.CategoryParametersResponse; +import org.onap.vid.model.CategoryParameter; +import org.onap.vid.model.CategoryParameterOption; +import org.onap.vid.services.CategoryParameterService; +import org.onap.vid.services.CategoryParameterServiceImpl; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import javax.ws.rs.ForbiddenException; +import java.util.Collections; +import java.util.function.BiFunction; + +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.times; +import static org.onap.vid.model.CategoryParameter.Family.PARAMETER_STANDARDIZATION; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class MaintenanceControllerTest { + + final private String MAINTENANCE_CATEGORY_PATH = "/maintenance/category_parameter"; + final private String CATEGORY_PARAMETER_PATH = MAINTENANCE_CATEGORY_PATH + "/{name}"; + final private String DELETE_CATEGORY_PATH = "/maintenance/delete_category_parameter/{name}"; + + @Mock + private CategoryParameterService service; + private MaintenanceController maintenanceController; + private MockMvc mockMvc; + private ObjectMapper objectMapper; + + @Before + public void setUp() { + maintenanceController = new MaintenanceController(service); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(maintenanceController).build(); + objectMapper = new ObjectMapper(); + } + + @Test + public void addCategoryOptions_shouldReturnMultiStatus_whenErrorsExist() throws Exception { + String categoryName = "catName1"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("first option", "second option"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse( + ImmutableList.of("error one", "error two")); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willReturn(addCategoryOptionResponse); + + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isMultiStatus()) + .andExpect( + content().json(objectMapper + .writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void addCategoryOptions_shouldReturnOk_whenNoErrorsExist() throws Exception { + String categoryName = "catName2"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("first option", "second option", "third option"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willReturn(addCategoryOptionResponse); + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isOk()) + .andExpect(content().json( + objectMapper.writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void addCategoryOptions_shouldReturnNotFound_whenUnfoundedCategoryExceptionIsThrown() throws Exception { + String unfoundedMsg = "unfounded category exception message"; + String categoryName = "catName3"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("first option"); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryException(unfoundedMsg)); + + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isNotFound()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedMsg))))); + } + + @Test + public void addCategoryOptions_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + String categoryName = "catName13"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("option second", "first option"); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willThrow(new RuntimeException()); + + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isInternalServerError()); + } + + @Test + public void updateNameForOption_shouldReturnMultiStatus_whenErrorsExist() throws Exception { + String categoryName = "catName4"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id1", "name1"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse( + ImmutableList.of("error one", "error two")); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willReturn(addCategoryOptionResponse); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isMultiStatus()) + .andExpect( + content().json(objectMapper + .writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void updateNameForOption_shouldReturnOk_whenNoErrorsExist() throws Exception { + String categoryName = "catName5"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id2", "name2"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willReturn(addCategoryOptionResponse); + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isOk()) + .andExpect(content().json( + objectMapper.writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void updateNameForOption_shouldReturnForbidden_whenForbiddenExceptionIsThrown() throws Exception { + String categoryName = "catName6"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id3", "name3"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new ForbiddenException()); + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isForbidden()) + .andExpect(content().json( + objectMapper + .writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of("HTTP 403 Forbidden"))))); + } + + @Test + public void updateNameForOption_shouldReturnNotFound_whenUnfoundedIsThrown() throws Exception { + String unfoundedOptionMsg = "unfounded category option exception message"; + String categoryName = "catName7"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id4", "name4"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryOptionException(unfoundedOptionMsg)); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isNotFound()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedOptionMsg))))); + } + + @Test + public void updateNameForOption_shouldReturnConflict_whenAlreadyExistOptionNameIsThrown() throws Exception { + String conflictMsg = "already exists option name exception message"; + String categoryName = "catName8"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id5", "name5"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new CategoryParameterServiceImpl.AlreadyExistOptionNameException(conflictMsg)); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isConflict()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(conflictMsg))))); + } + + @Test + public void updateNameForOption_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + String categoryName = "catName18"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id6", "name6"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new RuntimeException()); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isInternalServerError()); + } + + @Test + public void getCategoryParameter_shouldReturnExistingMap() throws Exception { + CategoryParametersResponse categoryParametersResponse = + new CategoryParametersResponse( + ImmutableMap.of( + "key1", ImmutableList.of( + new CategoryParameterOptionRep("testId", "testName")))); + + given(service.getCategoryParameters(PARAMETER_STANDARDIZATION)) + .willReturn(categoryParametersResponse); + + mockMvc.perform(get(MAINTENANCE_CATEGORY_PATH) + .param("familyName", "PARAMETER_STANDARDIZATION") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(categoryParametersResponse))); + } + + @Test + public void getCategoryParameter_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + given(service.getCategoryParameters(PARAMETER_STANDARDIZATION)) + .willThrow(new RuntimeException()); + + mockMvc.perform(get(MAINTENANCE_CATEGORY_PATH) + .param("familyName", "PARAMETER_STANDARDIZATION") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isInternalServerError()); + } + + @Test + public void deleteCategoryOption_shouldReturnOk_whenNoExceptionIsThrown() throws Exception { + String categoryName = "catName9"; + CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id1", "name1", + new CategoryParameter()); + + prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOption)) + .andExpect(status().isOk()); + + then(service).should(times(1)) + .deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); + } + + @Test + public void deleteCategoryOption_shouldReturnNotFound_whenUnfoundedExceptionIsThrown() throws Exception { + String unfoundedMsg = "unfounded category exception message"; + String categoryName = "catName10"; + CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id2", "name2", + new CategoryParameter()); + + willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryException(unfoundedMsg)) + .given(service).deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); + + prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOption)) + .andExpect(status().isNotFound()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedMsg))))); + } + + @Test + public void deleteCategoryOption_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + String categoryName = "catName19"; + CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id3", "name3", + new CategoryParameter()); + + willThrow(new RuntimeException()).given(service) + .deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); + + prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOption)) + .andExpect(status().isInternalServerError()); + } + + private ArgumentMatcher requestMatcher(T t) { + return new ArgumentMatcher() { + @Override + public boolean matches(Object o) { + return t.equals(o); + } + }; + } + + private ResultActions prepareRequestExpectations( + BiFunction httpMethod, + String path, String name, String jsonContent) throws Exception { + return mockMvc.perform(httpMethod.apply(path, name) + .contentType(MediaType.APPLICATION_JSON) + .content(jsonContent)); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java new file mode 100644 index 00000000..747783d5 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java @@ -0,0 +1,394 @@ +package org.onap.vid.controller; + +import org.junit.Test; +import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestDetailsWrapper; +import org.onap.vid.services.CloudOwnerServiceImpl; +import org.springframework.http.ResponseEntity; +import org.togglz.core.manager.FeatureManager; + +import javax.servlet.http.HttpServletRequest; + +import static org.mockito.Mockito.mock; + +public class MsoControllerNewTest { + + private MsoController createTestSubject() { + try { + return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class),mock(FeatureManager.class)), new CloudOwnerServiceImpl(null, null)); + } catch (Exception e) { + return null; + } + } + + @Test + public void testCreateSvcInstance() throws Exception { + MsoController testSubject; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createSvcInstance(request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateVnf() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createVnf(serviceInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateNwInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createNwInstance(serviceInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateVolumeGroupInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createVolumeGroupInstance(serviceInstanceId, vnfInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateVfModuleInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createVfModuleInstance(serviceInstanceId, vnfInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateConfigurationInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetailsWrapper mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createConfigurationInstance(serviceInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteSvcInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + String result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteSvcInstance(serviceInstanceId, request, mso_request, ""); + } catch (Exception e) { + } + } + + @Test + public void testDeleteVnf() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteVnf(serviceInstanceId, vnfInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetailsWrapper mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testActivateConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.activateConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeactivateConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deactivateConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDisablePortOnConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.disablePortOnConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testEnablePortOnConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.enablePortOnConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteVfModule() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + String vfModuleId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteVfModule(serviceInstanceId, vnfInstanceId, vfModuleId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteVolumeGroupInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + String volumeGroupId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteVolumeGroupInstance(serviceInstanceId, vnfInstanceId, volumeGroupId, request, + mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteNwInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String networkInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteNwInstance(serviceInstanceId, networkInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testGetOrchestrationRequest() throws Exception { + MsoController testSubject; + String requestId = ""; + HttpServletRequest request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.getOrchestrationRequest(requestId, request); + } catch (Exception e) { + } + } + + @Test + public void testGetOrchestrationRequests() throws Exception { + MsoController testSubject; + String filterString = ""; + HttpServletRequest request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.getOrchestrationRequests(filterString, request); + } catch (Exception e) { + } + } + + @Test + public void testActivateServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.activateServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testDeactivateServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deactivateServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testManualTaskComplete() throws Exception { + MsoController testSubject; + String taskId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.manualTaskComplete(taskId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testRemoveRelationshipFromServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.removeRelationshipFromServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testAddRelationshipToServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.addRelationshipToServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java index 4645a83a..c69bce32 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java @@ -2,10 +2,8 @@ package org.onap.vid.controller; import org.apache.commons.lang.StringEscapeUtils; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.controllers.MsoConfig; -import org.onap.vid.controllers.MsoController; -import org.onap.vid.domain.mso.RequestInfo; import org.onap.vid.factories.MsoRequestFactory; +import org.onap.vid.mso.model.RequestInfo; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.Task; @@ -15,7 +13,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.Assert; -import org.testng.Assert.*; import org.testng.annotations.Test; import java.util.List; @@ -32,7 +29,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { public void testInstanceCreationNew() throws Exception { RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); //TODO: make ths test to really test something //ResponseEntity responseEntityNew = msoController.createSvcInstanceNew(null, requestDetails); ResponseEntity responseEntity = msoController.createSvcInstance(null, requestDetails); @@ -44,7 +41,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { public void testInstanceCreationLocalWithRest() throws Exception { RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); ResponseEntity responseEntityNew = msoController.createSvcInstance(null, requestDetails); //TODO: make ths test to really test something // ResponseEntity responseEntityRest = msoController.createSvcInstanceNewRest(null, requestDetails); @@ -57,7 +54,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { public void testInstanceCreation() throws Exception { RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); ResponseEntity responseEntity = msoController.createSvcInstance(null, requestDetails); @@ -72,7 +69,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { @Test(enabled = false) public void testGetOrchestrationRequestsForDashboard() throws Exception { - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); List orchestrationRequestsForDashboard = msoController.getOrchestrationRequestsForDashboard(); Assert.assertEquals(orchestrationRequestsForDashboard.size(), 2); @@ -80,7 +77,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { @Test(enabled = false) public void testGetManualTasksByRequestId() throws Exception { - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); List orchestrationRequestsForDashboard = msoController.getManualTasksByRequestId("za1234d1-5a33-55df-13ab-12abad84e335"); Assert. assertEquals(orchestrationRequestsForDashboard.get(0).getTaskId(), "daf4dd84-b77a-42da-a051-3239b7a9392c"); @@ -94,7 +91,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { requestInfo.setSource("VID"); RequestDetails requestDetails = new RequestDetails(); requestDetails.setRequestInfo(requestInfo); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); ResponseEntity responseEntity = msoController.manualTaskComplete("daf4dd84-b77a-42da-a051-3239b7a9392c", requestDetails); String assertString = "{ \\\"status\\\": 200, \\\"entity\\\": {\\n\" +\n" + " \" \\\"taskRequestReference\\\": {\\n\" +\n" + diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java new file mode 100644 index 00000000..e9d2cfd4 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java @@ -0,0 +1,39 @@ +package org.onap.vid.controller; + +import org.junit.Test; +import org.springframework.http.ResponseEntity; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; + +public class PropertyControllerTest { + + private PropertyController createTestSubject() { + return new PropertyController(); + } + + @Test + public void testWelcome() throws Exception { + PropertyController testSubject; + HttpServletRequest request = null; + ModelAndView result; + + // default test + testSubject = createTestSubject(); + result = testSubject.welcome(request); + } + + + @Test + public void testGetProperty() throws Exception { + PropertyController testSubject; + String name = ""; + String defaultvalue = ""; + HttpServletRequest request = null; + ResponseEntity result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getProperty(name, defaultvalue, request); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java new file mode 100644 index 00000000..c19b810d --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java @@ -0,0 +1,26 @@ +package org.onap.vid.controller; + +import org.junit.Test; +import org.springframework.http.ResponseEntity; + +public class RoleGeneratorControllerTest { + + private RoleGeneratorController createTestSubject() { + return new RoleGeneratorController(); + } + + @Test + public void testGenerateRoleScript() throws Exception { + RoleGeneratorController testSubject; + boolean firstRun = false; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.generateRoleScript(firstRun); + } catch (Exception e) { + + } + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java new file mode 100644 index 00000000..f9f80d1b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java @@ -0,0 +1,48 @@ +package org.onap.vid.controller; + +import org.jetbrains.annotations.NotNull; +import org.onap.vid.aai.model.Permissions; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.roles.RoleValidator; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ServicePermissionsTest { + + @DataProvider + public static Object[][] trueAndFalse() { + return new Object[][]{{TRUE}, {FALSE}}; + } + + + @Test(dataProvider = "trueAndFalse") + public void servicePermissions_responseMatchesMockedRoleValidator(boolean expected) { + String subscriberId = randomAlphanumeric(8); + String serviceType = randomAlphanumeric(8); + + RoleProvider roleProvider = mock(RoleProvider.class); + RoleValidator roleValidator = mock(RoleValidator.class); + when(roleProvider.getUserRolesValidator(any())).thenReturn(roleValidator); + when(roleValidator.isServicePermitted(subscriberId, serviceType)).thenReturn(expected); + + AaiController2 aaiController2 = new AaiController2(null, roleProvider, null); + + Permissions permissions = aaiController2.servicePermissions(unimportantRequest(), subscriberId, serviceType); + assertThat(permissions, is(new Permissions(expected))); + } + + @NotNull + private MockHttpServletRequest unimportantRequest() { + return new MockHttpServletRequest("", ""); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java index 36a17910..5751852a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java @@ -1,42 +1,47 @@ package org.onap.vid.controller; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.module.kotlin.KotlinModule; +import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.onap.vid.model.NewServiceModel; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + /** * Created by moriya1 on 04/07/2017. */ public class ToscaParserMockHelper { + private static final Logger logger = LogManager.getLogger(ToscaParserMockHelper.class); - private String uuid; - private String filePath; - private NewServiceModel newServiceModel; + private static final ObjectMapper om = new ObjectMapper(); + private final String uuid; + private final String filePath; + private final NewServiceModel newServiceModel; - public ToscaParserMockHelper(String uuid, String filePath) { + public ToscaParserMockHelper(String uuid, String filePath) throws IOException { this.uuid = uuid; this.filePath = filePath; + + InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(getFilePath()); + logger.info(jsonFile); + String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); + om.registerModule(new KotlinModule()); + this.newServiceModel = om.readValue(expectedJsonAsString, NewServiceModel.class); } public String getUuid() { return uuid; } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getFilePath() { return filePath; } - public void setFilePath(String filePath) { - this.filePath = filePath; - } - public NewServiceModel getNewServiceModel() { return newServiceModel; } - - public void setNewServiceModel(NewServiceModel newServiceModel) { - this.newServiceModel = newServiceModel; - } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java new file mode 100644 index 00000000..f57ba8a7 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java @@ -0,0 +1,31 @@ +package org.onap.vid.controller; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + + +public class VersionControllerTest { + + @DataProvider + public static Object[][] majorVersionContainer() { + return new Object[][]{ + {"features.properties", "1.0.2000", "features.properties.2000"}, + {"", "1.0.2000", ".2000"}, + {"kuku", "1.0.2000", "kuku.2000"}, + {"/kuku", "1.0.2000", "kuku.2000"}, + {"1810p.features.properties", "1.0.2000", "1810p.2000"}, + {"/opt/app/dev.features.properties", "1.0.2000", "dev.2000"}, + {"foo", "2000", "foo.2000"}, + }; + } + + final VersionController versionController = new VersionController(null); + + @Test(dataProvider = "majorVersionContainer") + public void testGetDisplayVersion(String majorVersionContainer, String buildNumberContainer, String expected) { + assertThat(versionController.getDisplayVersion(majorVersionContainer, buildNumberContainer), is(expected)); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java new file mode 100644 index 00000000..aeb03b60 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.vid.controller; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.log4j.BasicConfigurator; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.SecureServices; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.asdc.beans.ServiceBuilder; +import org.onap.vid.model.*; +import org.onap.vid.model.PombaInstance.PombaRequest; +import org.onap.vid.model.PombaInstance.ServiceInstance; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.services.AaiService; +import org.onap.vid.services.PombaService; +import org.onap.vid.services.VidService; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.IntStream; + +import static java.util.stream.Collectors.toMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.not; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.times; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class VidControllerTest { + + public static final String REST_MODELS_SERVICES = "/rest/models/services"; + public static final String REST_MODELS_SERVICES_UUID = "/rest/models/services/{uuid}"; + public static final String REST_MODELS_RESET = "/rest/models/reset"; + public static final String REST_MODELS_SERVICES_VERIFY_SERVICE = "/rest/models/services/verifyService"; + @Mock + private VidService vidService; + @Mock + private AaiService aaiService; + @Mock + private RoleProvider roleProvider; + @Mock + private PombaService pombaService; + + private VidController vidController; + private MockMvc mockMvc; + private ObjectMapper objectMapper; + + private String uuid1; + private String uuid2; + private String uuid3; + + @Before + public void setUp() { + vidController = new VidController(vidService, aaiService, roleProvider, pombaService); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(vidController).build(); + objectMapper = new ObjectMapper(); + + uuid1 = UUID.randomUUID().toString(); + uuid2 = UUID.randomUUID().toString(); + uuid3 = UUID.randomUUID().toString(); + } + + @Test + public void getServices_shouldReturnService_whenServiceExists() throws Exception { + List services = ImmutableList.of(createService(uuid1, 1), createService(uuid2, 2), createService(uuid3, 3)); + + given(aaiService.getServicesByDistributionStatus()).willReturn(services); + + SecureServices secureServices = new SecureServices(); + secureServices.setServices(services); + secureServices.setReadOnly(false); + + mockMvc.perform(get(REST_MODELS_SERVICES) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(secureServices))); + } + + @Test + public void getService_shouldReturnService_whenNoExceptionIsThrown() throws Exception { + ServiceModel model = expectedServiceModel(uuid1); + + given(vidService.getService(uuid1)).willReturn(model); + + mockMvc.perform(get(REST_MODELS_SERVICES_UUID, uuid1) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(model))); + } + + @Test + public void getService_shouldThrow_whenAsdcCatalogExceptionIsThrown() throws Exception { + String testUuid = UUID.randomUUID().toString(); + + given(vidService.getService(testUuid)).willThrow(new AsdcCatalogException("error msg")); + + mockMvc.perform(get(REST_MODELS_SERVICES_UUID, testUuid) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isServiceUnavailable()); + } + + @Test + public void invalidateServiceModelCache_shouldReturnAccepted() throws Exception { + mockMvc.perform(post(REST_MODELS_RESET) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isAccepted()); + + then(vidService).should(times(1)).invalidateServiceCache(); + } + + @Test + public void verifyServiceInstance_shouldReturnOk() throws Exception { + PombaRequest pombaRequest = new PombaRequest(); + pombaRequest.serviceInstanceList = ImmutableList.of(new ServiceInstance()); + + mockMvc.perform(post(REST_MODELS_SERVICES_VERIFY_SERVICE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(pombaRequest))) + .andExpect(status().isOk()); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(PombaRequest.class); + then(pombaService).should(times(1)).verify(argumentCaptor.capture()); + + assertThat(pombaRequest).isEqualToComparingFieldByFieldRecursively(argumentCaptor.getValue()); + } + + private ServiceModel expectedServiceModel(String uuid) { + final ServiceModel serviceModel = getModelsByUuid().get(uuid); + Assert.assertThat(serviceModel, is(not(nullValue()))); + return serviceModel; + } + + private Service createService(String uuid, int i) { + return new ServiceBuilder().setUuid(uuid).setInvariantUUID("invariantUUID" + i) + .setCategory("category" + i).setVersion("version" + i).setName("name" + i) + .setDistributionStatus("distStatus" + i).setToscaModelURL("toscaModelUrl" + i).build(); + } + + private ServiceModel createServiceModel(int i) { + ServiceModel model = new ServiceModel(); + + model.setCollectionResource(ImmutableMap.of("resKey" + i, new CR())); + model.setNetworks(ImmutableMap.of("network" + i, new Network())); + model.setPnfs(ImmutableMap.of("pnf" + i, new Node())); + model.setServiceProxies(ImmutableMap.of("servProxy" + i, new ServiceProxy())); + model.setVfModules(ImmutableMap.of("vfmod" + i, new VfModule())); + model.setVnfs(ImmutableMap.of("vnf" + i, new VNF())); + model.setVolumeGroups(ImmutableMap.of("volgroup" + i, new VolumeGroup())); + model.setService(new org.onap.vid.model.Service()); + return model; + } + + private Map getModelsByUuid() { + ServiceModel serviceModel1 = createServiceModel(1); + ServiceModel serviceModel2 = createServiceModel(2); + ServiceModel serviceModel3 = createServiceModel(3); + + List pseudoServiceModels = ImmutableList.of(serviceModel1, serviceModel2, serviceModel3); + List uuids = ImmutableList.of(uuid1, uuid2, uuid3); + return IntStream.range(0, pseudoServiceModels.size()).boxed() + .collect(toMap(i -> uuids.get(i), i -> pseudoServiceModels.get(i))); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java new file mode 100644 index 00000000..9729c4e7 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java @@ -0,0 +1,46 @@ +package org.onap.vid.controller; +//package org.onap.vid.controller; +// +//import javax.servlet.http.HttpServletRequest; +// +//import org.junit.Test; +//import org.springframework.web.servlet.ModelAndView; +// +//public class ViewEditSubControllerTest { +// +// private ViewEditSubController createTestSubject() { +// return new ViewEditSubController(); +// } +// +// @Test +// public void testWelcome() throws Exception { +// ViewEditSubController testSubject; +// HttpServletRequest request = null; +// ModelAndView result; +// +// // default test +// testSubject = createTestSubject(); +// result = testSubject.welcome(request); +// } +// +// +// @Test +// public void testGetViewName() throws Exception { +// ViewEditSubController testSubject; +// String result; +// +// // default test +// testSubject = createTestSubject(); +// result = testSubject.getViewName(); +// } +// +// @Test +// public void testSetViewName() throws Exception { +// ViewEditSubController testSubject; +// String viewName = ""; +// +// // default test +// testSubject = createTestSubject(); +// testSubject.setViewName(viewName); +// } +//} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java deleted file mode 100644 index 2a398b36..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/AaiControllerTest.java +++ /dev/null @@ -1,440 +0,0 @@ -package org.onap.vid.controllers; - -import javax.servlet.http.HttpServletRequest; - -import org.json.simple.JSONObject; -import org.junit.Test; -import org.onap.vid.aai.AaiResponse; -import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList; -import org.onap.vid.controllers.AaiController; -import org.onap.vid.model.VersionByInvariantIdsRequest; -import org.springframework.http.ResponseEntity; -import org.springframework.web.servlet.ModelAndView; -import java.util.*; -import org.junit.Assert; - -public class AaiControllerTest { - - private AaiController createTestSubject() { - return new AaiController(); - } - - @Test - public void testWelcome() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - ModelAndView result; - - // default test - testSubject = createTestSubject(); - result = testSubject.welcome(request); - } - - @Test - public void testGetTargetProvStatus() throws Exception { - AaiController testSubject; - ResponseEntity result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getTargetProvStatus(); - } - - @Test - public void testViewEditGetTenantsFromServiceType() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - String globalCustomerId = ""; - String serviceType = ""; - ResponseEntity result; - - // default test - testSubject = createTestSubject(); - result = testSubject.viewEditGetTenantsFromServiceType(request, globalCustomerId, serviceType); - } - - - - - - @Test - public void testGetAicZones() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getAicZones(request); - } catch (Exception e) { - } - } - - @Test - public void testGetAicZoneForPnf() throws Exception { - AaiController testSubject; - String globalCustomerId = ""; - String serviceType = ""; - String serviceId = ""; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getAicZoneForPnf(globalCustomerId, serviceType, serviceId, request); - } catch (Exception e) { - } - } - - @Test - public void testGetUserID() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getUserID(request); - } catch (Exception e) { - } - } - - @Test - public void testDoGetServices() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.doGetServices(request); - } catch (Exception e) { - } - } - - @Test - public void testGetVersionByInvariantId() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - VersionByInvariantIdsRequest versions = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getVersionByInvariantId(request, versions); - } catch (Exception e) { - } - } - - // @Test - // public void testAaiResponseToResponseEntity() throws Exception { - // AaiController testSubject;AaiResponse aaiResponseData = null; - // ResponseEntity result; - // - // // default test - // } - - @Test - public void testDoGetServiceInstance() throws Exception { - AaiController testSubject; - String serviceInstanceId = ""; - String serviceInstanceType = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.doGetServiceInstance(serviceInstanceId, serviceInstanceType); - } catch (Exception e) { - } - } - - @Test - public void testDoGetServices_1() throws Exception { - AaiController testSubject; - String globalCustomerId = ""; - String serviceSubscriptionId = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.doGetServices(globalCustomerId, serviceSubscriptionId); - } catch (Exception e) { - } - } - - @Test - public void testDoGetSubscriberList() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - String fullSet = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.doGetSubscriberList(request, fullSet); - } catch (Exception e) { - } - } - - @Test - public void testGetOperationalEnvironments() throws Exception { - AaiController testSubject; - String operationalEnvironmentType = ""; - String operationalEnvironmentStatus = ""; - AaiResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getOperationalEnvironments(operationalEnvironmentType, operationalEnvironmentStatus); - } catch (Exception e) { - } - } - - @Test - public void testGetFullSubscriberList() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getFullSubscriberList(request); - } catch (Exception e) { - } - } - - @Test - public void testGetVnfDataByGlobalIdAndServiceType() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - String globalCustomerId = ""; - String serviceType = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getVnfDataByGlobalIdAndServiceType(request, globalCustomerId, serviceType); - } catch (Exception e) { - } - } - - @Test - public void testDoRefreshSubscriberList() throws Exception { - AaiController testSubject; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.doRefreshSubscriberList(); - } catch (Exception e) { - } - } - - @Test - public void testDoRefreshFullSubscriberList() throws Exception { - AaiController testSubject; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.doRefreshFullSubscriberList(); - } catch (Exception e) { - } - } - - @Test - public void testGetSubscriberDetails() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - String subscriberId = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.GetSubscriberDetails(request, subscriberId); - } catch (Exception e) { - } - } - - @Test - public void testSearchServiceInstances() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - String subscriberId = ""; - String instanceIdentifier = ""; - List projects = null; - List owningEntities = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.SearchServiceInstances(request, subscriberId, instanceIdentifier, projects, - owningEntities); - } catch (Exception e) { - } - } - - @Test - public void testViewEditGetComponentList() throws Exception { - AaiController testSubject; - String namedQueryId = ""; - String globalCustomerId = ""; - String serviceType = ""; - String serviceInstance = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.viewEditGetComponentList(namedQueryId, globalCustomerId, serviceType, serviceInstance); - } catch (Exception e) { - } - } - - @Test - public void testGetVnfData() throws Exception { - AaiController testSubject; - String globalCustomerId = ""; - String serviceType = ""; - String serviceInstanceId = ""; - AaiResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getVnfData(globalCustomerId, serviceType, serviceInstanceId); - } catch (Exception e) { - } - } - - @Test - public void testViewEditGetComponentList_1() throws Exception { - AaiController testSubject; - String namedQueryId = ""; - String globalCustomerId = ""; - String serviceType = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.viewEditGetComponentList(namedQueryId, globalCustomerId, serviceType); - } catch (Exception e) { - } - } - - @Test - public void testGetNodeTemplateInstances() throws Exception { - AaiController testSubject; - String globalCustomerId = ""; - String serviceType = ""; - String modelVersionId = ""; - String modelInvariantId = ""; - String cloudRegion = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId, - modelInvariantId, cloudRegion); - } catch (Exception e) { - } - } - - @Test - public void testGetByUri() throws Exception { - AaiController testSubject; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getByUri(request); - } catch (Exception e) { - } - } - - @Test - public void testGetSpecificConfiguration() throws Exception { - AaiController testSubject; - String configurationId = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getSpecificConfiguration(configurationId); - } catch (Exception e) { - } - } - - @Test - public void testGetServiceInstanceAssociatedPnfs() throws Exception { - AaiController testSubject; - String globalCustomerId = ""; - String serviceType = ""; - String serviceInstanceId = ""; - List result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getServiceInstanceAssociatedPnfs(globalCustomerId, serviceType, serviceInstanceId); - } catch (Exception e) { - } - } - - @Test - public void testGetSpecificPnf() throws Exception { - AaiController testSubject; - String pnfId = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getSpecificPnf(pnfId); - } catch (Exception e) { - } - } - - @Test - public void testGetPnfInstances() throws Exception { - AaiController testSubject; - String globalCustomerId = ""; - String serviceType = ""; - String modelVersionId = ""; - String modelInvariantId = ""; - String cloudRegion = ""; - String equipVendor = ""; - String equipModel = ""; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getPnfInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId, - cloudRegion, equipVendor, equipModel); - } catch (Exception e) { - } - - } - -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java deleted file mode 100644 index 3c8250b2..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java +++ /dev/null @@ -1,455 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright © 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.vid.controllers; - -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.isA; -import static org.onap.vid.controllers.ChangeManagementController.CHANGE_MANAGEMENT; -import static org.onap.vid.controllers.ChangeManagementController.GET_VNF_WORKFLOW_RELATION; -import static org.onap.vid.controllers.ChangeManagementController.SCHEDULER_BY_SCHEDULE_ID; -import static org.onap.vid.controllers.ChangeManagementController.VNF_WORKFLOW_RELATION; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.collect.ImmutableList; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.Scanner; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.log4j.BasicConfigurator; -import org.json.simple.JSONArray; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.vid.changeManagement.GetVnfWorkflowRelationRequest; -import org.onap.vid.changeManagement.GetWorkflowsResponse; -import org.onap.vid.changeManagement.VnfDetailsWithWorkflows; -import org.onap.vid.changeManagement.VnfWorkflowRelationAllResponse; -import org.onap.vid.changeManagement.VnfWorkflowRelationResponse; -import org.onap.vid.domain.mso.InstanceIds; -import org.onap.vid.domain.mso.RequestStatus; -import org.onap.vid.exceptions.NotFoundException; -import org.onap.vid.model.ExceptionResponse; -import org.onap.vid.mso.rest.Request; -import org.onap.vid.services.ChangeManagementService; -import org.onap.vid.services.WorkflowService; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.multipart.MultipartFile; - -@RunWith(MockitoJUnitRunner.class) -public class ChangeManagementControllerTest { - - private static final String FILE_NAME = "file"; - private static final String GET_VNF_WORKFLOW_RELATION_URL = - "/" + CHANGE_MANAGEMENT + "/" + GET_VNF_WORKFLOW_RELATION; - private static final String WORKFLOW_URL = "/" + CHANGE_MANAGEMENT + "/workflow"; - private static final String WORKFLOW_NAME_URL = WORKFLOW_URL + "/{name}"; - private static final String MSO_URL = "/" + CHANGE_MANAGEMENT + "/mso"; - private static final String UPLOAD_CONFIG_UPDATE_FILE_URL = "/" + CHANGE_MANAGEMENT + "/uploadConfigUpdateFile"; - private static final String SCHEDULER_URL = "/" + CHANGE_MANAGEMENT + "/scheduler"; - private static final String SCHEDULER_BY_SCHEDULE_ID_URL = "/" + CHANGE_MANAGEMENT + SCHEDULER_BY_SCHEDULE_ID; - private static final String VNF_WORKFLOW_RELATION_URL = "/" + CHANGE_MANAGEMENT + "/" + VNF_WORKFLOW_RELATION; - private static final String VNFS = "vnfs"; - - private static final String FAILED_TO_GET_MSG = "Failed to get workflows for vnf"; - private static final String FAILED_TO_ADD_MSG = "Failed to add vnf to workflow relation"; - private static final String FAILED_TO_GET_ALL_MSG = "Failed to get all vnf to workflow relations"; - private static final String FAILED_TO_DELETE_MSG = "Failed to delete vnf from workflow relation"; - - private final ObjectMapper objectMapper = new ObjectMapper(); - private ChangeManagementController controller; - private MockMvc mockMvc; - @Mock - private WorkflowService workflowService; - @Mock - private ChangeManagementService changeManagementService; - @Mock - private Response mockResponse; - @Mock - private Response.StatusType statusType; - private ClassLoader classLoader = getClass().getClassLoader(); - private final String CHANGE_MANAGEMENT_REQUEST_JSON = getRequestContent("change-management-request.json"); - private final String GET_VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent( - "get-vnf-workflow-relation-request.json"); - private final String VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent("vnf-workflow-relation-request.json"); - - @Before - public void setUp() { - controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper); - BasicConfigurator.configure(); - mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); - } - - @Test - public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception { - - Collection givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3"); - Collection resultWorkflows = ImmutableList.of("workflow1", "workflow2"); - - given( - workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other)))) - .willReturn(resultWorkflows); - - mockMvc.perform(get(WORKFLOW_URL) - .param(VNFS, StringUtils.join(givenVnfs, ","))) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows))); - } - - @Test - public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue() - throws Exception { - - Collection requests = ImmutableList.of( - createRequest("network-instance-id-1", "status-message-1"), - createRequest("network-instance-id-2", "status-message-2")); - - given(changeManagementService.getMSOChangeManagements()).willReturn(requests); - - mockMvc.perform(get(MSO_URL)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(requests))); - } - - @Test - public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception { - - String vnfName = "vnfName1"; - String jsonBody = "{'param1': 'paramparam'}"; - - given(changeManagementService.doChangeManagement( - argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName))) - .willReturn(ResponseEntity.ok().body(jsonBody)); - - mockMvc.perform(post(WORKFLOW_NAME_URL, vnfName) - .contentType(MediaType.APPLICATION_JSON) - .content(CHANGE_MANAGEMENT_REQUEST_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(jsonBody)); - } - - @Test - public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception { - - String jsonString = "{'param1': 'paramparam'}"; - byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); - MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); - - given(changeManagementService - .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)))) - .willReturn(jsonString); - - mockMvc.perform(MockMvcRequestBuilders - .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) - .file(file)) - .andExpect(status().isOk()) - .andExpect(content().json(jsonString)); - } - - @Test - public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException() - throws Exception { - - byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); - MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); - - given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value()); - given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value()); - given(mockResponse.getStatusInfo()).willReturn(statusType); - - WebApplicationException exception = new WebApplicationException(mockResponse); - - willThrow(exception).given(changeManagementService) - .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))); - - mockMvc.perform(MockMvcRequestBuilders - .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) - .file(file)) - .andExpect(status().isNotFound()) - .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception)))); - } - - @Test - public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() - throws Exception { - - byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); - MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); - - RuntimeException exception = new RuntimeException("runtime exception message"); - - willThrow(exception).given(changeManagementService) - .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))); - - mockMvc.perform(MockMvcRequestBuilders - .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) - .file(file)) - .andExpect(status().isInternalServerError()) - .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception)))); - } - - @Test - public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception { - - JSONArray array = new JSONArray(); - array.add("element1"); - array.add("element2"); - - given(changeManagementService.getSchedulerChangeManagements()).willReturn(array); - - mockMvc.perform(get(SCHEDULER_URL)) - .andExpect(status().isOk()) - .andExpect(content().json(array.toJSONString())); - } - - @Test - public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { - - String id = "schedule-id-1"; - Pair pair = new ImmutablePair<>("myString", HttpStatus.OK.value()); - - given(changeManagementService.deleteSchedule(id)).willReturn(pair); - - mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id)) - .andExpect(status().isOk()); - } - - @Test - public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception { - - String id = "schedule-id-1"; - Pair pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value()); - - given(changeManagementService.deleteSchedule(id)).willReturn(pair); - - mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id)) - .andExpect(status().isNotFound()); - } - - @Test - public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { - - ImmutableList elements = ImmutableList.of("workflow1", "workflow2"); - GetWorkflowsResponse response = new GetWorkflowsResponse(); - response.setWorkflows(elements); - - given(changeManagementService - .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)))) - .willReturn(elements); - - mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception { - - String errorMsg = "not found"; - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg)); - - willThrow(new NotFoundException(errorMsg)) - .given(changeManagementService) - .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))); - - mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isNotFound()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception { - - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG)); - - willThrow(new RuntimeException("runtime exception message")) - .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class)); - - mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isInternalServerError()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { - - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(); - - given(changeManagementService - .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON)))) - .willReturn(response); - - mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception { - - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG)); - - willThrow(new RuntimeException("runtime exception message")) - .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request, - VNF_WORKFLOW_RELATION_REQUEST_JSON))); - - mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isInternalServerError()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { - - VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows(); - workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2")); - VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows)); - - given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response); - - mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() - throws Exception { - - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG)); - - willThrow(new RuntimeException("runtime exception message")) - .given(changeManagementService).getAllVnfWorkflowRelations(); - - mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL)) - .andExpect(status().isInternalServerError()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc")); - - given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request, - VNF_WORKFLOW_RELATION_REQUEST_JSON)))) - .willReturn(response); - - mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - @Test - public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() - throws Exception { - VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG)); - - willThrow(new RuntimeException("runtime exception message")) - .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request, - VNF_WORKFLOW_RELATION_REQUEST_JSON))); - - mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL) - .contentType(MediaType.APPLICATION_JSON) - .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) - .andExpect(status().isInternalServerError()) - .andExpect(content().json(objectMapper.writeValueAsString(response))); - } - - private boolean matches(T request, String expectedJson) { - try { - return objectMapper.writeValueAsString(request).equals(expectedJson); - } catch (JsonProcessingException e) { - System.out.println("Exception occurred: " + e.getMessage()); - } - return false; - } - - private ArgumentMatcher multipartFileMatcher(MultipartFile otherFile) { - return other -> { - try { - return other.getName().equals(otherFile.getName()) - && other.getSize() == otherFile.getSize() - && Arrays.equals(other.getBytes(), otherFile.getBytes()); - } catch (IOException e) { - System.out.println("IOException occurred: " + e.getMessage()); - } - return false; - }; - } - - private Request createRequest(String networkInstanceId, String statusMessage) { - Request req = new Request(); - InstanceIds instanceIds = new InstanceIds(); - instanceIds.setNetworkInstanceId(networkInstanceId); - - RequestStatus requestStatus = new RequestStatus(); - requestStatus.setStatusMessage(statusMessage); - - req.setInstanceIds(instanceIds); - req.setRequestStatus(requestStatus); - - return req; - } - - private String getRequestContent(String filename) { - InputStream inputStream = classLoader.getResourceAsStream(filename); - return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", ""); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java deleted file mode 100644 index 4894f35e..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/HealthCheckControllerTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.onap.vid.controllers; - -import org.apache.log4j.BasicConfigurator; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.dao.FnAppDoaImpl; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import java.sql.SQLException; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; -import static org.springframework.http.HttpStatus.OK; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(MockitoJUnitRunner.class) -public class HealthCheckControllerTest { - - private static final String ERROR_MESSAGE = "error message"; - private HealthCheckController testSubject; - private MockMvc mockMvc; - - @Mock - private FnAppDoaImpl fnAppDoa; - - @Before - public void setUp() { - testSubject = new HealthCheckController(fnAppDoa); - BasicConfigurator.configure(); - mockMvc = MockMvcBuilders.standaloneSetup(testSubject).build(); - } - - @Test - public void getHealthCheckStatusForIDNS_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception { - databaseConnectionEstablished(); - mockMvc.perform(get("/healthCheck") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.statusCode").value(OK.value())) - .andExpect(jsonPath("$.detailedMsg").value("health check succeeded")); - } - - @Test - public void getHealthCheckStatusForIDNS_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception { - databaseNotAccessible(); - mockMvc.perform(get("/healthCheck") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value())) - .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE)); - } - - @Test - public void getHealthCheck_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception { - databaseConnectionEstablished(); - mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.statusCode").value(OK.value())) - .andExpect(jsonPath("$.detailedMsg").value("health check succeeded")) - .andExpect(jsonPath("$.date").isString()); - } - - @Test - public void getHealthCheck_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception { - databaseNotAccessible(); - mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value())) - .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE)); - } - - @Test - public void getCommitInfo_shouldReturnCommitData_whenCorrectPropertiesFileExists() throws Exception { - mockMvc.perform(get("/commitInfo") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.commitId").value("123")) - .andExpect(jsonPath("$.commitMessageShort").value("Test short commit message")) - .andExpect(jsonPath("$.commitTime").value("1999-09-12T13:48:55+0200")); - } - - private void databaseConnectionEstablished() throws SQLException { - given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString())) - .willReturn(0); - } - - private void databaseNotAccessible() throws SQLException { - given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString())) - .willThrow(new SQLException(ERROR_MESSAGE)); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java deleted file mode 100644 index 59fed334..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.onap.vid.controllers; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.onap.vid.aai.AaiClient; -import org.onap.vid.aai.AaiClientInterface; -import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.local.LocalAsdcClient; -import org.onap.vid.asdc.parser.ToscaParserImpl2; -import org.onap.vid.controllers.VidController; -import org.onap.vid.services.AaiService; -import org.onap.vid.services.AaiServiceImpl; -import org.onap.vid.services.VidService; -import org.onap.vid.services.VidServiceImpl; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.io.IOException; -import java.io.InputStream; - -@Configuration -public class LocalWebConfig { - - /** - * Gets the object mapper. - * - * @return the object mapper - */ - @Bean - public ObjectMapper getObjectMapper() { - return new ObjectMapper(); - } - - - @Bean - public VidService vidService(AsdcClient asdcClient) { - return new VidServiceImpl(asdcClient, null); - } - - @Bean - public AaiService getAaiService() { - return new AaiServiceImpl(); - } - - @Bean - public AaiClientInterface getAaiClientInterface() { - return new AaiClient(null,null); - } - - @Bean - public AsdcClient asdcClient() throws IOException { - - - final InputStream asdcServicesFile = VidController.class.getClassLoader().getResourceAsStream("sdcservices.json"); - - final JSONTokener jsonTokener = new JSONTokener(IOUtils.toString(asdcServicesFile)); - final JSONObject sdcServicesCatalog = new JSONObject(jsonTokener); - - return new LocalAsdcClient.Builder().catalog(sdcServicesCatalog).build(); - - } - - @Bean - public ToscaParserImpl2 getToscaParser() { - return new ToscaParserImpl2(); - } - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java deleted file mode 100644 index 5a3002ab..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/LoggerControllerTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.onap.vid.controllers; - -import static org.junit.Assert.*; -import java.util.*; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.NotAuthorizedException; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.vid.model.ExceptionResponse; - - -public class LoggerControllerTest { - - private LoggerController createTestSubject() { - return new LoggerController(); - } - - /*@Test - public void testGetLog() throws Exception { - LoggerController testSubject; - String loggerName = ""; - HttpServletRequest request = null; - Integer limit = 0; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLog(loggerName, request, limit); - }*/ - - - @Test - public void testNotAuthorizedHandler() throws Exception { - LoggerController testSubject; - NotAuthorizedException e = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.notAuthorizedHandler(e); - } - - /*@Test - public void testIoExceptionHandler() throws Exception { - LoggerController testSubject; - Exception e = null; - ExceptionResponse result; - - // default test - testSubject = createTestSubject(); - result = testSubject.ioExceptionHandler(e); - }*/ -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java deleted file mode 100644 index 3a9d88f0..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java +++ /dev/null @@ -1,339 +0,0 @@ -package org.onap.vid.controllers; - -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright © 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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========================================================= - */ - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import org.apache.log4j.BasicConfigurator; -import org.codehaus.jackson.map.ObjectMapper; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentMatcher; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.category.AddCategoryOptionResponse; -import org.onap.vid.category.AddCategoryOptionsRequest; -import org.onap.vid.category.CategoryParameterOptionRep; -import org.onap.vid.category.CategoryParametersResponse; -import org.onap.vid.model.CategoryParameter; -import org.onap.vid.model.CategoryParameterOption; -import org.onap.vid.services.CategoryParameterService; -import org.onap.vid.services.CategoryParameterServiceImpl; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import javax.ws.rs.ForbiddenException; -import java.util.Collections; -import java.util.function.BiFunction; - -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.BDDMockito.*; -import static org.mockito.Mockito.times; -import static org.onap.vid.model.CategoryParameter.Family.PARAMETER_STANDARDIZATION; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(MockitoJUnitRunner.class) -public class MaintenanceControllerTest { - - final private String MAINTENANCE_CATEGORY_PATH = "/maintenance/category_parameter"; - final private String CATEGORY_PARAMETER_PATH = MAINTENANCE_CATEGORY_PATH + "/{name}"; - final private String DELETE_CATEGORY_PATH = "/maintenance/delete_category_parameter/{name}"; - - @Mock - private CategoryParameterService service; - private MaintenanceController maintenanceController; - private MockMvc mockMvc; - private ObjectMapper objectMapper; - - @Before - public void setUp() { - maintenanceController = new MaintenanceController(service); - BasicConfigurator.configure(); - mockMvc = MockMvcBuilders.standaloneSetup(maintenanceController).build(); - objectMapper = new ObjectMapper(); - } - - @Test - public void addCategoryOptions_shouldReturnMultiStatus_whenErrorsExist() throws Exception { - String categoryName = "catName1"; - AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); - req.options = ImmutableList.of("first option", "second option"); - AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse( - ImmutableList.of("error one", "error two")); - - given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) - .willReturn(addCategoryOptionResponse); - - prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(req)) - .andExpect(status().isMultiStatus()) - .andExpect( - content().json(objectMapper - .writeValueAsString(addCategoryOptionResponse))); - } - - @Test - public void addCategoryOptions_shouldReturnOk_whenNoErrorsExist() throws Exception { - String categoryName = "catName2"; - AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); - req.options = ImmutableList.of("first option", "second option", "third option"); - AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); - - given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) - .willReturn(addCategoryOptionResponse); - prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(req)) - .andExpect(status().isOk()) - .andExpect(content().json( - objectMapper.writeValueAsString(addCategoryOptionResponse))); - } - - @Test - public void addCategoryOptions_shouldReturnNotFound_whenUnfoundedCategoryExceptionIsThrown() throws Exception { - String unfoundedMsg = "unfounded category exception message"; - String categoryName = "catName3"; - AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); - req.options = ImmutableList.of("first option"); - - given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) - .willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryException(unfoundedMsg)); - - prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(req)) - .andExpect(status().isNotFound()) - .andExpect(content().json( - objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedMsg))))); - } - - @Test - public void addCategoryOptions_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { - String categoryName = "catName13"; - AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); - req.options = ImmutableList.of("option second", "first option"); - - given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) - .willThrow(new RuntimeException()); - - prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(req)) - .andExpect(status().isInternalServerError()); - } - - @Test - public void updateNameForOption_shouldReturnMultiStatus_whenErrorsExist() throws Exception { - String categoryName = "catName4"; - CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id1", "name1"); - AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse( - ImmutableList.of("error one", "error two")); - - given(service - .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) - .willReturn(addCategoryOptionResponse); - - prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOptionRep)) - .andExpect(status().isMultiStatus()) - .andExpect( - content().json(objectMapper - .writeValueAsString(addCategoryOptionResponse))); - } - - @Test - public void updateNameForOption_shouldReturnOk_whenNoErrorsExist() throws Exception { - String categoryName = "catName5"; - CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id2", "name2"); - AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); - - given(service - .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) - .willReturn(addCategoryOptionResponse); - prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOptionRep)) - .andExpect(status().isOk()) - .andExpect(content().json( - objectMapper.writeValueAsString(addCategoryOptionResponse))); - } - - @Test - public void updateNameForOption_shouldReturnForbidden_whenForbiddenExceptionIsThrown() throws Exception { - String categoryName = "catName6"; - CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id3", "name3"); - - given(service - .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) - .willThrow(new ForbiddenException()); - prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOptionRep)) - .andExpect(status().isForbidden()) - .andExpect(content().json( - objectMapper - .writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of("HTTP 403 Forbidden"))))); - } - - @Test - public void updateNameForOption_shouldReturnNotFound_whenUnfoundedIsThrown() throws Exception { - String unfoundedOptionMsg = "unfounded category option exception message"; - String categoryName = "catName7"; - CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id4", "name4"); - - given(service - .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) - .willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryOptionException(unfoundedOptionMsg)); - - prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOptionRep)) - .andExpect(status().isNotFound()) - .andExpect(content().json( - objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedOptionMsg))))); - } - - @Test - public void updateNameForOption_shouldReturnConflict_whenAlreadyExistOptionNameIsThrown() throws Exception { - String conflictMsg = "already exists option name exception message"; - String categoryName = "catName8"; - CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id5", "name5"); - - given(service - .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) - .willThrow(new CategoryParameterServiceImpl.AlreadyExistOptionNameException(conflictMsg)); - - prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOptionRep)) - .andExpect(status().isConflict()) - .andExpect(content().json( - objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(conflictMsg))))); - } - - @Test - public void updateNameForOption_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { - String categoryName = "catName18"; - CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id6", "name6"); - - given(service - .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) - .willThrow(new RuntimeException()); - - prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOptionRep)) - .andExpect(status().isInternalServerError()); - } - - @Test - public void getCategoryParameter_shouldReturnExistingMap() throws Exception { - CategoryParametersResponse categoryParametersResponse = - new CategoryParametersResponse( - ImmutableMap.of( - "key1", ImmutableList.of( - new CategoryParameterOptionRep("testId", "testName")))); - - given(service.getCategoryParameters(PARAMETER_STANDARDIZATION)) - .willReturn(categoryParametersResponse); - - mockMvc.perform(get(MAINTENANCE_CATEGORY_PATH) - .param("familyName", "PARAMETER_STANDARDIZATION") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(categoryParametersResponse))); - } - - @Test - public void getCategoryParameter_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { - given(service.getCategoryParameters(PARAMETER_STANDARDIZATION)) - .willThrow(new RuntimeException()); - - mockMvc.perform(get(MAINTENANCE_CATEGORY_PATH) - .param("familyName", "PARAMETER_STANDARDIZATION") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isInternalServerError()); - } - - @Test - public void deleteCategoryOption_shouldReturnOk_whenNoExceptionIsThrown() throws Exception { - String categoryName = "catName9"; - CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id1", "name1", - new CategoryParameter()); - - prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOption)) - .andExpect(status().isOk()); - - then(service).should(times(1)) - .deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); - } - - @Test - public void deleteCategoryOption_shouldReturnNotFound_whenUnfoundedExceptionIsThrown() throws Exception { - String unfoundedMsg = "unfounded category exception message"; - String categoryName = "catName10"; - CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id2", "name2", - new CategoryParameter()); - - willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryException(unfoundedMsg)) - .given(service).deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); - - prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOption)) - .andExpect(status().isNotFound()) - .andExpect(content().json( - objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedMsg))))); - } - - @Test - public void deleteCategoryOption_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { - String categoryName = "catName19"; - CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id3", "name3", - new CategoryParameter()); - - willThrow(new RuntimeException()).given(service) - .deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); - - prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, - objectMapper.writeValueAsString(categoryParameterOption)) - .andExpect(status().isInternalServerError()); - } - - private ArgumentMatcher requestMatcher(T t) { - return new ArgumentMatcher() { - @Override - public boolean matches(Object o) { - return t.equals(o); - } - }; - } - - private ResultActions prepareRequestExpectations( - BiFunction httpMethod, - String path, String name, String jsonContent) throws Exception { - return mockMvc.perform(httpMethod.apply(path, name) - .contentType(MediaType.APPLICATION_JSON) - .content(jsonContent)); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java deleted file mode 100644 index d1e09ce8..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java +++ /dev/null @@ -1,391 +0,0 @@ -package org.onap.vid.controllers; - -import static org.junit.Assert.*; - -import javax.servlet.http.HttpServletRequest; - -import org.junit.Test; -import org.onap.vid.mso.MsoBusinessLogicImpl; -import org.onap.vid.mso.rest.RequestDetails; -import org.onap.vid.mso.rest.RequestDetailsWrapper; -import org.springframework.http.ResponseEntity; - -public class MsoControllerNewTest { - - private MsoController createTestSubject() { - try { - return new MsoController(new MsoBusinessLogicImpl(null,null)); - } catch (Exception e) { - return null; - } - } - - @Test - public void testCreateSvcInstance() throws Exception { - MsoController testSubject; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createSvcInstance(request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testCreateVnf() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createVnf(serviceInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testCreateNwInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createNwInstance(serviceInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testCreateVolumeGroupInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String vnfInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createVolumeGroupInstance(serviceInstanceId, vnfInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testCreateVfModuleInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String vnfInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createVfModuleInstance(serviceInstanceId, vnfInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testCreateConfigurationInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - HttpServletRequest request = null; - RequestDetailsWrapper mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createConfigurationInstance(serviceInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDeleteSvcInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - String result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteSvcInstance(serviceInstanceId, request, mso_request, ""); - } catch (Exception e) { - } - } - - @Test - public void testDeleteVnf() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String vnfInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVnf(serviceInstanceId, vnfInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDeleteConfiguration() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String configurationId = ""; - RequestDetailsWrapper mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteConfiguration(serviceInstanceId, configurationId, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testActivateConfiguration() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String configurationId = ""; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.activateConfiguration(serviceInstanceId, configurationId, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDeactivateConfiguration() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String configurationId = ""; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deactivateConfiguration(serviceInstanceId, configurationId, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDisablePortOnConfiguration() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String configurationId = ""; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.disablePortOnConfiguration(serviceInstanceId, configurationId, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testEnablePortOnConfiguration() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String configurationId = ""; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.enablePortOnConfiguration(serviceInstanceId, configurationId, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDeleteVfModule() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String vnfInstanceId = ""; - String vfModuleId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVfModule(serviceInstanceId, vnfInstanceId, vfModuleId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDeleteVolumeGroupInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String vnfInstanceId = ""; - String volumeGroupId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVolumeGroupInstance(serviceInstanceId, vnfInstanceId, volumeGroupId, request, - mso_request); - } catch (Exception e) { - } - } - - @Test - public void testDeleteNwInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - String networkInstanceId = ""; - HttpServletRequest request = null; - RequestDetails mso_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteNwInstance(serviceInstanceId, networkInstanceId, request, mso_request); - } catch (Exception e) { - } - } - - @Test - public void testGetOrchestrationRequest() throws Exception { - MsoController testSubject; - String requestId = ""; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getOrchestrationRequest(requestId, request); - } catch (Exception e) { - } - } - - @Test - public void testGetOrchestrationRequests() throws Exception { - MsoController testSubject; - String filterString = ""; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getOrchestrationRequests(filterString, request); - } catch (Exception e) { - } - } - - @Test - public void testActivateServiceInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - RequestDetails requestDetails = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.activateServiceInstance(serviceInstanceId, requestDetails); - } catch (Exception e) { - } - } - - @Test - public void testDeactivateServiceInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - RequestDetails requestDetails = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deactivateServiceInstance(serviceInstanceId, requestDetails); - } catch (Exception e) { - } - } - - @Test - public void testManualTaskComplete() throws Exception { - MsoController testSubject; - String taskId = ""; - RequestDetails requestDetails = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.manualTaskComplete(taskId, requestDetails); - } catch (Exception e) { - } - } - - @Test - public void testRemoveRelationshipFromServiceInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - RequestDetails requestDetails = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.removeRelationshipFromServiceInstance(serviceInstanceId, requestDetails); - } catch (Exception e) { - } - } - - @Test - public void testAddRelationshipToServiceInstance() throws Exception { - MsoController testSubject; - String serviceInstanceId = ""; - RequestDetails requestDetails = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.addRelationshipToServiceInstance(serviceInstanceId, requestDetails); - } catch (Exception e) { - } - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java deleted file mode 100644 index 0d155954..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.onap.vid.controllers; - -import org.apache.commons.lang.StringEscapeUtils; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.controllers.MsoConfig; -import org.onap.vid.controllers.MsoController; -import org.onap.vid.domain.mso.RequestInfo; -import org.onap.vid.factories.MsoRequestFactory; -import org.onap.vid.mso.rest.Request; -import org.onap.vid.mso.rest.RequestDetails; -import org.onap.vid.mso.rest.Task; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.web.WebAppConfiguration; -import org.testng.Assert; -import org.testng.Assert.*; -import org.testng.annotations.Test; - -import java.util.List; - - -@WebAppConfiguration -@ContextConfiguration(classes = {SystemProperties.class, MsoConfig.class}) -public class MsoControllerTest extends AbstractTestNGSpringContextTests { - - @Autowired - MsoRequestFactory msoRequestFactory; - - @Test(enabled = false) - public void testInstanceCreationNew() throws Exception { - - RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); - //TODO: make ths test to really test something - //ResponseEntity responseEntityNew = msoController.createSvcInstanceNew(null, requestDetails); - ResponseEntity responseEntity = msoController.createSvcInstance(null, requestDetails); - //Assert.assertEquals(responseEntityNew, responseEntity); - - } - - @Test(enabled = false) - public void testInstanceCreationLocalWithRest() throws Exception { - - RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); - ResponseEntity responseEntityNew = msoController.createSvcInstance(null, requestDetails); - //TODO: make ths test to really test something -// ResponseEntity responseEntityRest = msoController.createSvcInstanceNewRest(null, requestDetails); -// -// Assert.assertEquals(responseEntityNew.getBody(), responseEntityRest.getBody()); - - } - - @Test(enabled = false) - public void testInstanceCreation() throws Exception { - - RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); - ResponseEntity responseEntity = msoController.createSvcInstance(null, requestDetails); - - - Assert.assertEquals(responseEntity.getBody(), "{ \"status\": 200, \"entity\": {\n" + - " \"requestReferences\": {\n" + - " \"instanceId\": \"ba00de9b-3c3e-4b0a-a1ad-0c5489e711fb\",\n" + - " \"requestId\": \"311cc766-b673-4a50-b9c5-471f68914586\"\n" + - " }\n" + - "}}"); - - } - - @Test(enabled = false) - public void testGetOrchestrationRequestsForDashboard() throws Exception { - MsoController msoController = new MsoController(null); - List orchestrationRequestsForDashboard = msoController.getOrchestrationRequestsForDashboard(); - - Assert.assertEquals(orchestrationRequestsForDashboard.size(), 2); - } - - @Test(enabled = false) - public void testGetManualTasksByRequestId() throws Exception { - MsoController msoController = new MsoController(null); - List orchestrationRequestsForDashboard = msoController.getManualTasksByRequestId("za1234d1-5a33-55df-13ab-12abad84e335"); - - Assert. assertEquals(orchestrationRequestsForDashboard.get(0).getTaskId(), "daf4dd84-b77a-42da-a051-3239b7a9392c"); - } - - - public void testCompleteManualTask() throws Exception { // TODO not done yet - RequestInfo requestInfo = new RequestInfo(); - requestInfo.setResponseValue("rollback"); - requestInfo.setRequestorId("abc"); - requestInfo.setSource("VID"); - RequestDetails requestDetails = new RequestDetails(); - requestDetails.setRequestInfo(requestInfo); - MsoController msoController = new MsoController(null); - ResponseEntity responseEntity = msoController.manualTaskComplete("daf4dd84-b77a-42da-a051-3239b7a9392c", requestDetails); - String assertString = "{ \\\"status\\\": 200, \\\"entity\\\": {\\n\" +\n" + - " \" \\\"taskRequestReference\\\": {\\n\" +\n" + - " \" \\\"taskId\\\": \\\"daf4dd84-b77a-42da-a051-3239b7a9392c\\\"\\n\" +\n" + - " \" }\\n\" +\n" + - " \"}\\n\" +\n" + - " \"}"; - Assert.assertEquals(responseEntity.getBody(), StringEscapeUtils.unescapeJava(assertString)); - } - - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java deleted file mode 100644 index 33bed45e..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/PolicyControllerTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.onap.vid.controllers; - -import javax.servlet.http.HttpServletRequest; - -import org.json.simple.JSONObject; -import org.junit.Test; -import org.onap.vid.policy.PolicyResponseWrapper; -import org.springframework.http.ResponseEntity; - -public class PolicyControllerTest { - - private PolicyController createTestSubject() { - return new PolicyController(); - } - - @Test - public void testGetPolicyInfo() throws Exception { - PolicyController testSubject; - HttpServletRequest request = null; - JSONObject policy_request = null; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getPolicyInfo(request, policy_request); - }catch(Exception e){} - } - -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java deleted file mode 100644 index f1740395..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/PromiseEcompRequestIdFilterTest.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.onap.vid.controllers; - -import com.google.common.collect.ImmutableMap; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; -import org.onap.portalsdk.core.web.support.UserUtils; -import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; -import org.springframework.mock.web.MockHttpServletResponse; -import org.testng.annotations.Test; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.*; -import java.util.function.Function; - -import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; -import static org.onap.portalsdk.core.util.SystemProperties.ECOMP_REQUEST_ID; - -@Test -public class PromiseEcompRequestIdFilterTest { - - private final String anotherHeader = "ANDREI_RUBLEV"; - private final String anotherValue = "foo value"; - private final String mixedCaseHeader = "x-ecomp-REQUESTID"; - - @Test - public void givenRequestIdHeader_headerValueNotChanged() throws IOException, ServletException { - - final String someTxId = "863850e2-8545-4efd-94b8-afba5f52b3d5"; - - final ImmutableMap incomingRequestHeaders = ImmutableMap.of( - anotherHeader, anotherValue, - ECOMP_REQUEST_ID, someTxId - ); - - buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId)); - } - - @Test - public void givenMixedCaseRequestIdHeader_headerValueNotChanged() throws IOException, ServletException { - - final String someTxId = "729bbd8d-b0c2-4809-a794-dcccd9cda2c0"; - - final ImmutableMap incomingRequestHeaders = ImmutableMap.of( - mixedCaseHeader, someTxId, - anotherHeader, anotherValue - ); - - buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId)); - } - - @Test - public void givenNoRequestIdHeader_headerValueWasGenerated() throws IOException, ServletException { - - final ImmutableMap incomingRequestHeaders = ImmutableMap.of( - anotherHeader, anotherValue - ); - - buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, UserUtils::getRequestId); - } - - - private void buildRequestThenRunThroughFilterAndAssertResultRequestHeaders( - ImmutableMap originalRequestHeaders, - Function txIdExtractor - ) throws IOException, ServletException { - HttpServletRequest servletRequest = createMockedHttpServletRequest(originalRequestHeaders); - HttpServletResponse servletResponse = createMockedHttpServletResponse(); - - final FilterChain capturingFilterChain = Mockito.mock(FilterChain.class); - - ////////////////// - // - // doFilter() is the function under test - // - new PromiseEcompRequestIdFilter().doFilter(servletRequest, servletResponse, capturingFilterChain); - // - ////////////////// - - final ServletRequest capturedServletRequest = extractCapturedServletRequest(capturingFilterChain); - final ServletResponse capturedServletResponse = extractCapturedServletResponse(capturingFilterChain); - final String expectedTxId = txIdExtractor.apply((HttpServletRequest) capturedServletRequest); - - assertRequestObjectHeaders(capturedServletRequest, expectedTxId); - assertResponseObjectHeaders(capturedServletResponse, expectedTxId); - } - - - private void assertRequestObjectHeaders(ServletRequest request, String expectedTxId) { - /* - Assert that: - - Two headers are in place - - Direct value extraction is as expected - - UserUtils.getRequestId() returns correct and valid value - */ - final HttpServletRequest httpServletRequest = (HttpServletRequest) request; - - assertThat(Collections.list(httpServletRequest.getHeaderNames()), - containsInAnyOrder(equalToIgnoringCase(ECOMP_REQUEST_ID), equalToIgnoringCase(anotherHeader))); - - assertThat(httpServletRequest.getHeader(anotherHeader), is(anotherValue)); - - assertThat(httpServletRequest.getHeader(ECOMP_REQUEST_ID), is(expectedTxId)); - assertThat(httpServletRequest.getHeader(mixedCaseHeader), is(expectedTxId)); - - assertThat(UserUtils.getRequestId(httpServletRequest), is(expectedTxId)); - assertThat(UserUtils.getRequestId(httpServletRequest), is(not(emptyOrNullString()))); - } - - private void assertResponseObjectHeaders(ServletResponse response, String txId) { - final String REQUEST_ID_HEADER_NAME_IN_RESPONSE = mixedCaseHeader + "-echo"; - final HttpServletResponse httpServletResponse = (HttpServletResponse) response; - - assertThat("header " + REQUEST_ID_HEADER_NAME_IN_RESPONSE.toLowerCase() + " in response must be provided", - httpServletResponse.getHeader(REQUEST_ID_HEADER_NAME_IN_RESPONSE), is(txId)); - } - - - - private HttpServletRequest createMockedHttpServletRequest(Map requestHeaders) { - HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); - requestHeaders.forEach((k, v) -> { - Mockito.when(servletRequest.getHeader(argThat(s -> equalsIgnoreCase(s, k)))).thenReturn(v); - Mockito.when(servletRequest.getHeaders(argThat(s -> equalsIgnoreCase(s, k)))).then(returnEnumerationAnswer(v)); - }); - Mockito.when(servletRequest.getHeaderNames()).then(returnEnumerationAnswer(requestHeaders.keySet())); - return servletRequest; - } - - private HttpServletResponse createMockedHttpServletResponse() { - return new MockHttpServletResponse(); - } - - private static Answer> returnEnumerationAnswer(String ... items) { - return returnEnumerationAnswer(Arrays.asList(items)); - } - - private static Answer> returnEnumerationAnswer(Collection items) { - return invocation -> Collections.enumeration(items); - } - - private Function specificTxId(String someTxId) { - return r -> someTxId; - } - - private ServletRequest extractCapturedServletRequest(FilterChain capturingFilterChain) throws IOException, ServletException { - ArgumentCaptor captor = ArgumentCaptor.forClass(ServletRequest.class); - Mockito.verify(capturingFilterChain).doFilter(captor.capture(), any()); - return captor.getValue(); - } - - private ServletResponse extractCapturedServletResponse(FilterChain capturingFilterChain) throws IOException, ServletException { - ArgumentCaptor captor = ArgumentCaptor.forClass(ServletResponse.class); - Mockito.verify(capturingFilterChain).doFilter(any(), captor.capture()); - return captor.getValue(); - } - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java deleted file mode 100644 index b4a6a8f9..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/PropertyControllerTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.onap.vid.controllers; - -import javax.servlet.http.HttpServletRequest; - -import org.junit.Test; -import org.onap.vid.controllers.PropertyController; -import org.springframework.http.ResponseEntity; -import org.springframework.web.servlet.ModelAndView; - -public class PropertyControllerTest { - - private PropertyController createTestSubject() { - return new PropertyController(); - } - - @Test - public void testWelcome() throws Exception { - PropertyController testSubject; - HttpServletRequest request = null; - ModelAndView result; - - // default test - testSubject = createTestSubject(); - result = testSubject.welcome(request); - } - - - @Test - public void testGetProperty() throws Exception { - PropertyController testSubject; - String name = ""; - String defaultvalue = ""; - HttpServletRequest request = null; - ResponseEntity result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getProperty(name, defaultvalue, request); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java deleted file mode 100644 index 11ab2fcc..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/RoleGeneratorControllerTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.onap.vid.controllers; - -import org.junit.Test; -import org.springframework.http.ResponseEntity; - -public class RoleGeneratorControllerTest { - - private RoleGeneratorController createTestSubject() { - return new RoleGeneratorController(); - } - - @Test - public void testGenerateRoleScript() throws Exception { - RoleGeneratorController testSubject; - boolean firstRun = false; - ResponseEntity result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.generateRoleScript(firstRun); - } catch (Exception e) { - - } - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java deleted file mode 100644 index 317c8e50..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/ToscaParserMockHelper.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.onap.vid.controllers; - -import org.onap.vid.model.NewServiceModel; - -/** - * Created by moriya1 on 04/07/2017. - */ -public class ToscaParserMockHelper { - - private String uuid; - private String filePath; - private NewServiceModel newServiceModel; - - public ToscaParserMockHelper(String uuid, String filePath) { - this.uuid = uuid; - this.filePath = filePath; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public NewServiceModel getNewServiceModel() { - return newServiceModel; - } - - public void setNewServiceModel(NewServiceModel newServiceModel) { - this.newServiceModel = newServiceModel; - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java deleted file mode 100644 index 198680af..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java +++ /dev/null @@ -1,204 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Modifications Copyright 2018 Nokia - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.vid.controllers; - - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import org.apache.log4j.BasicConfigurator; -import org.codehaus.jackson.map.ObjectMapper; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.beans.SecureServices; -import org.onap.vid.asdc.beans.Service; -import org.onap.vid.asdc.beans.ServiceBuilder; -import org.onap.vid.model.*; -import org.onap.vid.model.PombaInstance.PombaRequest; -import org.onap.vid.model.PombaInstance.ServiceInstance; -import org.onap.vid.roles.RoleProvider; -import org.onap.vid.services.AaiService; -import org.onap.vid.services.PombaService; -import org.onap.vid.services.VidService; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import javax.ws.rs.core.MediaType; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.IntStream; - -import static java.util.stream.Collectors.toMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.not; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.then; -import static org.mockito.Mockito.times; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(MockitoJUnitRunner.class) -public class VidControllerTest { - - public static final String REST_MODELS_SERVICES = "/rest/models/services"; - public static final String REST_MODELS_SERVICES_UUID = "/rest/models/services/{uuid}"; - public static final String REST_MODELS_RESET = "/rest/models/reset"; - public static final String REST_MODELS_SERVICES_VERIFY_SERVICE = "/rest/models/services/verifyService"; - @Mock - private VidService vidService; - @Mock - private AaiService aaiService; - @Mock - private RoleProvider roleProvider; - @Mock - private PombaService pombaService; - - private VidController vidController; - private MockMvc mockMvc; - private ObjectMapper objectMapper; - - private String uuid1; - private String uuid2; - private String uuid3; - - @Before - public void setUp() { - vidController = new VidController(vidService, aaiService, roleProvider, pombaService); - BasicConfigurator.configure(); - mockMvc = MockMvcBuilders.standaloneSetup(vidController).build(); - objectMapper = new ObjectMapper(); - - uuid1 = UUID.randomUUID().toString(); - uuid2 = UUID.randomUUID().toString(); - uuid3 = UUID.randomUUID().toString(); - } - - @Test - public void getServices_shouldReturnService_whenServiceExists() throws Exception { - List services = ImmutableList.of(createService(uuid1, 1), createService(uuid2, 2), createService(uuid3, 3)); - - given(aaiService.getServicesByDistributionStatus()).willReturn(services); - - SecureServices secureServices = new SecureServices(); - secureServices.setServices(services); - secureServices.setReadOnly(false); - - mockMvc.perform(get(REST_MODELS_SERVICES) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(secureServices))); - } - - @Test - public void getService_shouldReturnService_whenNoExceptionIsThrown() throws Exception { - ServiceModel model = expectedServiceModel(uuid1); - - given(vidService.getService(uuid1)).willReturn(model); - - mockMvc.perform(get(REST_MODELS_SERVICES_UUID, uuid1) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().json(objectMapper.writeValueAsString(model))); - } - - @Test - public void getService_shouldThrow_whenAsdcCatalogExceptionIsThrown() throws Exception { - String testUuid = UUID.randomUUID().toString(); - - given(vidService.getService(testUuid)).willThrow(new AsdcCatalogException("error msg")); - - mockMvc.perform(get(REST_MODELS_SERVICES_UUID, testUuid) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isServiceUnavailable()); - } - - @Test - public void invalidateServiceModelCache_shouldReturnAccepted() throws Exception { - mockMvc.perform(post(REST_MODELS_RESET) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isAccepted()); - - then(vidService).should(times(1)).invalidateServiceCache(); - } - - @Test - public void verifyServiceInstance_shouldReturnOk() throws Exception { - PombaRequest pombaRequest = new PombaRequest(); - pombaRequest.serviceInstanceList = ImmutableList.of(new ServiceInstance()); - - mockMvc.perform(post(REST_MODELS_SERVICES_VERIFY_SERVICE) - .contentType(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(pombaRequest))) - .andExpect(status().isOk()); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(PombaRequest.class); - then(pombaService).should(times(1)).verify(argumentCaptor.capture()); - - assertThat(pombaRequest).isEqualToComparingFieldByFieldRecursively(argumentCaptor.getValue()); - } - - private ServiceModel expectedServiceModel(String uuid) { - final ServiceModel serviceModel = getModelsByUuid().get(uuid); - Assert.assertThat(serviceModel, is(not(nullValue()))); - return serviceModel; - } - - private Service createService(String uuid, int i) { - return new ServiceBuilder().setUuid(uuid).setInvariantUUID("invariantUUID" + i) - .setCategory("category" + i).setVersion("version" + i).setName("name" + i) - .setDistributionStatus("distStatus" + i).setToscaModelURL("toscaModelUrl" + i).build(); - } - - private ServiceModel createServiceModel(int i) { - ServiceModel model = new ServiceModel(); - - model.setCollectionResource(ImmutableMap.of("resKey" + i, new CR())); - model.setNetworks(ImmutableMap.of("network" + i, new Network())); - model.setPnfs(ImmutableMap.of("pnf" + i, new Node())); - model.setServiceProxies(ImmutableMap.of("servProxy" + i, new ServiceProxy())); - model.setVfModules(ImmutableMap.of("vfmod" + i, new VfModule())); - model.setVnfs(ImmutableMap.of("vnf" + i, new VNF())); - model.setVolumeGroups(ImmutableMap.of("volgroup" + i, new VolumeGroup())); - model.setService(new org.onap.vid.model.Service()); - return model; - } - - private Map getModelsByUuid() { - ServiceModel serviceModel1 = createServiceModel(1); - ServiceModel serviceModel2 = createServiceModel(2); - ServiceModel serviceModel3 = createServiceModel(3); - - List pseudoServiceModels = ImmutableList.of(serviceModel1, serviceModel2, serviceModel3); - List uuids = ImmutableList.of(uuid1, uuid2, uuid3); - return IntStream.range(0, pseudoServiceModels.size()).boxed() - .collect(toMap(i -> uuids.get(i), i -> pseudoServiceModels.get(i))); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java deleted file mode 100644 index 7d61f98f..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/ViewEditSubControllerTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.onap.vid.controllers; -//package org.onap.vid.controller; -// -//import javax.servlet.http.HttpServletRequest; -// -//import org.junit.Test; -//import org.springframework.web.servlet.ModelAndView; -// -//public class ViewEditSubControllerTest { -// -// private ViewEditSubController createTestSubject() { -// return new ViewEditSubController(); -// } -// -// @Test -// public void testWelcome() throws Exception { -// ViewEditSubController testSubject; -// HttpServletRequest request = null; -// ModelAndView result; -// -// // default test -// testSubject = createTestSubject(); -// result = testSubject.welcome(request); -// } -// -// -// @Test -// public void testGetViewName() throws Exception { -// ViewEditSubController testSubject; -// String result; -// -// // default test -// testSubject = createTestSubject(); -// result = testSubject.getViewName(); -// } -// -// @Test -// public void testSetViewName() throws Exception { -// ViewEditSubController testSubject; -// String viewName = ""; -// -// // default test -// testSubject = createTestSubject(); -// testSubject.setViewName(viewName); -// } -//} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java new file mode 100644 index 00000000..61a54f25 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java @@ -0,0 +1,88 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.model.GroupProperties; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.VfModule; +import org.onap.vid.services.VidService; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.*; + +public class CommandUtilsTest { + + @InjectMocks + CommandUtils commandUtils; + + @Mock + VidService vidService; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @AfterMethod + public void resetVidService() { + reset(vidService); + } + + @DataProvider + public static Object[][] trueAndFalse() { + return new Object[][]{ {true}, {false} }; + } + + @Test(dataProvider="trueAndFalse") + void testIsVfModelIsBaseModule(boolean isBase) throws AsdcCatalogException { + final String serviceModelUuid = UUID.randomUUID().toString(); + final String vfModuleUuid = UUID.randomUUID().toString(); + + ServiceModel mockedServiceModel = mock(ServiceModel.class); + VfModule mockedVfModule = mock(VfModule.class); + GroupProperties mockedGroupProperties = mock(GroupProperties.class); + Map vfModulesMap = ImmutableMap.of(randomAlphanumeric(10), mockedVfModule); + + when(vidService.getService(serviceModelUuid)).thenReturn(mockedServiceModel); + when(mockedServiceModel.getVfModules()).thenReturn(vfModulesMap); + when(mockedVfModule.getUuid()).thenReturn(vfModuleUuid); + when(mockedVfModule.getProperties()).thenReturn(mockedGroupProperties); + when(mockedGroupProperties.getBaseModule()).thenReturn(isBase); + + assertThat(commandUtils.isVfModuleBaseModule(serviceModelUuid, vfModuleUuid), equalTo(isBase)); + } + + @Test(expectedExceptions = AsdcCatalogException.class) + void whenCantFindModelInSdc_thenExceptionIsThrown() throws AsdcCatalogException { + String serviceModelUuid = UUID.randomUUID().toString(); + when(vidService.getService(serviceModelUuid)).thenReturn(null); + commandUtils.isVfModuleBaseModule(serviceModelUuid, "abc"); + } + + @Test(expectedExceptions = AsdcCatalogException.class) + void whenCantFindVfModuleInModel_thenExceptionIsThrown() throws AsdcCatalogException { + + String serviceModelUuid = UUID.randomUUID().toString(); + + ServiceModel mockedServiceModel = mock(ServiceModel.class); + Map emptyMap = Collections.emptyMap(); + + when(vidService.getService(serviceModelUuid)).thenReturn(mockedServiceModel); + when(mockedServiceModel.getVfModules()).thenReturn(emptyMap); + + commandUtils.isVfModuleBaseModule(serviceModelUuid, "abc"); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java deleted file mode 100644 index bc623928..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.command; - - -import io.joshworks.restclient.http.HttpResponse; -import org.mockito.Mock; -import org.onap.vid.job.Job; -import org.onap.vid.job.NextCommand; -import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.rest.AsyncRequestStatus; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.services.AuditService; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import javax.ws.rs.ProcessingException; -import java.util.UUID; - - -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -public class InProgressStatusCommandTest { - - @Mock - private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic; - - @Mock - private MsoInterface msoInterface; - - @Mock - private AuditService auditService; - - @Mock - private HttpResponse msoResponse; - - @Mock - private AsyncRequestStatus asyncRequestStatus; - - @Mock - private AsyncRequestStatus.Request request; - - private UUID uuid = UUID.randomUUID(); - - private InProgressStatusCommand inProgressStatusCommand; - - @BeforeMethod - public void setUp() { - initMocks(this); - - inProgressStatusCommand = new InProgressStatusCommand(asyncInstantiationBusinessLogic, msoInterface, auditService, uuid, "sampleRequestId"); - - when(asyncInstantiationBusinessLogic.getOrchestrationRequestsPath()).thenReturn("http://localhost:8080/samplePath"); - when(msoInterface.get("http://localhost:8080/samplePath/sampleRequestId", AsyncRequestStatus.class)).thenReturn(msoResponse); - when(msoResponse.getBody()).thenReturn(asyncRequestStatus); - } - - - @Test - public void whenSOReturnsErrorShouldSetProperFailureStateAndReturnRetryCommand() { - when(msoResponse.getStatus()).thenReturn(500); - - NextCommand call = inProgressStatusCommand.call(); - - assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS); - assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); - - verify(auditService).setFailedAuditStatusFromMso(uuid, "sampleRequestId", 500, asyncRequestStatus.toString()); - } - - @Test - public void shouldProperlyHandleFailedInstantiation() { - when(msoResponse.getStatus()).thenReturn(200); - when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenReturn(Job.JobStatus.FAILED); - asyncRequestStatus.request = request; - - NextCommand call = inProgressStatusCommand.call(); - - assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); - assertThat(call.getStatus()).isEqualTo(Job.JobStatus.FAILED); - - verify(asyncInstantiationBusinessLogic).handleFailedInstantiation(uuid); - verify(asyncInstantiationBusinessLogic).auditMsoStatus(uuid, request); - } - - @Test - public void shouldRetryCommandWithPausedState() { - when(msoResponse.getStatus()).thenReturn(200); - when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenReturn(Job.JobStatus.PAUSE); - asyncRequestStatus.request = request; - - NextCommand call = inProgressStatusCommand.call(); - - assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); - assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS); - - verify(asyncInstantiationBusinessLogic).auditMsoStatus(uuid, request); - verify(asyncInstantiationBusinessLogic).updateServiceInfoAndAuditStatus(uuid, Job.JobStatus.PAUSE); - } - - @Test - public void shouldRetryCommandExitedWithProcessingException() { - when(msoResponse.getStatus()).thenReturn(200); - when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenThrow(new ProcessingException("")); - - NextCommand call = inProgressStatusCommand.call(); - - assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); - assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS); - } - - @Test - public void shouldSetStoppedStatusWhenRuntimeExceptionOccurs() { - when(msoResponse.getStatus()).thenReturn(200); - when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenThrow(new RuntimeException()); - - NextCommand call = inProgressStatusCommand.call(); - - assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); - assertThat(call.getStatus()).isEqualTo(Job.JobStatus.STOPPED); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java new file mode 100644 index 00000000..2e813971 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java @@ -0,0 +1,83 @@ +package org.onap.vid.job.command; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.UUID; +import java.util.stream.Stream; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; +import static org.testng.AssertJUnit.assertEquals; + +public class InProgressStatusServiceTest { + + @Mock + private RestMsoImplementation restMso; + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @InjectMocks + private InProgressStatusService inProgressStatusService; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @DataProvider + public static Object[][] jobStatuses() { + return Stream.of(Job.JobStatus.values()) + .map(student -> new Object[] { student }) + .toArray(Object[][]::new); + } + + @Test(dataProvider = "jobStatuses") + public void whenGetFromMsoRequestStatus_returnItToCaller(Job.JobStatus expectedJobStatus) { + + UUID jobUuid = UUID.randomUUID(); + String userId = "mockedUserID"; + String requestId = UUID.randomUUID().toString(); + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); + + when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(""); + + RestObject msoResponse = mock(RestObject.class); + AsyncRequestStatus requestStatus = AsyncInstantiationBaseTest.asyncRequestStatusResponse(""); + + when(msoResponse.getStatusCode()).thenReturn(200); + when(msoResponse.get()).thenReturn(requestStatus); + when(restMso.GetForObject(contains(requestId), eq(AsyncRequestStatus.class))).thenReturn(msoResponse); + + when(asyncInstantiationBL.calcStatus(any())).thenReturn(expectedJobStatus); + + ExpiryChecker expiryChecker = mock(ExpiryChecker.class); + when(expiryChecker.isExpired(any())).thenReturn(false); + + JobSharedData sharedData = new JobSharedData(jobUuid, userId, serviceInstantiation); + Job.JobStatus actualJobStatus = inProgressStatusService.call(expiryChecker, sharedData, requestId); + assertEquals(expectedJobStatus, actualJobStatus); + + verify(asyncInstantiationBL).auditMsoStatus(eq(jobUuid), same(requestStatus.request)); + + //verify we don't update service info during this case, which shall stay in_progress + verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any()); + + + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java new file mode 100644 index 00000000..4cd00174 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java @@ -0,0 +1,85 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.beanutils.BeanUtils; +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.serviceInstantiation.InstanceGroup; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.http.HttpMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Optional; +import java.util.Set; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class InstanceGroupCommandTest { + + @Mock(answer = Answers.RETURNS_MOCKS) + RestMsoImplementation restMso; + + @Mock InstanceGroup instanceGroupRequest; + + @Mock(answer = Answers.RETURNS_MOCKS) + MsoResultHandlerService msoResultHandlerService; + + @Mock WatchChildrenJobsBL watchChildrenJobsBL; + + @Mock(answer = Answers.RETURNS_MOCKS) + AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Mock InProgressStatusService inProgressStatusService; + + @InjectMocks + private InstanceGroupCommand command; + + @BeforeMethod + public void initMocks() { + command = null; + MockitoAnnotations.initMocks(this); + } + + @Test + public void createMyself_callsMso() { + final ModelInfo serviceModelInfo = setRandomStrings(new ModelInfo()); + final String serviceInstanceId = "service-instance-id"; + final String userId = "ff3223"; + + command.init(new JobSharedData( + null, userId, instanceGroupRequest + ), ImmutableMap.of( + "resourceModelInfos", ImmutableMap.of("SERVICE_MODEL_INFO", serviceModelInfo), + "resourceInstancesIds", ImmutableMap.of("SERVICE_INSTANCE_ID", serviceInstanceId) + )); + + command.createMyself(); + + verify(asyncInstantiationBL).generateInstanceGroupInstantiationRequest( + same(instanceGroupRequest), eq(serviceModelInfo), eq(serviceInstanceId), eq(userId)); + verify(restMso, only()).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty())); + + } + + private ModelInfo setRandomStrings(ModelInfo object) { + try { + Set fields = BeanUtils.describe(object).keySet(); + BeanUtils.populate(object, + fields.stream().collect(toMap(identity(), s -> randomAlphanumeric(4)))); + return object; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java index b51553be..2138b77c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java @@ -1,17 +1,22 @@ package org.onap.vid.job.command; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobCommand; import org.onap.vid.job.JobType; +import org.onap.vid.job.impl.JobSharedData; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.stream.Collectors; @@ -48,19 +53,48 @@ public class JobCommandFactoryTest { } + public static class MockedRequest implements JobAdapter.AsyncJobRequest { + + final public int x; + final public String y; + + @JsonCreator + public MockedRequest(@JsonProperty("x")int x, @JsonProperty("y")String y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof MockedRequest)) return false; + MockedRequest that = (MockedRequest) o; + return x == that.x && + Objects.equals(y, that.y); + } + + @Override + public int hashCode() { + + return Objects.hash(x, y); + } + } + @Test(dataProvider = "jobTypes") public void givenJob_createCommandCallsTheInitAndReturnsTheInstance(JobType jobType) { final UUID uuid = UUID.randomUUID(); final Map data = ImmutableMap.of("foo", "bar"); + final JobSharedData sharedData = new JobSharedData(uuid, "userid", new MockedRequest(1,"a")); when(job.getType()).thenReturn(jobType); when(job.getUuid()).thenReturn(uuid); when(job.getData()).thenReturn(data); + when(job.getSharedData()).thenReturn(sharedData); final JobCommand command = jobCommandFactory.toCommand(job); - verify(mockCommand).init(uuid, data); + verify(mockCommand).init(sharedData, data); assertThat(command, equalTo(mockCommand)); } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java new file mode 100644 index 00000000..29be48ed --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java @@ -0,0 +1,303 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.jetbrains.annotations.NotNull; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.mso.RestMsoImplementation; +import org.springframework.http.HttpMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import javax.ws.rs.ProcessingException; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; +import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE; +import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE; +import static org.onap.vid.utils.Logging.getMethodCallerName; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; + +public class ResourceCommandTest { + + public static class MockCommand extends ResourceCommand { + + public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus) { + super(mock(RestMsoImplementation.class, RETURNS_MOCKS), mock(InProgressStatusService.class), mock(MsoResultHandlerService.class, RETURNS_MOCKS), mock(WatchChildrenJobsBL.class)); + + this.mockedJobStatus = mockedJobStatus; + this.mockState = mockState; + this.mockPhase = mockPhase; + if (mockState==InternalState.INITIAL) { + init(mock(JobSharedData.class), Collections.emptyMap()); + } + else { + init(mock(JobSharedData.class), ImmutableMap.of(INTERNAL_STATE, mockState.name(), ACTION_PHASE, mockPhase.name())); + } + when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus); + } + + private final Job.JobStatus mockedJobStatus; + private final InternalState mockState; + private final Action mockPhase; + + + @NotNull + @Override + public Job.JobStatus createChildren() { + if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Action.Delete)) + return mockedJobStatus; + throw (new RuntimeException("Not expected to call "+getMethodCallerName())); + } + + protected Job.JobStatus mockedStatusOrThrow(InternalState expectedState) { + if (mockState == expectedState) + return mockedJobStatus; + throw (new RuntimeException("Not expected to call "+getMethodCallerName())); + } + + protected MsoRestCallPlan mockedPlanOrThrow(InternalState expectedState) { + if (mockState == expectedState) + return new MsoRestCallPlan(HttpMethod.POST, "path", Optional.empty(), Optional.empty(), "nothing"); + throw (new RuntimeException("Not expected to call "+getMethodCallerName())); + } + + @NotNull + @Override + public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) { + return mockedPlanOrThrow(InternalState.CREATE_MYSELF); + } + + @NotNull + @Override + public MsoRestCallPlan planDeleteMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) { + return mockedPlanOrThrow(InternalState.DELETE_MYSELF); + } + } + + public static class MockCommandTestingStateMachine extends MockCommand { + + private final JobSharedData sharedData; + + public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf) { + this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false); + } + + public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService) { + super(mockState, mockPhase, mockedJobStatus); + this.mockedNeedToDeleteMySelf = mockedNeedToDeleteMySelf; + this.isService = isService; + this.sharedData = mock(JobSharedData.class, RETURNS_MOCKS); + } + + protected final boolean mockedNeedToDeleteMySelf; + private final boolean isService; + + @NotNull + @Override + public Job.JobStatus inProgress() { + return mockedStatusOrThrow(InternalState.IN_PROGRESS); + } + + @NotNull + @Override + public Job.JobStatus watchChildren() { + return mockedStatusOrThrow(InternalState.WATCHING); + } + + @Override + public boolean isNeedToDeleteMyself() { + return mockedNeedToDeleteMySelf; + } + + @Override + protected boolean isServiceCommand() { + return isService; + } + + @Override + public JobSharedData getSharedData() { + return sharedData; + } + } + + @DataProvider + public static Object[][] nextStateDeletePhaseProvider() { + return new Object[][]{ + {InternalState.CREATING_CHILDREN, Job.JobStatus.COMPLETED, InternalState.WATCHING}, + {InternalState.WATCHING, Job.JobStatus.COMPLETED, InternalState.DELETE_MYSELF}, + {InternalState.WATCHING, Job.JobStatus.IN_PROGRESS, InternalState.WATCHING}, + {InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS, InternalState.WATCHING}, + {InternalState.DELETE_MYSELF, Job.JobStatus.COMPLETED, InternalState.IN_PROGRESS}, + {InternalState.IN_PROGRESS, Job.JobStatus.COMPLETED, InternalState.TERMINAL}, + {InternalState.IN_PROGRESS, Job.JobStatus.IN_PROGRESS, InternalState.IN_PROGRESS}, + {InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS, InternalState.IN_PROGRESS}, + }; + } + + @Test(dataProvider = "nextStateDeletePhaseProvider") + public void whenCalcNextStateDeletePhase_expectedStateIsReturned( + InternalState internalState, Job.JobStatus jobStatus, InternalState expectedState) { + + //there is no meaning to the constructor inputs here + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.FAILED, true); + assertEquals(expectedState, underTest.calcNextStateDeletePhase(jobStatus, internalState)); + } + + @Test + public void whenNoNeedToDeleteMyself_internalStateMovesFromWatchingToTerminal() { + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false); + assertEquals(InternalState.TERMINAL, underTest.calcNextStateDeletePhase(Job.JobStatus.COMPLETED, InternalState.WATCHING)); + } + + @DataProvider + public static Object[][] testShallStopJobDataProvider() { + return new Object[][]{ + {Job.JobStatus.IN_PROGRESS, Action.None, false, false}, + {Job.JobStatus.COMPLETED_WITH_NO_ACTION, Action.None, false, false}, + {Job.JobStatus.COMPLETED, Action.None, false, false}, + {Job.JobStatus.FAILED, Action.None, false, true}, + {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, false, true}, + {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, true, false}, + {Job.JobStatus.FAILED, Action.None, true, false}, + {Job.JobStatus.FAILED, Action.Delete, true, true}, + {Job.JobStatus.FAILED, Action.Create, true, true}, + }; + } + + + @Test(dataProvider = "testShallStopJobDataProvider") + public void testShallStopJob(Job.JobStatus jobStatus, Action action, boolean isService, boolean expectedResult) { + //in this test, there is no meaning to constructor parameters besides isService + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false, isService); + + BaseResource mockedRequest = mock(BaseResource.class); + when(underTest.getSharedData().getRequest()).thenReturn(mockedRequest); + when(mockedRequest.getAction()).thenReturn(action); + + assertEquals(expectedResult, underTest.shallStopJob(jobStatus)); + } + + @DataProvider + public static Object[][] testCallDataProvider() { + return new Object[][]{ + {"initial state with successful creating children" ,InternalState.INITIAL, Job.JobStatus.COMPLETED, InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"initial state with failed creating children", InternalState.INITIAL, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED}, + {"watching state with children still in progress" ,InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS, InternalState.WATCHING, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"watching state with children that completed with errors" ,InternalState.WATCHING, Job.JobStatus.COMPLETED_WITH_ERRORS, null, Job.JobStatus.COMPLETED_WITH_ERRORS}, + {"watching state with children that completed with no action" ,InternalState.WATCHING, Job.JobStatus.COMPLETED_WITH_NO_ACTION, InternalState.DELETE_MYSELF, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"watching state with children that has completed" ,InternalState.WATCHING, Job.JobStatus.COMPLETED, InternalState.DELETE_MYSELF, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"mso call state that failed" ,InternalState.DELETE_MYSELF, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED}, + //TODO handle AAI get unique name state {"mso call state that still in progress" ,InternalState.DELETE_MYSELF, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED, false}, + {"mso call state that success" ,InternalState.DELETE_MYSELF, Job.JobStatus.COMPLETED, InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"in progress return in progress" ,InternalState.IN_PROGRESS, Job.JobStatus.IN_PROGRESS, InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.PAUSE, InternalState.IN_PROGRESS, Job.JobStatus.RESOURCE_IN_PROGRESS}, + {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.STOPPED, null, Job.JobStatus.STOPPED}, + {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.FAILED, null, Job.JobStatus.FAILED}, + {"in progress return in pause" ,InternalState.IN_PROGRESS, Job.JobStatus.COMPLETED, null, Job.JobStatus.COMPLETED}, + + }; + } + + @Test(dataProvider = "testCallDataProvider") + public void whenCallCommandWithDeletePhase_nextJobStatusAndInternalStateAreAsExpected( + String description, InternalState internalState, Job.JobStatus currentStateResult, + InternalState expectedNextState, Job.JobStatus expectedNextStatus) { + + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Action.Delete, currentStateResult, true); + NextCommand nextCommand = underTest.call(); + assertEquals(expectedNextStatus, nextCommand.getStatus()); + + //expectedNextState == null means nextCommand has no real command + if (expectedNextState!=null) { + assertEquals(expectedNextState, (nextCommand.getCommand().getData().get(INTERNAL_STATE))); + assertFalse(nextCommand.getStatus().isFinal()); + } + else { + assertNull(nextCommand.getCommand()); + assertTrue(nextCommand.getStatus().isFinal()); + } + } + + @Test(expectedExceptions = IllegalStateException.class) + public void whenCommandInUnMappedState_exceptionIsThrown() { + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.COMPLETED, true); + underTest.call(); + } + + @DataProvider + public static Object[][] InProgressDataProvider() { + return Stream.of(Job.JobStatus.values()) + .map(status -> new Object[] { status }) + .toArray(Object[][]::new); + } + + @Test(dataProvider = "InProgressDataProvider") + public void whenGetResultFromMso_InProgressReturnThem(Job.JobStatus mockedJobStatus) { + Job.JobStatus expectedJobStatus = (mockedJobStatus== Job.JobStatus.PAUSE) ? Job.JobStatus.IN_PROGRESS : mockedJobStatus; + MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, mockedJobStatus); + when(underTest.getInProgressStatusService().call(any(), any(), any())).thenReturn(mockedJobStatus); + assertEquals(expectedJobStatus, underTest.inProgress()); + } + + @DataProvider + public static Object[][] InProgressExceptionsDataProvider() { + return new Object[][]{ + {new ProcessingException(""), Job.JobStatus.IN_PROGRESS}, + {new InProgressStatusService.BadResponseFromMso(null), Job.JobStatus.IN_PROGRESS}, + {new GenericUncheckedException(""),Job.JobStatus.STOPPED } + }; + } + + @Test(dataProvider = "InProgressExceptionsDataProvider") + public void whenInProgressStatusServiceThrowException_InProgressReturnStatus(Exception exception, Job.JobStatus expectedJobStatus) { + MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, expectedJobStatus); + when(underTest.getInProgressStatusService().call(any(), any(), any())).thenThrow(exception); + assertEquals(expectedJobStatus, underTest.inProgress()); + } + + @DataProvider + public static Object[][] testIsNeedToDeleteMySelfDataProvider() { + return Stream.of(Action.values()) + .map(status -> new Object[] { status }) + .toArray(Object[][]::new); + } + + @Test(dataProvider = "testIsNeedToDeleteMySelfDataProvider") + public void testIsNeedToDeleteMySelf(Action action) { + boolean expectedResult = (action== Action.Delete); + MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Action.Delete, Job.JobStatus.IN_PROGRESS); + BaseResource mockedBaseResource = mock(BaseResource.class); + when(underTest.getSharedData().getRequest()).thenReturn(mockedBaseResource); + when(mockedBaseResource.getAction()).thenReturn(action); + assertEquals(expectedResult, underTest.isNeedToDeleteMyself()); + } + + @DataProvider + public static Object[][] testWatchingDataProvider() { + return new Object[][]{ + {"all children final, no failed child ", Job.JobStatus.COMPLETED, Job.JobStatus.COMPLETED}, + {"all children final, there is failed child ", Job.JobStatus.COMPLETED_WITH_ERRORS, Job.JobStatus.COMPLETED_WITH_ERRORS}, + {"not all children final", Job.JobStatus.IN_PROGRESS, Job.JobStatus.IN_PROGRESS}, + }; + } + + @Test(dataProvider = "testWatchingDataProvider") + public void testWatching(String desc, Job.JobStatus childrenJobsStatus, Job.JobStatus expectedJobStatus) { + MockCommand underTest = new MockCommand(InternalState.WATCHING, Action.Delete, Job.JobStatus.IN_PROGRESS); + when(underTest.getWatchChildrenJobsBL().retrieveChildrenJobsStatus(any())).thenReturn(childrenJobsStatus); + assertEquals(expectedJobStatus, underTest.watchChildren()); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java new file mode 100644 index 00000000..9ec49a2e --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java @@ -0,0 +1,40 @@ +package org.onap.vid.job.command; + +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + + +public class ResourceInProgressStatusCommandTest { + + @InjectMocks + private ResourceInProgressStatusCommand commandUnderTest = new ResourceInProgressStatusCommand(); + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @DataProvider + public static Object[][] givenStatusToExpectedStatus() { + return new Object[][]{ + {Job.JobStatus.IN_PROGRESS, Job.JobStatus.IN_PROGRESS}, + {Job.JobStatus.FAILED, Job.JobStatus.FAILED}, + {Job.JobStatus.COMPLETED, Job.JobStatus.COMPLETED} + }; + } + + @Test(dataProvider = "givenStatusToExpectedStatus") + public void whenGetStatusFromMso_returnExpectedNextCommand(Job.JobStatus jobStatus, Job.JobStatus expectedNextStatus) { + NextCommand nextCommand = commandUnderTest.processJobStatus(jobStatus); + assertThat(nextCommand.getStatus(), is(expectedNextStatus)); + assertThat(nextCommand.getCommand(), is(commandUnderTest)); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java new file mode 100644 index 00000000..bfda6cf3 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java @@ -0,0 +1,208 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.job.*; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.Network; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.properties.Features; +import org.onap.vid.properties.VidProperties; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.springframework.core.env.Environment; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Map; +import java.util.TreeMap; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.core.Is.is; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; +import static org.onap.vid.job.Job.JobStatus.*; + +public class ServiceInProgressStatusCommandTest { + + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Mock + private JobsBrokerService jobsBrokerService; + + @Mock + private JobAdapter jobAdapter; + + @Mock + private FeatureManager featureManager; + + @Mock + private JobSharedData sharedData; + + @Mock + private Environment environment; + + @Mock + private ServiceInstantiation request; + + @Mock + private InProgressStatusService inProgressStatusService; + + @InjectMocks + private ServiceInProgressStatusCommand command = new ServiceInProgressStatusCommand(); + + @DataProvider + public static Object[][] isNeedToCreateChildJobsDataProvider() { + return new Object[][]{ + {new TreeMap() , true, true, false}, + {null , true, true, false}, + {ImmutableMap.of("a",mock(Vnf.class)), false, true, false}, + {ImmutableMap.of("a",mock(Vnf.class)), true, false, false}, + {ImmutableMap.of("a",mock(Vnf.class)), true, true, true}, + }; + } + + @DataProvider + public static Object[][] processJobStatusData() { + return new Object[][]{ + /* {MSO jobStatus, jobStartTime, isNeedToCreateChildJobs(), property vid.job.max.hoursInProgress, expected nextCommand.getStatus() } */ + {IN_PROGRESS, false, IN_PROGRESS}, + {FAILED, false, FAILED}, + {PAUSE, false, IN_PROGRESS}, + {COMPLETED, false, COMPLETED}, + {COMPLETED, true, IN_PROGRESS}, + {RESOURCE_IN_PROGRESS, false, RESOURCE_IN_PROGRESS}, + {PENDING, false, PENDING}, + {STOPPED, false, STOPPED}, + {COMPLETED_WITH_ERRORS, false, COMPLETED_WITH_ERRORS}, + {CREATING, false, CREATING} + }; + } + + @DataProvider + public static Object[][] isExpiredJobStatusData() { + return new Object[][]{ + {ZonedDateTime.now(), "24", false}, + {getTimeNowMinus(2), "1", true}, + {getTimeNowMinus(24), "24", true}, + {getTimeNowMinus(2), "0", false}, + {getTimeNowMinus(2), "-1", false}, + {getTimeNowMinus(2), "", false}, + {getTimeNowMinus(2), "a", false} + }; + } + + private static ZonedDateTime getTimeNowMinus(int hoursAgo) { + return ZonedDateTime.ofInstant(Instant.now().minus(hoursAgo, ChronoUnit.HOURS), ZoneOffset.UTC); + } + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test(dataProvider = "isNeedToCreateChildJobsDataProvider" ) + public void testIsNeedToCreateChildJobs(Map serviceVnfs, boolean isALaCarte, + boolean isFeatureEnabled, boolean expected) { + MockitoAnnotations.initMocks(this); + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); + when(serviceInstantiation.getVnfs()).thenReturn(serviceVnfs); + when(serviceInstantiation.isALaCarte()).thenReturn(isALaCarte); + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(isFeatureEnabled); + assertThat(command.isNeedToCreateChildJobs(serviceInstantiation), is(expected)); + } + + @Test + public void whenGetFromMsoCompletedAndALaCarte_generateNewJobsForVnfs() { + UUID uuid = UUID.randomUUID(); + String userId = "mockedUserID"; + Vnf vnf1 = mock(Vnf.class); + Vnf vnf2 = mock(Vnf.class); + Network network1 = mock(Network.class); + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); + when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("a", vnf1, "b", vnf2)); + when(serviceInstantiation.getNetworks()).thenReturn(ImmutableMap.of("c", network1)); + when(serviceInstantiation.isALaCarte()).thenReturn(true); + when(serviceInstantiation.getModelInfo()).thenReturn(new ModelInfo()); + + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); + + UUID uuid1 = UUID.fromString("12345678-1234-1234-1234-123456789012"); + UUID uuid2 = UUID.fromString("12345678-1234-1234-1234-123456789013"); + UUID uuid3 = UUID.fromString("12345678-1234-1234-1234-123456789014"); + when(jobsBrokerService.add(any())).thenReturn(uuid1).thenReturn(uuid2).thenReturn(uuid3); + + JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation); + command.init(sharedData, "", ""); + when(inProgressStatusService.call(any(), eq(sharedData), any())).thenReturn(Job.JobStatus.COMPLETED); + NextCommand nextCommand = command.call(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class); + verify(jobAdapter, times(2)).createChildJob(eq(JobType.VnfInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any()); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any()); + assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network1)); + + verify(jobsBrokerService, times(3)).add(any()); + + //verify we don't update service info during this case, which shall stay in_progress + verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any()); + + assertThat(nextCommand.getStatus(), is(Job.JobStatus.IN_PROGRESS)); + assertThat(nextCommand.getCommand().getType(), is(new WatchingCommand().getType())); + assertThat(nextCommand.getCommand().getData().get("childrenJobs"), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString()))); + assertThat(nextCommand.getCommand().getData().get("isService"), is(true)); + } + + @Test(dataProvider = "processJobStatusData") + public void processJobStatusTest(Job.JobStatus jobStatus, boolean isNeedToCreateChildJobs, Job.JobStatus expectedStatus) { + + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); + // All mocks under are used for isNeedToCreateChildJobs=true case + when(sharedData.getRequest()).thenReturn(request); + when(request.isALaCarte()).thenReturn(true); + Map vnfs = mock(Map.class); + ModelInfo modelInfo = mock(ModelInfo.class); + + // if vnfs.isEmpty -> isNeedToCreateChildJobs will return false + when(vnfs.isEmpty()).thenReturn(!isNeedToCreateChildJobs); + + when(request.getVnfs()).thenReturn(vnfs); + when(request.getModelInfo()).thenReturn(modelInfo); + command.instanceId = "MockInstId"; + + NextCommand nextCommand = command.processJobStatus(jobStatus); + Assert.assertEquals(nextCommand.getStatus(), expectedStatus); + if (isNeedToCreateChildJobs) { + Assert.assertEquals(nextCommand.getCommand().getClass(), WatchingCommand.class); + } else { + Assert.assertEquals(nextCommand.getCommand(), command); + } + } + + @Test(dataProvider = "isExpiredJobStatusData") + public void isExpiredJobStatusTest(ZonedDateTime jobStartTime, String configValue, boolean expectedResult) { + SystemProperties systemProperties = new SystemProperties(); + systemProperties.setEnvironment(environment); + when(environment.getRequiredProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)).thenReturn(configValue); + when(environment.containsProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)).thenReturn(true); + Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java deleted file mode 100644 index e7ab4f09..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.command; - - -import io.joshworks.restclient.http.HttpResponse; -import org.mockito.Mock; -import org.onap.vid.aai.AaiResponse; -import org.onap.vid.aai.exceptions.InvalidAAIResponseException; -import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.domain.mso.RequestReferences; -import org.onap.vid.exceptions.MaxRetriesException; -import org.onap.vid.job.Job; -import org.onap.vid.job.NextCommand; -import org.onap.vid.model.RequestReferencesContainer; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.services.AuditService; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.UUID; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -public class ServiceInstantiationCommandTest { - @Mock - private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic; - - @Mock - private MsoInterface msoInterface; - - @Mock - private AuditService auditService; - - @Mock - private ServiceInstantiation serviceInstantiation; - - @Mock - private HttpResponse msoResponse; - - @Mock - private RequestDetailsWrapper requestDetailsWrapper; - - @Mock - private AaiResponse aaiResponse; - - @Mock - private RequestReferencesContainer requestReferencesContainer; - - - private UUID uuid = UUID.randomUUID(); - - - private ServiceInstantiationCommand serviceInstantiationCommand; - - @BeforeMethod - public void setUp() { - initMocks(this); - serviceInstantiationCommand = new ServiceInstantiationCommand(asyncInstantiationBusinessLogic, auditService, msoInterface, uuid, serviceInstantiation, "sampleUserId"); - } - - - @Test - public void shouldProperlyHandleMaxRetriesException() { - when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenThrow(new MaxRetriesException("", 2)); - - NextCommand call = serviceInstantiationCommand.call(); - - assertThat(call.getCommand(), is(nullValue())); - assertThat(call.getStatus(), is(equalTo(Job.JobStatus.FAILED))); - - verify(asyncInstantiationBusinessLogic).handleFailedInstantiation(uuid); - } - - @Test - public void shouldProperlyHandleInvalidAAIResponseException() { - doThrow(new InvalidAAIResponseException(aaiResponse)).when(asyncInstantiationBusinessLogic).generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId"); - - NextCommand call = serviceInstantiationCommand.call(); - - assertThat(call.getCommand(), is(serviceInstantiationCommand)); - assertThat(call.getStatus(), is(equalTo(Job.JobStatus.IN_PROGRESS))); - } - - - @Test - public void shouldProperlyHandleInvalidSOResponse() { - when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenReturn(requestDetailsWrapper); - when(asyncInstantiationBusinessLogic.getServiceInstantiationPath(serviceInstantiation)).thenReturn("samplePath"); - when(msoInterface.post("samplePath", requestDetailsWrapper, RequestReferencesContainer.class)).thenReturn(msoResponse); - when(msoResponse.getStatus()).thenReturn(500); - when(msoResponse.getBody()).thenReturn(requestReferencesContainer); - - NextCommand call = serviceInstantiationCommand.call(); - - assertThat(call.getCommand(), is(nullValue())); - assertThat(call.getStatus(), is(equalTo(Job.JobStatus.FAILED))); - - verify(auditService).setFailedAuditStatusFromMso(uuid, null, 500, requestReferencesContainer.toString()); - } - - - @Test - public void shouldProperlyUpdateServiceStatusAndReturnInProgressCommand() { - RequestReferences requestReferences = createRequestReferences(); - - when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenReturn(requestDetailsWrapper); - when(asyncInstantiationBusinessLogic.getServiceInstantiationPath(serviceInstantiation)).thenReturn("samplePath"); - when(msoInterface.post("samplePath", requestDetailsWrapper, RequestReferencesContainer.class)).thenReturn(msoResponse); - when(msoResponse.getStatus()).thenReturn(200); - when(msoResponse.getBody()).thenReturn(requestReferencesContainer); - when(requestReferencesContainer.getRequestReferences()).thenReturn(requestReferences); - - - NextCommand call = serviceInstantiationCommand.call(); - - assertThat(call.getCommand(), instanceOf(InProgressStatusCommand.class)); - assertThat(call.getStatus(), is(equalTo(Job.JobStatus.IN_PROGRESS))); - - } - - private RequestReferences createRequestReferences() { - RequestReferences requestReferences = new RequestReferences(); - requestReferences.setInstanceId("sampleInstanceId"); - requestReferences.setRequestId("sampleRequestId"); - return requestReferences; - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java new file mode 100644 index 00000000..98524c7d --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java @@ -0,0 +1,98 @@ +package org.onap.vid.job.command; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.impl.JobDaoImpl; +import org.onap.vid.utils.DaoUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; +import static org.testng.AssertJUnit.assertEquals; + +public class WatchChildrenJobsBLTest { + @Mock + private DataAccessService dataAccessService; + + @InjectMocks + private WatchChildrenJobsBL watchChildrenJobsBL; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + public static Object[][] dataProviderForChildrenStatusOnly() { + return new Object[][]{ + {Arrays.asList(JobStatus.STOPPED, JobStatus.COMPLETED_WITH_NO_ACTION, JobStatus.COMPLETED), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(null, JobStatus.COMPLETED), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(null, JobStatus.IN_PROGRESS), JobStatus.IN_PROGRESS}, + {Arrays.asList(null, JobStatus.FAILED), JobStatus.FAILED}, + {new ArrayList<>(), JobStatus.COMPLETED_WITH_NO_ACTION} + }; + } + + @DataProvider + public static Object[][] childrenStatusDataProvider() { + + List result = new ArrayList<>(); + result.addAll(Arrays.asList(dataProviderForChildrenStatusOnly())); + result.addAll(Arrays.asList(inputsStatusAndExpectedOutputDataProvider())); + return result.toArray(new Object[result.size()][]); + } + + @DataProvider + public static Object[][] inputsStatusAndExpectedOutputDataProvider() { + return new Object[][]{ + {Arrays.asList(JobStatus.COMPLETED, JobStatus.COMPLETED), JobStatus.COMPLETED}, + {Arrays.asList(JobStatus.COMPLETED, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED}, + {Arrays.asList(JobStatus.FAILED, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.FAILED}, + {Arrays.asList(JobStatus.FAILED, JobStatus.COMPLETED), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(JobStatus.RESOURCE_IN_PROGRESS, JobStatus.FAILED), JobStatus.IN_PROGRESS}, + {Arrays.asList(JobStatus.PAUSE, JobStatus.FAILED), JobStatus.IN_PROGRESS}, + {Arrays.asList(JobStatus.PENDING, JobStatus.FAILED), JobStatus.IN_PROGRESS}, + {Arrays.asList(JobStatus.IN_PROGRESS, JobStatus.COMPLETED), JobStatus.IN_PROGRESS}, + {Arrays.asList(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS), JobStatus.IN_PROGRESS}, + {Arrays.asList(JobStatus.COMPLETED, JobStatus.COMPLETED_WITH_ERRORS), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(JobStatus.COMPLETED_WITH_ERRORS, JobStatus.FAILED), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(JobStatus.COMPLETED_WITH_ERRORS, JobStatus.COMPLETED_WITH_ERRORS), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(JobStatus.COMPLETED_WITH_ERRORS, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED_WITH_ERRORS}, + {Arrays.asList(JobStatus.COMPLETED_WITH_NO_ACTION, JobStatus.COMPLETED_WITH_NO_ACTION), JobStatus.COMPLETED_WITH_NO_ACTION}, + + + }; + } + + @Test(dataProvider = "childrenStatusDataProvider") + public void whenRetrieveListOfChildrenWithStatues_thenAccumulatedChildrenStatusAsExpected(List childJobs, JobStatus expectedChildrenJobsStatus) { + //init sql result mock + List mockChildren = childJobs.stream().map(st -> { + JobDaoImpl job = new JobDaoImpl(); + job.setUuid(UUID.randomUUID()); + job.setStatus(st); + return job; + }).collect(Collectors.toList()); + when(dataAccessService.getList(eq(JobDaoImpl.class), anyString(), any(), eq(DaoUtils.getPropsMap()))) + .thenReturn(mockChildren); + + List uuids = mockChildren.stream().map(job -> job.getUuid().toString()).collect(Collectors.toList()); + assertEquals(expectedChildrenJobsStatus, watchChildrenJobsBL.retrieveChildrenJobsStatus(uuids)); + } + + @Test(dataProvider = "inputsStatusAndExpectedOutputDataProvider") + public void whenCumulate2JobStatus_thenResultAsExpected(List jobs, JobStatus expectedChildrenJobsStatus) { + assertEquals(expectedChildrenJobsStatus, watchChildrenJobsBL.cumulateJobStatus(jobs.get(0), jobs.get(1))); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java new file mode 100644 index 00000000..f47a18d5 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java @@ -0,0 +1,77 @@ +package org.onap.vid.job.command; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; + +public class WatchingCommandTest { + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Mock + private DataAccessService dataAccessService; + + @Mock + private WatchChildrenJobsBL watchChildrenJobsBL; + + @InjectMocks + private WatchingCommand watchingCommand = new WatchingCommand(); + + + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @DataProvider + public static Object[][] testWatchingDataProvider() { + return new Object[][]{ + {"all children final, no failed child, is service", Job.JobStatus.COMPLETED, true, Job.JobStatus.COMPLETED}, + {"all children final, there is failed child, is service", Job.JobStatus.COMPLETED_WITH_ERRORS, true, Job.JobStatus.COMPLETED_WITH_ERRORS}, + {"not all children final, is service", Job.JobStatus.IN_PROGRESS, true, Job.JobStatus.IN_PROGRESS}, + {"all children final, no failed child, not service", Job.JobStatus.COMPLETED, false, Job.JobStatus.COMPLETED}, + {"all children final, there is failed child, not service", Job.JobStatus.COMPLETED_WITH_ERRORS, false, Job.JobStatus.COMPLETED_WITH_ERRORS}, + {"not all children final, not service", Job.JobStatus.IN_PROGRESS, false, Job.JobStatus.RESOURCE_IN_PROGRESS}, + }; + } + + + + @Test(dataProvider = "testWatchingDataProvider") + public void whenGetChildrenStatus_thenJobStatusAsExpected(String desc, Job.JobStatus childrenComulativeStatus, boolean isService, Job.JobStatus expectedCommandStatus) { + UUID jobUUID = UUID.randomUUID(); + JobSharedData sharedData = new JobSharedData(jobUUID, "mockedUserID", mock(ServiceInstantiation.class)); + List uuids = mock(List.class); + watchingCommand.init(sharedData, uuids, isService); + when(watchChildrenJobsBL.retrieveChildrenJobsStatus(eq(uuids))).thenReturn(childrenComulativeStatus); + when(watchChildrenJobsBL.cumulateJobStatus(eq(childrenComulativeStatus),eq(Job.JobStatus.COMPLETED))).thenReturn(childrenComulativeStatus); + + //execute command and verify + NextCommand nextCommand = watchingCommand.call(); + assertThat(nextCommand.getStatus(), is(expectedCommandStatus)); + if (!expectedCommandStatus.equals(Job.JobStatus.IN_PROGRESS) && isService) { + verify(asyncInstantiationBL).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus); + } else { + verify(asyncInstantiationBL, never()).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus); + } + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java new file mode 100644 index 00000000..f7f83bdf --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java @@ -0,0 +1,925 @@ +package org.onap.vid.job.impl; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.StringUtils; +import org.mockito.Mockito; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.config.DataSourceConfig; +import org.onap.vid.config.JobCommandsConfigWithMockedMso; +import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.job.Job; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.JobType; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.command.CommandUtils; +import org.onap.vid.job.command.InternalState; +import org.onap.vid.model.Action; +import org.onap.vid.model.NameCounter; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.model.RequestReferences; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.properties.Features; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.utils.DaoUtils; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.togglz.core.manager.FeatureManager; + +import javax.inject.Inject; +import javax.ws.rs.ProcessingException; +import java.lang.reflect.Method; +import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.*; +import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.core.Every.everyItem; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.endsWith; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.onap.vid.job.Job.JobStatus.*; +import static org.onap.vid.model.JobAuditStatus.SourceStatus.MSO; +import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID; +import static org.testng.AssertJUnit.*; + +//it's more like integration test than UT +//But it's very hard to test in API test so I use UT +@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class, JobCommandsConfigWithMockedMso.class}) +public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTest { + + private static final String FAILED_STR = "FAILED"; + private static final String COMPLETE_STR = "COMPLETE"; + private static final String IN_PROGRESS_STR = "IN_PROGRESS"; + private static final String REQUESTED = "REQUESTED"; + private static final String PENDING_MANUAL_TASK = "PENDING_MANUAL_TASK"; + public static final String RAW_DATA_FROM_MSO = "RAW DATA FROM MSO"; + private static String USER_ID = "123"; + public static String REQUEST_ID = UUID.randomUUID().toString(); + public static String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + + @Inject + private JobsBrokerService jobsBrokerService; + + @Inject + private JobWorker jobWorker; + + @Inject + private FeatureManager featureManager; + + @Inject + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Inject + private RestMsoImplementation restMso; + + @Inject + private DataAccessService dataAccessService; + + @Inject + private CommandUtils commandUtils; + + @BeforeClass + void initServicesInfoService() { + createInstanceParamsMaps(); + } + + @BeforeMethod + void clearDb() { + dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", DaoUtils.getPropsMap()); + dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", DaoUtils.getPropsMap()); + dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", DaoUtils.getPropsMap()); + } + + @BeforeMethod + void defineMocks() { + mockAaiClientAnyNameFree(); + } + + //@Test + public void whenPushNewBulk_thenAllServicesAreInPending() { + + pushMacroBulk(); + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + assertThat( serviceInfoList, everyItem(hasProperty("jobStatus", is(PENDING)))); + } + + private List pushMacroBulk() { + ServiceInstantiation serviceInstantiation = generateMockMacroServiceInstantiationPayload(false, + createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), + 3, true,PROJECT_NAME, true); + return asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID); + } + + private UUID pushALaCarteWithVnf() { + ServiceInstantiation serviceInstantiation = generateALaCarteWithVnfsServiceInstantiationPayload(); + List uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID); + assertThat(uuids, hasSize(1)); + return uuids.get(0); + } + + private UUID pushALaCarteUpdateWithGroups() { + ServiceInstantiation serviceInstantiation = generateALaCarteUpdateWith1ExistingGroup2NewGroupsPayload(); + List uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID); + assertThat(uuids, hasSize(1)); + return uuids.get(0); + } + + public static RestObject createResponse(int statusCode) { + return createResponse(statusCode, SERVICE_INSTANCE_ID, REQUEST_ID); + } + + public static RestObject createResponse(int statusCode, String instanceId, String requestId) { + RequestReferences requestReferences = new RequestReferences(); + requestReferences.setRequestId(requestId); + requestReferences.setInstanceId(instanceId); + RestObject restObject = new RestObject<>(); + restObject.set(new RequestReferencesContainer(requestReferences)); + restObject.setStatusCode(statusCode); + restObject.setRaw(RAW_DATA_FROM_MSO); + return restObject; + } + + ImmutableList statusesToStrings(JobStatus... jobStatuses) { + return Stream.of(jobStatuses).map( + Enum::toString).collect(ImmutableList.toImmutableList()); + } + + /* + Make sure service state is in progress once request has sent to MSO + Make sure service state is in progress once request has sent to MSO and MSO status is in_progress + Make sure service state is Failed once we got from MSO failure state, and that job's are not collected any more. + Make sure service state is Completed successfully once we got from MSO complete, and that next job is peeked. + Once a service in the bulk is failed, other services moved to Stopped, and no other jobs from the bulk are peeked. + */ + //@Test + public void testStatusesOfMacroServiceInBulkDuringBulkLifeCycle() { + when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); + ImmutableList> expectedStatusesForVid = ImmutableList.of( + statusesToStrings(PENDING, IN_PROGRESS, COMPLETED), + statusesToStrings(PENDING, IN_PROGRESS, FAILED), + statusesToStrings(PENDING, STOPPED) + ); + + ImmutableList> expectedStatusesForMso = ImmutableList.of( + ImmutableList.of(REQUESTED, IN_PROGRESS_STR, "not a state", FAILED_STR ,COMPLETE_STR), + ImmutableList.of(REQUESTED, FAILED_STR), + ImmutableList.of() + ); + + List uuids = pushMacroBulk(); + pullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); + + //assert that when get ProcessingException from restMso, status remain the same + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenThrow(new ProcessingException("fake message")); + Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + UUID firstHandledJobUUID = job.getUuid(); + listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + + //assert that when get IN_PROGRESS status from restMso, status remain IN_PROGRESS + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + + //assert that when get unrecognized status from restMso, status remain IN_PROGRESS + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject("not a state")); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + + //assert that when get non 200 status code during IN_PROGRESS, status remain IN_PROGRESS + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR, 404)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + + //when get job COMPLETE from MSO, service status become COMPLETED + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); + List serviceInfoList = listServicesAndAssertStatus(COMPLETED, PENDING, job); + + + //for use later in the test + Map expectedJobStatusMap = serviceInfoList.stream().collect( + Collectors.toMap(ServiceInfo::getJobId, x-> PENDING)); + expectedJobStatusMap.put(job.getUuid(), COMPLETED); + + //when handling another PENDING job, statuses are : COMPLETED, IN_PROGRESS, PENDING + job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS); + assertThat(job.getUuid(), not(equalTo(firstHandledJobUUID))); //assert different job was handled now + expectedJobStatusMap.put(job.getUuid(), JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(expectedJobStatusMap); + + //when get FAILED status from MSO statuses are : COMPLETED, FAILED, STOPPED + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED); + expectedJobStatusMap.put(job.getUuid(), JobStatus.FAILED); + expectedJobStatusMap = expectedJobStatusMap.entrySet().stream().collect(Collectors.toMap( + e -> e.getKey(), e -> e.getValue() == PENDING ? JobStatus.STOPPED : e.getValue() + )); + + listServicesAndAssertStatus(expectedJobStatusMap); + IntStream.range(0, uuids.size()).forEach(i -> { + UUID uuid = uuids.get(i); + List msoStatuses = asyncInstantiationBL.getAuditStatuses(uuid, MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); + List vidStatuses = asyncInstantiationBL.getAuditStatuses(uuid, VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); + assertThat(msoStatuses, is(expectedStatusesForMso.get(i))); + assertThat(vidStatuses, is(expectedStatusesForVid.get(i))); + }); + // + assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); + assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent()); + } + + + @DataProvider + public static Object[][] AlaCarteStatuses(Method test) { + return new Object[][]{ + {COMPLETE_STR, JobStatus.COMPLETED, JobStatus.COMPLETED}, + {FAILED_STR, JobStatus.COMPLETED_WITH_ERRORS, JobStatus.FAILED}, + }; + } + + /* + Make sure service state is in progress once request has sent to MSO + Make sure service state is watching until state changes to complemented + Make sure service state is watching until vnf state changes to completed + Make sure service state is Completed successfully once we got from MSO complete for the vnf job. + status Creating + */ + //@Test(dataProvider = "AlaCarteStatuses") + public void testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules(String msoVnfStatus, JobStatus expectedServiceStatus, JobStatus expectedVnfStatus) { + /* + [v] + push alacarte with 1 vnf + [v] verify STATUS pending + [v] + pull+execute (should post to MSO) + [v] verify STATUS in progress + [v] + pull+execute (should GET completed from MSO) + [v] verify STATUS in progress; TYPE watching + [v] verify job#2 *new* VNF job STATUS creating + [v] + pull+execute job#2 (should post to MSO) + [v] verify job#2 STATUS resource in progress + [v] verify job#1 STATUS in progress + [v] + pull+execute job#2 (should GET completed from MSO) + [v] verify job#2 STATUS completed + [v] + pull+execute job#1 + [v] verify job#1 STATUS completed + + * not looking on audit (yet) + */ + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false); + final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + final String VNF_REQUEST_ID = UUID.randomUUID().toString(); + + + //push alacarte with 1 vnf, verify STATUS pending + UUID uuid = pushALaCarteWithVnf(); + singleServicesAndAssertStatus(JobStatus.PENDING, uuid); + + //mock mso to answer 200 of create service instance request, verify STATUS in progress + when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + //mock mso to answer COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching + reset(restMso); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress + reset(restMso); + when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VNF_REQUEST_ID)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus); + + //verify service job STATUS in progress + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status, + //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS) + reset(restMso); + when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(msoVnfStatus)); + pullJobProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, expectedVnfStatus, false); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, expectedServiceStatus, true); + singleServicesAndAssertStatus(expectedServiceStatus, uuid); + + } + + /* + this test is almost duplication of testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules. + + IgnoringVfModules test check the scenario while FLAG_ASYNC_ALACARTE_VFMODULE is off + WithVfModules test check the scenario while FLAG_ASYNC_ALACARTE_VFMODULE is on + + We shall consider later to remove testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules + And union these tests to single one. + */ + + //@Test + public void testALaCarteLifeCycle1Vnf2VfModules() { + + + String msoVnfStatus = COMPLETE_STR; + JobStatus expectedServiceStatus = IN_PROGRESS; + JobStatus expectedVnfStatus = RESOURCE_IN_PROGRESS; + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true); + final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + final String VNF_REQUEST_ID = UUID.randomUUID().toString(); + final String VNF_INSTANCE_ID = UUID.randomUUID().toString(); + final String VG_REQUEST_ID = UUID.randomUUID().toString(); + final String VG_INSTANCE_ID = UUID.randomUUID().toString(); + final String VF_MODULE_REQUEST_ID = UUID.randomUUID().toString(); + final String VF_MODULE_REQUEST_ID2 = UUID.randomUUID().toString(); + + + //push alacarte with 1 vnf, verify STATUS pending + UUID uuid = pushALaCarteWithVnf(); + singleServicesAndAssertStatus(JobStatus.PENDING, uuid); + + /*---------- service -----------*/ + + //mock mso to answer 200 of create service instance request, verify STATUS in progress + when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + //mock mso to answer COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching + reset(restMso); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + /*---------- vnf -----------*/ + + //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress + reset(restMso); + when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus); + + //verify service job STATUS in progress + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status, + //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS) + reset(restMso); + when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + try { + reset(commandUtils); + when(commandUtils.isVfModuleBaseModule(SERVICE_MODEL_VERSION_ID, VF_MODULE_0_MODEL_VERSION_ID)).thenReturn(true); + when(commandUtils.isVfModuleBaseModule(SERVICE_MODEL_VERSION_ID, VF_MODULE_1_MODEL_VERSION_ID)).thenReturn(false); + } catch (AsdcCatalogException e) { + + } + + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.RESOURCE_IN_PROGRESS, JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + + /*---------- vf Module without volume group name (base) -----------*/ + + //vg name not exist, so vf module created immediately + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + + //verify vnf/volumeGroup job STATUS still watching with resource in progress + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + + //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress + reset(restMso); + when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + + //mock mso to answer for vf module orchestration request + reset(restMso); + when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus); + + //verify volume group become completed + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.COMPLETED, JobType.Watching); + + //vnf become watching after volume group completed, and new volume group created + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + + /*---------- volume group & vf module (non base) -----------*/ + + /*---------- volume group -----------*/ + + //mock mso to answer 200 of create volumeGroup instance request, pull+execute volumeGroup job, STATUS resource in progress + reset(restMso); + when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, VG_INSTANCE_ID, VG_REQUEST_ID)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus); + + //verify vnf job STATUS still watching with resource in progress + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + + //mock mso to answer for volume group orchestration request + reset(restMso); + when(restMso.GetForObject(endsWith(VG_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(msoVnfStatus)); + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + + /*---------- vfModule -----------*/ + + //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress + reset(restMso); + when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID2)); + pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + + //mock mso to answer for vf module orchestration request + reset(restMso); + when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID2), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus); + + //execute twice - 1 for parent volume group, 1 for parent vnf + pullAllJobProcessAndPushBackByType(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching , JobStatus.COMPLETED); + + singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.COMPLETED, true); + singleServicesAndAssertStatus(JobStatus.COMPLETED, uuid); + } + + //@Test + public void testBadAaiResponseForSearchNamesAndBackToNormal() { + when(aaiClient.isNodeTypeExistsByName(any(), any())).thenThrow(aaiNodeQueryBadResponseException()); + pushMacroBulk(); //JOB shall become IN_PROGRESS but service info is still pending + Job job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, true); + listServicesAndAssertStatus(PENDING, PENDING, job); + + //JOB shall remain in IN_PROGRESS + job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); + //make sure the job command is still ServiceInstantiation + assertThat(job.getType(), is(JobType.MacroServiceInstantiation)); + listServicesAndAssertStatus(PENDING, PENDING, job); + + //simulate AAI back to normal, AAI return name is free, and MSO return good response + Mockito.reset(aaiClient); // must forget the "thenThrow" + when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(false); + when(restMso.PostForObject(any(),any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); + job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); + listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + + //when get job COMPLETE from MSO, service status become COMPLETED + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); + listServicesAndAssertStatus(COMPLETED, PENDING, job); + } + + //@Test + public void testAaiResponseNameUsedTillMaxRetries() { + when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(true); + asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10); + pushMacroBulk(); + //JOB shall become IN_PROGRESS but service info is still pending + Job job = pullJobProcessAndPushBack(PENDING, JobStatus.FAILED, true); + listServicesAndAssertStatus(JobStatus.FAILED, JobStatus.STOPPED, job); + } + + private Job pullJobProcessAndPushBack(JobStatus topic, JobStatus expectedNextJobStatus) { + return pullJobProcessAndPushBack(topic, expectedNextJobStatus, true); + } + + //return the pulled job (and not the pushed job) + private Job pullJobProcessAndPushBack(JobStatus topic, JobStatus expectedNextJobStatus, boolean pullingAssertion) { + Optional job = pullJob(topic, pullingAssertion); + + Job nextJob = jobWorker.executeJobAndGetNext(job.get()); + + try { + assertThat("next job not ok: " + nextJob.getData(), nextJob.getStatus(), is(expectedNextJobStatus)); + + if (pullingAssertion) { + //assert another pulling on same topic return no result (before push back) + assertFalse(jobsBrokerService.pull(topic, randomUuid()).isPresent()); + } + + } finally { + jobsBrokerService.pushBack(nextJob); // push back to let retries - even if any assertion failure + } + assertThat(jobsBrokerService.peek(job.get().getUuid()).getStatus(), is(expectedNextJobStatus)); + return job.get(); + } + + private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, + JobType expectedNextJobType) { + Job job = pullJobProcessAndPushBack(topic, expectedNextJobStatus, false); + assertThat("job not ok: " + job.getData(), job.getType(), is(expectedNextJobType)); + return job; + } + + private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, + JobType expectedNextJobType, int retries) { + return retryWithAssertionsLimit(retries, () -> { + return pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType); + }); + } + + private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, + JobType expectedNextJobType, Action actionPhase, InternalState internalState, int retries) { + return retryWithAssertionsLimit(retries, () -> { + Job job = pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType); + assertThat("job not ok: " + job.getData(), job.getData(), is(jsonPartEquals("actionPhase", actionPhase.name()))); + if (internalState != null) { + assertThat("job not ok: " + job.getData(), job.getData(), is(jsonPartEquals("internalState", internalState.name()))); + } + return job; + }); + } + + private Job retryWithAssertionsLimit(int retries, Supplier supplier) { + java.util.Stack history = new Stack<>(); + + do { + try { + return supplier.get(); + } catch (AssertionError assertionError) { + history.push(assertionError); + } + } while (history.size() < retries); + + // No success: + throw new AssertionError("No luck while all of these assertion errors: " + history.stream() + .map(Throwable::getMessage) + .map(s -> s.replace('\n', ' ')) + .map(s -> s.replaceAll("\\s{2,}"," ")) + .distinct() + .collect(joining("\n ", "\n ", "")), history.peek()); + } + + private Job pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus topic, JobType expectedCurrentJobType, JobStatus expectedNextJobStatus, + JobType expectedNextJobType) { + List pulledJobs = new ArrayList<>(); + Job lastJob = null; + while (lastJob == null || lastJob.getType() != expectedCurrentJobType) { + lastJob = pullJob(topic, false).get(); + if (lastJob.getType() != expectedCurrentJobType) { + pulledJobs.add(lastJob); + } + } + + Job nextJob = jobWorker.executeJobAndGetNext(lastJob); + assertThat(nextJob.getStatus(), is(expectedNextJobStatus)); + assertThat(nextJob.getType(), is(expectedNextJobType)); + + jobsBrokerService.pushBack(nextJob); + assertThat(jobsBrokerService.peek(nextJob.getUuid()).getStatus(), is(expectedNextJobStatus)); + + pulledJobs.forEach(job -> + jobsBrokerService.pushBack(job) + ); + + return nextJob; + } + + private void pullAllJobProcessAndPushBackByType(JobStatus topic, JobType commandType, JobStatus expectedFinalStatus) { + Map jobStatusMap = new HashMap<>(); + Optional job = pullJob(topic, false); + for (int i=0; i<1000 && job.isPresent() && job.get().getType() == commandType; i++) { + Job nextJob = jobWorker.executeJobAndGetNext(job.get()); + jobStatusMap.put(nextJob.getUuid(), nextJob.getStatus()); + jobsBrokerService.pushBack(nextJob); + job = jobsBrokerService.pull(topic, UUID.randomUUID().toString()); + } + assertThat(jobStatusMap.values(), everyItem(is(expectedFinalStatus))); + + } + + private Optional pullJob(JobStatus topic, boolean pullingAssertion) { + if (pullingAssertion) { + //assert pulling on inverse topic return no result + assertFalse(jobsBrokerService.pull(inverseTopic(topic), randomUuid()).isPresent()); + } + + Optional job = jobsBrokerService.pull(topic, randomUuid()); + assertTrue("no job fetched", job.isPresent()); + + if (pullingAssertion) { + //assert another pulling on same topic return no result + assertFalse(jobsBrokerService.pull(topic, randomUuid()).isPresent()); + } + + return job; + } + + private JobStatus inverseTopic(JobStatus topic) { + return topic==JobStatus.IN_PROGRESS ? PENDING : JobStatus.IN_PROGRESS; + } + + + //@Test + public void whenPushNewBulk_andGetNoResponseFromMsoOnCreation_thenServiceMoveToFailedAndOtherToStopped() { + when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(500)); + pushBulkPullPendingJobAndAssertJobStatus(JobStatus.FAILED, JobStatus.STOPPED); + } + + //@Test + public void whenMsoStatusIsPendingManualTask_ThenJobStatusIsPaused() { + when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); + + Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); + + //assert that when get ProcessingException from restMso, status remain the same + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(PENDING_MANUAL_TASK)); + Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(PAUSE, PENDING, job); + + //The paused job is pulled and remain in pause state. Other jobs from bulk remain pending + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(PAUSE, PENDING, job); + + //the job get IN_PROGRESS response (simulate activate operation) and status changed to IN_PROGRESS + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); + listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); + listServicesAndAssertStatus(COMPLETED, PENDING, job); + + //Pulling PENDING job return another job + assertThat(jobsBrokerService.pull(PENDING, randomUuid()).get().getUuid(), not(equalTo(job.getUuid()))); + + + ImmutableList expectedStatusesForMso = ImmutableList.of(REQUESTED, PENDING_MANUAL_TASK, IN_PROGRESS_STR, COMPLETE_STR); + List msoStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); + assertThat(msoStatuses, is(expectedStatusesForMso)); + + ImmutableList expectedStatusesForVid = statusesToStrings(PENDING, IN_PROGRESS, PAUSE, IN_PROGRESS, COMPLETED); + List vidStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); + assertThat(vidStatuses, is(expectedStatusesForVid)); + } + + private Job pushBulkPullPendingJobAndAssertJobStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus) { + pushMacroBulk(); + return pullPendingJobAndAssertJobStatus(pulledJobStatus, otherJobsStatus); + } + + private Job pullPendingJobAndAssertJobStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus) { + Job job = pullJobProcessAndPushBack(PENDING, pulledJobStatus, false); + listServicesAndAssertStatus(pulledJobStatus, otherJobsStatus, job); + return job; + } + + //@Test + public void test2BulksLifeCyclesAreIndependent() { + pushMacroBulk(); + when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); + //push 2nd job, then when pulling first job the job become in_progress, other jobs (from 2 bulks) remain pending + Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); + + //assert we can pull another job from pending from other template id + Job secondJob = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); + assertThat(firstJob.getTemplateId(), not(equalTo(secondJob.getTemplateId()))); + + //assert no more PENDING jobs to pull + assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); + + //when get FAILED status from MSO statuses for failed bulk are: FAILED, STOPPED, for other bulk: IN_PROGRESS, 2 pending + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); + Job failedJob = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED, false); + Map> servicesByTemplateId = + asyncInstantiationBL.getAllServicesInfo() + .stream().collect(groupingBy(ServiceInfo::getTemplateId)); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); + Job successJob = failedJob.getUuid().equals(firstJob.getUuid()) ? secondJob : firstJob; + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), JobStatus.IN_PROGRESS, PENDING, successJob); + + //yet no more PENDING jobs to pull + assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); + + //assert that job from non failed bulk can progress. + //When completed, failed bulk statuses: FAILED, STOPPED. Succeeded bulk statuses are : COMPLETED, 2 pending + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); + servicesByTemplateId = + asyncInstantiationBL.getAllServicesInfo() + .stream().collect(groupingBy(ServiceInfo::getTemplateId)); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, PENDING, successJob); + + //advance other jobs of succeeded bulk till al of them reach to COMPLETED + pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); + pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); + servicesByTemplateId = + asyncInstantiationBL.getAllServicesInfo() + .stream().collect(groupingBy(ServiceInfo::getTemplateId)); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, COMPLETED, successJob); + + //assert no more PENDING jobs nor IN_PROGRESS jobs to pull + assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); + assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent()); + } + + public void deploy2NewGroupsToServiceWith1ExistingGroup() { + + /* + new feature: skip service (existing impl) and skip group (new impl) + service+group aren't touched, 2 groups ARE created + + [v] success if all GROUPs success + + Next test variation should: + [ ] error if all GROUPs error + [ ] completed with error if 1 GROUP error + + + [v] + service with 3 groups - 1 action=none, 2 action=create; service's action=none + [v] verify STATUS pending + [v] + pull+execute (should NOT post to MSO) + [v] verify STATUS in progress; TYPE watching + ... + [v] verify job#2 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete + [v] verify job#3 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete + [v] verify job#4 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete + + [v] + pull+execute job#1 (should NOT post to MSO) + [v] verify STATUS in progress; TYPE watching + [v] verify job#5 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create + [v] verify job#6 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create + [v] verify job#7 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create + + [v] + pull+execute job#5 (should NOT post to MSO) + [v] verify job#5 STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE create + [v] + pull+execute job#1 + [v] verify job#1 STATUS in progress; TYPE watching + + [v] + pull+execute job#6 (should post to MSO) + [v] verify job#6 STATUS resource in progress + [v] + pull+execute job#1 + [v] verify job#1 STATUS in progress; TYPE watching + [v] + pull+execute job#6 (should get from MSO) + [v] verify job#6 STATUS completed + [v] + pull+execute job#1 + [v] verify job#1 STATUS in progress; TYPE watching + + [v] + pull+execute job#7 (should post to MSO) + [v] verify job#7 STATUS resource in progress + [v] + pull+execute job#1 + [v] verify job#1 STATUS in progress; TYPE watching + [v] + pull+execute job#7 (should get from MSO) + [v] verify job#7 STATUS completed + [v] + pull+execute job#1 + [v] verify job#1 STATUS completed + + */ + + final String GROUP1_REQUEST_ID = UUID.randomUUID().toString(); + final String GROUP1_INSTANCE_ID = UUID.randomUUID().toString(); + final String GROUP2_REQUEST_ID = UUID.randomUUID().toString(); + final String GROUP2_INSTANCE_ID = UUID.randomUUID().toString(); + + // Utility method + final BiConsumer verify_Job1InProgress = (phase, nextJobStatus) -> { + pullJobProcessAndPushBackWithTypeAssertion(IN_PROGRESS, nextJobStatus, JobType.ALaCarteService, phase, InternalState.WATCHING, 2); + }; + + //service with 3 groups - 1 action=none, 2 action=create; service's action=none + UUID uuid = pushALaCarteUpdateWithGroups(); + singleServicesAndAssertStatus(PENDING, uuid); + + // take from pending, put in-progress -> 3 delete-child were born + pullJobProcessAndPushBackWithTypeAssertion(PENDING, IN_PROGRESS, JobType.ALaCarteService, Action.Delete, InternalState.WATCHING, 1); + verifyQueueSizes(ImmutableMap.of( + IN_PROGRESS, 1, CREATING, 3 + )); + + Stream.of(1, 2, 3).forEach(i -> { + // take each child creating, put in-progress + verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS); + pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.InstanceGroup, Action.Delete, null, 1); + + // execute each in-progress -> job is completed + verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS); + pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED/*_WITH_NO_ACTION*/, JobType.InstanceGroup,1); + }); + verifyQueueSizes(ImmutableMap.of( + IN_PROGRESS, 1, COMPLETED, 3 + )); + + // take job #1 from phase delete to phase create -> 3 create-child were born + verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); + verifyQueueSizes(ImmutableMap.of( + IN_PROGRESS, 1, CREATING, 3, COMPLETED, 3 + )); + + // prepare MSO mock + when(restMso.PostForObject(any(), endsWith("instanceGroups"), eq(RequestReferencesContainer.class))) + .thenReturn(createResponse(200, GROUP1_INSTANCE_ID, GROUP1_REQUEST_ID)) + .thenReturn(createResponse(200, GROUP2_INSTANCE_ID, GROUP2_REQUEST_ID)) + .thenReturn(null); + when(restMso.GetForObject(argThat(uri -> StringUtils.endsWithAny(uri, GROUP1_REQUEST_ID, GROUP2_REQUEST_ID)), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + // take first "none" child from creating to completed + // note there's no concrete mechanism that makes the first child be + // the "action=None" case, but that's what happens, and following line + // relies on that fact. + pullJobProcessAndPushBackWithTypeAssertion(CREATING, COMPLETED_WITH_NO_ACTION, JobType.InstanceGroupInstantiation, 1); + + // take each of next two children from creating to in-progress, then to completed + // verify job #1 is watching, and MSO is getting requests + Stream.of(1, 2).forEach(i -> { + verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); + pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + verify(restMso, times(i)).PostForObject(any(), any(), any()); + + verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); + pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED, JobType.ResourceInProgressStatus); + verify(restMso, times(i)).GetForObject(any(), any()); + }); + + // job #1 is done as all children are done + verify_Job1InProgress.accept(Action.Create, COMPLETED); + verifyQueueSizes(ImmutableMap.of(COMPLETED, 7)); + } + + private void verifyQueueSizes(ImmutableMap expected) { + final Collection peek = jobsBrokerService.peek(); + final Map jobTypes = peek.stream().collect(groupingBy(Job::getStatus, counting())); + assertThat(jobTypes, is(expected)); + } + + private List listServicesAndAssertStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) { + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + assertServicesStatus(serviceInfoList, pulledJobStatus, otherJobsStatus, job); + + return serviceInfoList; + } + + private ServiceInfo singleServicesAndAssertStatus(JobStatus expectedStatus, UUID jobUUID) { + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + assertEquals(1, serviceInfoList.size()); + ServiceInfo serviceInfo = serviceInfoList.get(0); + assertThat(serviceInfo.getJobStatus(), is(expectedStatus)); + assertThat(serviceInfo.getJobId(), is(jobUUID)); + return serviceInfo; + } + + private void assertServicesStatus(List serviceInfoList, JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) { + serviceInfoList.forEach(si->{ + if (si.getJobId().equals(job.getUuid())) { + assertThat(si.getJobStatus(), is(pulledJobStatus)); + } + else { + assertThat(si.getJobStatus(), is(otherJobsStatus)); + } + }); + } + + private void listServicesAndAssertStatus(Map expectedJobStatusMap) { + Map actualStatuses = asyncInstantiationBL.getAllServicesInfo() + .stream().collect(Collectors.toMap(ServiceInfo::getJobId, ServiceInfo::getJobStatus)); + assertThat(actualStatuses.entrySet(), equalTo(expectedJobStatusMap.entrySet())); + } + + private String randomUuid() { + return UUID.randomUUID().toString(); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java deleted file mode 100644 index dc2eafc9..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.impl; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import org.mockito.Mock; -import org.onap.vid.job.Job; -import org.onap.vid.job.JobAdapter; -import org.onap.vid.job.JobType; -import org.onap.vid.model.JobBulk; -import org.onap.vid.model.JobModel; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.List; -import java.util.UUID; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -public class JobAdapterImplTest { - - - private static final int SAMPLE_INDEX = 10; - private static final String SAMPLE_USER_ID = "sampleUserId"; - - @Mock - private Job job; - - @Mock - private JobAdapter.AsyncJobRequest asyncJobRequest; - - private UUID sampleUuid=UUID.randomUUID(); - - private JobAdapterImpl jobAdapter = new JobAdapterImpl(); - - @BeforeMethod - public void setUp() { - initMocks(this); - - when(job.getUuid()).thenReturn(sampleUuid); - when(job.getStatus()).thenReturn(Job.JobStatus.IN_PROGRESS); - when(job.getTemplateId()).thenReturn(sampleUuid); - } - - @Test - public void shouldConvertJobToJobModel() { - - - JobModel convertedJob = jobAdapter.toModel(job); - - assertThat(convertedJob.getUuid()).isEqualByComparingTo(sampleUuid); - assertThat(convertedJob.getStatus()).isEqualByComparingTo(Job.JobStatus.IN_PROGRESS); - assertThat(convertedJob.getTemplateId()).isEqualByComparingTo(sampleUuid); - } - - - @Test - public void shouldProperlyCreateJob() { - UUID uuid = UUID.randomUUID(); - - Job createdJob = jobAdapter.createJob(JobType.ServiceInstantiation, asyncJobRequest, uuid, SAMPLE_USER_ID, SAMPLE_INDEX); - - assertThat(createdJob.getStatus()).isEqualByComparingTo(Job.JobStatus.PENDING); - assertThat(createdJob.getTemplateId()).isEqualByComparingTo(uuid); - assertThat(createdJob.getType()).isEqualByComparingTo(JobType.ServiceInstantiation); - assertThat(createdJob.getData()).isEqualTo(ImmutableMap.of("request", asyncJobRequest, "userId", SAMPLE_USER_ID)); - } - - @Test - public void shouldProperlyCreateBulkOfJobs(){ - List bulkOfJobs = jobAdapter.createBulkOfJobs(ImmutableMap.of("count", 5, "type", JobType.InProgressStatus.name())); - - - assertThat(bulkOfJobs).hasSize(5); - - Stream jobStream = bulkOfJobs.stream().filter(x -> JobType.InProgressStatus.equals(x.getType()) && Job.JobStatus.PENDING.equals(x.getStatus())); - - assertThat(jobStream).hasSize(5); - } - - - @Test - public void shouldConvertListToBulkJob(){ - JobBulk jobBulk = jobAdapter.toModelBulk(ImmutableList.of(job, job)); - - assertThat(jobBulk.getJobs()).hasSize(2); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java new file mode 100644 index 00000000..95228476 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java @@ -0,0 +1,100 @@ +package org.onap.vid.job.impl; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.RandomUtils; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.job.command.JobCommandFactoryTest; +import org.testng.annotations.Test; + +import java.util.UUID; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotEquals; +import static org.testng.AssertJUnit.assertNotNull; + +public class JobAdapterTest { + + @Test + public void testCreateServiceInstantiationJob() { + JobAdapter jobAdapter = new JobAdapterImpl(); + + JobType jobType = JobType.NoOp; + JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing"); + UUID templateId = UUID.randomUUID(); + String userId = "ou012t"; + String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName"; + int indexInBulk = RandomUtils.nextInt(); + Job job = jobAdapter.createServiceInstantiationJob( + jobType, + request, + templateId, + userId, + optimisticUniqueServiceInstanceName, + indexInBulk + ); + + assertEquals(job.getType(), jobType); + assertEquals(job.getSharedData().getRequest(), request); + assertEquals(job.getSharedData().getRequestType(), request.getClass()); + assertEquals(job.getSharedData().getUserId(), userId); + assertEquals(job.getSharedData().getJobUuid(), job.getUuid()); + assertEquals(job.getSharedData().getRootJobId(), job.getUuid()); + assertNotNull(job.getUuid()); + assertEquals(job.getTemplateId(), templateId); + assertEquals(job.getData().get("optimisticUniqueServiceInstanceName"), optimisticUniqueServiceInstanceName); + assertEquals((int)job.getIndexInBulk(), indexInBulk ); + assertEquals(job.getStatus(), Job.JobStatus.PENDING); + } + + @Test + public void testCreateChildJob() { + + JobAdapter jobAdapter = new JobAdapterImpl(); + + UUID templateId = UUID.randomUUID(); + String userId = "ou012t"; + String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName"; + int indexInBulk = RandomUtils.nextInt(); + Job grandJob = jobAdapter.createServiceInstantiationJob( + JobType.HttpCall, + new JobCommandFactoryTest.MockedRequest(99, "anything"), + templateId, + userId, + optimisticUniqueServiceInstanceName, + indexInBulk + ); + + Job.JobStatus jobStatus = Job.JobStatus.PAUSE; + JobType jobType = JobType.NoOp; + JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing"); + Job parentJob = jobAdapter.createChildJob(jobType, jobStatus, request, grandJob.getSharedData(), ImmutableMap.of()); + + assertEquals(parentJob.getType(), jobType); + assertEquals(parentJob.getSharedData().getRequest(), request); + assertEquals(parentJob.getSharedData().getRequestType(), request.getClass()); + assertEquals(parentJob.getSharedData().getUserId(), userId); + assertEquals(parentJob.getSharedData().getJobUuid(), parentJob.getUuid()); + assertNotNull(parentJob.getUuid()); + assertNotEquals(parentJob.getUuid(), grandJob.getUuid()); + assertEquals(parentJob.getStatus(), jobStatus); + assertEquals(parentJob.getSharedData().getRootJobId(), grandJob.getUuid()); + + Job.JobStatus jobStatus2 = Job.JobStatus.IN_PROGRESS; + JobType jobType2 = JobType.AggregateState; + JobAdapter.AsyncJobRequest request2 = new JobCommandFactoryTest.MockedRequest(66,"abc"); + Job job = jobAdapter.createChildJob(jobType2, jobStatus2, request2, parentJob.getSharedData(), ImmutableMap.of()); + + assertEquals(job.getType(), jobType2); + assertEquals(job.getSharedData().getRequest(), request2); + assertEquals(job.getSharedData().getRequestType(), request2.getClass()); + assertEquals(job.getSharedData().getUserId(), userId); + assertEquals(job.getSharedData().getJobUuid(), job.getUuid()); + assertNotNull(job.getUuid()); + assertNotEquals(job.getUuid(), parentJob.getUuid()); + assertEquals(job.getStatus(), jobStatus2); + assertEquals(job.getSharedData().getRootJobId(), grandJob.getUuid()); + + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java deleted file mode 100644 index 93afd170..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.impl; - - -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.onap.vid.job.JobsBrokerService; -import org.onap.vid.job.command.JobCommandFactory; -import org.onap.vid.properties.Features; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.Trigger; -import org.springframework.scheduling.quartz.SchedulerFactoryBean; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.togglz.core.manager.FeatureManager; - -import java.util.List; -import java.util.stream.Collectors; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -public class JobSchedulerInitializerTest { - - @Mock - private JobsBrokerService brokerService; - - @Mock - private SchedulerFactoryBean schedulerFactoryBean; - - @Mock - private FeatureManager featureManager; - - @Mock - private JobCommandFactory commandFactory; - - @Mock - private Scheduler scheduler; - - @InjectMocks - private JobSchedulerInitializer jobSchedulerInitializer; - - @BeforeMethod - public void setUp() { - initMocks(this); - } - - - @Test - public void shouldNotInitializeSchedulerWhenAsyncJobsAreDisabled() { - when(featureManager.isActive(Features.FLAG_ASYNC_JOBS)).thenReturn(false); - - jobSchedulerInitializer.init(); - - verifyZeroInteractions(schedulerFactoryBean); - } - - - @Test - public void shouldInitializeSchedulerWhenAsyncJobsAreEnabled() throws SchedulerException { - ArgumentCaptor jobDetailArgumentCaptor = ArgumentCaptor.forClass(JobDetail.class); - ArgumentCaptor triggerArgumentCaptor = ArgumentCaptor.forClass(Trigger.class); - when(featureManager.isActive(Features.FLAG_ASYNC_JOBS)).thenReturn(true); - when(schedulerFactoryBean.getScheduler()).thenReturn(scheduler); - - jobSchedulerInitializer.init(); - - verify(scheduler, times(2)).scheduleJob(jobDetailArgumentCaptor.capture(), triggerArgumentCaptor.capture()); - - List topics = extractTopics(jobDetailArgumentCaptor); - - List descriptions = extractDescription(triggerArgumentCaptor); - - assertThat(topics, containsInAnyOrder(org.onap.vid.job.Job.JobStatus.IN_PROGRESS, org.onap.vid.job.Job.JobStatus.PENDING)); - assertThat(descriptions, containsInAnyOrder("Trigger to run async worker for PENDING", "Trigger to run async worker for IN_PROGRESS")); - } - - private List extractTopics(ArgumentCaptor jobDetailArgumentCaptor) { - return jobDetailArgumentCaptor - .getAllValues() - .stream() - .map(JobDetail::getJobDataMap) - .map(x -> x.get("topic")) - .collect(Collectors.toList()); - } - - private List extractDescription(ArgumentCaptor triggerArgumentCaptor) { - return triggerArgumentCaptor - .getAllValues() - .stream() - .map(Trigger::getDescription) - .collect(Collectors.toList()); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java index e58b6ba0..3ff324d6 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java @@ -19,7 +19,7 @@ import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -47,12 +47,13 @@ public class JobWorkerTest { public final String foobar = "aux"; }; - originalType = JobType.ServiceInstantiation; - jobUnderTest = new JobAdapterImpl().createJob( + originalType = JobType.MacroServiceInstantiation; + jobUnderTest = new JobAdapterImpl().createServiceInstantiationJob( originalType, originalData, UUID.randomUUID(), "my user id", + "optimisticUniqueServiceInstanceName", RandomUtils.nextInt() ); } @@ -62,7 +63,7 @@ public class JobWorkerTest { assertNextJobAfterExecuteJob(null, new String[]{"status"}, allOf( hasProperty("status", is(Job.JobStatus.STOPPED)), - hasProperty("data", hasEntry("request", originalData)), + hasProperty("sharedData", hasProperty("request", is(originalData))), hasProperty("type", is(originalType))) ); } diff --git a/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java b/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java new file mode 100644 index 00000000..26db161d --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java @@ -0,0 +1,40 @@ +package org.onap.vid.model; + +import org.apache.commons.lang3.StringUtils; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Date; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class JobAuditStatusTest { + + @DataProvider + public static Object[][] AdditionalInfoSizes() { + return new Object[][]{ + {5, 5}, + {1999,1999}, + {2000, 2000}, + {2001, 2000}, + {10000, 2000} + }; + } + + @Test(dataProvider = "AdditionalInfoSizes") + public void testAdditionalInfoMaxLength(int originalSize, int finalSize) { + JobAuditStatus jobAuditStatus = new JobAuditStatus(); + jobAuditStatus.setAdditionalInfo(StringUtils.repeat("a", originalSize)); + assertThat(jobAuditStatus.getAdditionalInfo().length(), is(finalSize)); + } + + @Test(dataProvider = "AdditionalInfoSizes") + public void testAdditionalInfoMaxLengthInConstructor(int originalSize, int finalSize) { + final String additionalInfo = StringUtils.repeat("a", originalSize); + JobAuditStatus jobAuditStatus = new JobAuditStatus(UUID.randomUUID(), "myJobStatus", JobAuditStatus.SourceStatus.MSO, UUID.randomUUID(), additionalInfo, new Date()); + assertThat(jobAuditStatus.getAdditionalInfo().length(), is(finalSize)); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java b/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java index 4587f4e5..38bec90a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/model/RequestReferencesContainerTest.java @@ -1,9 +1,9 @@ package org.onap.vid.model; -import java.util.Map; - import org.junit.Test; -import org.onap.vid.domain.mso.RequestReferences; +import org.onap.vid.mso.model.RequestReferences; + +import java.util.Map; public class RequestReferencesContainerTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java index 718e22fb..8a821c27 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -22,6 +22,7 @@ package org.onap.vid.mso; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,7 +42,6 @@ import org.togglz.core.manager.FeatureManager; import java.io.IOException; import java.net.URL; -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @@ -206,7 +206,7 @@ public class MsoBusinessLogicImplTest { String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId); org.onap.vid.changeManagement.RequestDetails requestDetails = readRequest( "scaleOutVfModulePayload.json"); - org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest = readExpectedRequest( + org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest = readExpectedRequest( "scaleOutVfModulePayloadToMso.json"); MsoResponseWrapper expectedMsoResponseWrapper = createOkResponse(); given( @@ -229,7 +229,7 @@ public class MsoBusinessLogicImplTest { return objectMapper.readValue(url, org.onap.vid.changeManagement.RequestDetails.class); } - private org.onap.vid.changeManagement.RequestDetailsWrapper readExpectedRequest(String requestJsonFilename) + private org.onap.vid.changeManagement.RequestDetailsWrapper readExpectedRequest(String requestJsonFilename) throws IOException { Path path = Paths.get("payload_jsons", requestJsonFilename); URL url = this.getClass().getClassLoader().getResource(path.toString()); @@ -252,15 +252,15 @@ public class MsoBusinessLogicImplTest { } @Test - public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws IOException { + public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws Exception { //given String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_response.json"); String scaleOutActionOrchestrationRequests = getFileContentAsString("mso_action_scaleout_sample_response.json"); MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class); given(msoInterface - .getOrchestrationRequestsForDashboard(any(String.class), any(String.class), any(String.class), - any(RestObject.class))) + .getOrchestrationRequest(any(String.class), any(String.class), any(String.class), + any(RestObject.class), anyBoolean())) .willReturn(msoResponseWrapperMock); given(msoResponseWrapperMock.getEntity()) .willReturn(vnfModelTypeOrchestrationRequests, scaleOutActionOrchestrationRequests); @@ -276,14 +276,14 @@ public class MsoBusinessLogicImplTest { .map(el -> el.getRequestType().toUpperCase()) .collect(Collectors.toList())); assertThat(filteredOrchestrationReqs) - .extracting(org.onap.vid.domain.mso.Request::getRequestScope) + .extracting(Request::getRequestScope) .containsOnly("vnf", "vfModule"); } - private String getFileContentAsString(String resourceName) throws IOException { - URL url = this.getClass().getClassLoader().getResource("."); - Path path = Paths.get(url.getPath(), "payload_jsons", resourceName); - return new String(Files.readAllBytes(path)); + private String getFileContentAsString(String resourceName) throws Exception { + Path path = Paths.get("payload_jsons", resourceName); + URL url = this.getClass().getClassLoader().getResource(path.toString()); + return IOUtils.toString(url.toURI(), "UTF-8"); } private static class MsoRequestWrapperMatcher implements diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java index 5c5d6fd4..b396507b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java @@ -6,11 +6,11 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.controllers.OperationalEnvironmentController; -import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentManifest; -import org.onap.vid.mso.MsoBusinessLogic; -import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.controller.OperationalEnvironmentController; +import org.onap.vid.controller.OperationalEnvironmentController.OperationalEnvironmentManifest; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; @@ -28,10 +28,10 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -@Test public class MsoOperationalEnvironmentTest { private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(null,null); + private static final Logger logger = LogManager.getLogger(MsoOperationalEnvironmentTest.class); @Test(dataProvider = "getOperationalEnvironmentActivationPermutations") public void testJsonResultOfOperationalEnvironmentActivationRequestDetails(HashMap permutation) throws IOException { @@ -170,8 +170,8 @@ public class MsoOperationalEnvironmentTest { try { JSONAssert.assertEquals("built mso request is not ok", expected, requestDetailsAsString, JSONCompareMode.STRICT); } catch (AssertionError | Exception e) { - System.out.println("requestDetailsAsString: \n" + requestDetailsAsString); - System.out.println("expected: \n" + expected); + logger.info("requestDetailsAsString: \n" + requestDetailsAsString); + logger.info("expected: \n" + expected); throw e; } } diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java new file mode 100644 index 00000000..9d773d73 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/mso/RequestDetailsTest.java @@ -0,0 +1,63 @@ +package org.onap.vid.mso; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.mso.rest.RequestDetails; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static org.testng.AssertJUnit.assertEquals; + +public class RequestDetailsTest { + + private static final ImmutableList LCP_CLOUD_REGION_ID_PATH = ImmutableList.of("requestDetails", "cloudConfiguration", "lcpCloudRegionId"); + + @DataProvider + public static Object[][] extractValueByPathDataProvider() { + + RequestDetails requestDetails1 = new RequestDetails(); + Map cloudConfiguration = ImmutableMap.of("lcpCloudRegionId", "lcp1"); + requestDetails1.setAdditionalProperty("requestDetails", + ImmutableMap.of("cloudConfiguration", cloudConfiguration)); + + + return new Object[][] { + { requestDetails1, LCP_CLOUD_REGION_ID_PATH, String.class, "lcp1" }, + { requestDetails1, ImmutableList.of("requestDetails", "cloudConfiguration"), Map.class, cloudConfiguration }, + + }; + } + + @Test(dataProvider = "extractValueByPathDataProvider") + public void testExtractValueByPath(RequestDetails requestDetails, List keys, Class clz, Object expectedValue) { + assertEquals(expectedValue, requestDetails.extractValueByPathUsingAdditionalProperties(keys, clz)); + } + + @DataProvider + public static Object[][] extractValueByPathDataProviderThrowException() { + RequestDetails requestDetails1 = new RequestDetails(); + requestDetails1.setAdditionalProperty("requestDetails", + ImmutableMap.of("cloudConfiguration", "notMap")); + + RequestDetails requestDetails2 = new RequestDetails(); + requestDetails2.setAdditionalProperty("requestDetails", + ImmutableMap.of("cloudConfiguration", Collections.EMPTY_MAP)); + + return new Object[][] { + { new RequestDetails(), LCP_CLOUD_REGION_ID_PATH, String.class}, + { requestDetails1, LCP_CLOUD_REGION_ID_PATH, String.class}, + { requestDetails1, ImmutableList.of("requestDetails", "abc"), String.class}, + { requestDetails2, LCP_CLOUD_REGION_ID_PATH, String.class}, + }; + } + + @Test(dataProvider = "extractValueByPathDataProviderThrowException", expectedExceptions = NotFoundException.class) + public void testExtractValueByPathThrowException(RequestDetails requestDetails, List keys, Class clz) { + requestDetails.extractValueByPathUsingAdditionalProperties(keys, clz); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java deleted file mode 100644 index 3bcc01d6..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.onap.vid.mso; - -import static org.junit.Assert.*; -import org.junit.Test; -import org.onap.vid.changeManagement.RequestDetailsWrapper; - -import java.util.*; - -import javax.ws.rs.core.MultivaluedHashMap; - -import org.junit.Assert; - -public class RestMsoImplementationTest { - - private RestMsoImplementation createTestSubject() { - return new RestMsoImplementation(); - } - - @Test - public void testInitMsoClient() throws Exception { - RestMsoImplementation testSubject; - MultivaluedHashMap result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.initMsoClient(); - } catch (Exception e) { - } - } - - - @Test - public void testGetForObject() throws Exception { - RestMsoImplementation testSubject; - String sourceID = ""; - String path = ""; - - // default test - try { - testSubject = createTestSubject(); - testSubject.GetForObject(sourceID, path, null); - } catch (Exception e) { - } - } - - @Test - public void testDelete() throws Exception { - RestMsoImplementation testSubject; - String sourceID = ""; - String path = ""; - - // default test - try { - testSubject = createTestSubject(); - testSubject.Delete(null, null, sourceID, path, null); - } catch (Exception e) { - } - } - - @Test - public void testPostForObject() throws Exception { - RestMsoImplementation testSubject; - Object requestDetails = null; - String sourceID = ""; - String path = ""; - - // default test - try { - testSubject = createTestSubject(); - testSubject.PostForObject(requestDetails, sourceID, path, null); - } catch ( - - Exception e) { - } - } - - - - @Test - public void testPrepareClient() throws Exception { - RestMsoImplementation testSubject; - String path = ""; - String methodName = ""; - - // default test - try { - testSubject = createTestSubject(); - testSubject.prepareClient(path, methodName); - } catch ( - - Exception e) { - } - } - - - - - // @Test - // public void testInitMsoClient() throws Exception { - // RestMsoImplementation testSubject; - // - // // default test - // testSubject = createTestSubject(); - // testSubject.initMsoClient(); - // } - -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java index 9e00a781..cac6d089 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/model/OperationalEnvironmentActivateInfoTest.java @@ -1,9 +1,9 @@ package org.onap.vid.mso.model; import org.junit.Test; -import org.onap.vid.controllers.OperationalEnvironmentController; -import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentActivateBody; -import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentManifest; +import org.onap.vid.controller.OperationalEnvironmentController; +import org.onap.vid.controller.OperationalEnvironmentController.OperationalEnvironmentActivateBody; +import org.onap.vid.controller.OperationalEnvironmentController.OperationalEnvironmentManifest; public class OperationalEnvironmentActivateInfoTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java index 400a34e9..c855be75 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java @@ -1,8 +1,6 @@ package org.onap.vid.mso.rest; import org.junit.Test; -import org.onap.vid.domain.mso.InstanceIds; -import org.onap.vid.domain.mso.RequestStatus; public class AsyncRequestStatusTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index bfc82ce2..73a3964d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -20,6 +20,7 @@ */ package org.onap.vid.mso.rest; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xebialabs.restito.server.StubServer; import org.glassfish.grizzly.http.util.HttpStatus; import org.junit.AfterClass; @@ -28,8 +29,8 @@ import org.junit.Ignore; import org.junit.Test; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.client.SyncRestClient; -import org.onap.vid.controllers.MsoController; -import org.onap.vid.mso.MsoInterface; +import org.onap.vid.controller.MsoController; +import org.onap.vid.controller.WebConfig; import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; @@ -44,8 +45,8 @@ import java.nio.file.Paths; import java.util.Properties; import java.util.UUID; -import static org.onap.vid.controllers.MsoController.SVC_INSTANCE_ID; -import static org.onap.vid.controllers.MsoController.VNF_INSTANCE_ID; +import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; +import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; @ContextConfiguration(classes = {SystemProperties.class}) public class MsoRestClientNewTest { @@ -304,7 +305,7 @@ public class MsoRestClientNewTest { // default test try { testSubject = createTestSubject(); - result = testSubject.getOrchestrationRequestsForDashboard(t, sourceId, endpoint, restObject); + result = testSubject.getOrchestrationRequest(t, sourceId, endpoint, restObject, true); } catch (Exception e) { } } @@ -466,7 +467,8 @@ public class MsoRestClientNewTest { } private MsoRestClientNew msoRestClient() { - return new MsoRestClientNew(new SyncRestClient(MsoInterface.objectMapper()), baseUrl()); + final WebConfig webConfig = new WebConfig(); + return new MsoRestClientNew(new SyncRestClient(webConfig.unirestFasterxmlObjectMapper(new ObjectMapper())), baseUrl()); } private MsoRestClientNew createTestSubject() { diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java index 2b067b28..3d193777 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java @@ -23,21 +23,19 @@ package org.onap.vid.mso.rest; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONObject; import org.junit.Assert; +import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.RequestDetails; import org.onap.vid.client.SyncRestClient; -import org.onap.vid.domain.mso.CloudConfiguration; -import org.onap.vid.domain.mso.ModelInfo; -import org.onap.vid.domain.mso.RequestInfo; -import org.onap.vid.domain.mso.RequestParameters; +import org.onap.vid.controller.LocalWebConfig; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoBusinessLogicImpl; -import org.onap.vid.mso.rest.MsoRestClientNew; -import org.onap.vid.controllers.LocalWebConfig; -import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.mso.model.RequestInfo; +import org.onap.vid.mso.model.RequestParameters; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.annotations.Test; -import org.togglz.core.manager.FeatureManager; @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java new file mode 100644 index 00000000..e09ca807 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java @@ -0,0 +1,210 @@ +package org.onap.vid.mso.rest; + +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.mockito.*; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.ServletRequestHelper; +import org.onap.vid.aai.util.SystemPropertyHelper; +import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; +import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.Unchecked; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.MultivaluedMap; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.mockito.Mockito.when; + + +public class OutgoingRequestHeadersTest { + + +// @InjectMocks +// private RestMsoImplementation restMsoImplementation; + + @Mock + private SystemPropertyHelper systemPropertyHelper; + + @Mock + private ServletRequestHelper servletRequestHelper; + + @InjectMocks + private AAIRestInterface aaiRestInterface; + + @Captor + private ArgumentCaptor> multivaluedMapArgumentCaptor; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + when(servletRequestHelper.extractOrGenerateRequestId()).thenAnswer(invocation -> UUID.randomUUID().toString()); + } + + @BeforeMethod + private void putRequestInSpringContext() { + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes((HttpServletRequest) PromiseEcompRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest()))); + } + +// @DataProvider +// public Object[][] msoMethods() { +// return Stream.>of( +// +// client -> client.Get(new Object(), "/any path", new RestObject<>(), false), +// client -> client.GetForObject("/any path", Object.class), +// client -> client.Post("", "some payload", "/any path", new RestObject<>()), +// client -> client.PostForObject("some payload", "/any path", Object.class), +// client -> client.Put(Object.class, new RequestDetailsWrapper(), "/any path", new RestObject<>()) +// +// ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); +// } +// +// @Test(dataProvider = "msoMethods") +// public void mso(Consumer f) throws Exception { +// final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); +// +// f.accept(restMsoImplementation); +// +// Invocation.Builder fakeBuilder = mocks.getFakeBuilder(); +// Object requestIdValue = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder); +// assertEquals(requestIdValue, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID")); +// +// assertThat((String) captureHeaderKeyAndReturnItsValue(fakeBuilder, "Authorization"), startsWith("Basic ")); +// assertThat(captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-PartnerName"), equalTo("VID")); +// } +// +// @Test +// public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception { +// +// final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); +// String randomUserName = randomAlphabetic(10); +// +// restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName)); +// assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID")); +// } + + @DataProvider + public Object[][] aaiMethods() { + return Stream.>of( + + client -> client.RestGet("from app id", "some transId", Unchecked.toURI("/any path"), false), + client -> client.Delete("whatever source id", "some transId", "/any path"), + client -> client.RestPost("from app id", "/any path", "some payload", false), + client -> client.RestPut("from app id", "/any path", "some payload", false, false) + + ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + @Test(dataProvider = "aaiMethods") + public void aai(Consumer f) throws Exception { + final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface); + + f.accept(aaiRestInterface); + + verifyXEcompRequestIdHeaderWasAdded(mocks.getFakeBuilder()); + } + +// @Test(dataProvider = "schedulerMethods") +// public void scheduler(Consumer f) throws Exception { +// +// This test os not feasible in the wat acheduler is implemented today, +// as Scheduler's client is rewritten in every call. +// +// :-( +// +// } + + private Object verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) { + final String requestIdHeader = "x-ecomp-requestid"; + final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + Object requestId = captureHeaderKeyAndReturnItsValue(fakeBuilder, requestIdHeader); + + assertThat("header '" + requestIdHeader + "' should be a uuid", requestId, + allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex)))); + return requestId; + } + + private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) { + // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid) + // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid)) + + Object requestId; + // The 'verify()' will capture the request id. If no match -- AssertionError will + // catch for a second chance -- another 'verify()'. + try { + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Object.class); + Mockito.verify(fakeBuilder) + .header( + Matchers.argThat(s -> equalsIgnoreCase(s, headerName)), + argumentCaptor.capture() + ); + requestId = argumentCaptor.getValue(); + + } catch (AssertionError e) { + Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture()); + + final MultivaluedMap headersMap = multivaluedMapArgumentCaptor.getValue(); + final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName); + + assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader)); + requestId = headersMap.getFirst(thisRequestIdHeader); + } + return requestId; + } + + private String getFromSetCaseInsensitive(Set set, String key) { + return set.stream() + .filter(anotherString -> anotherString.equalsIgnoreCase(key)) + .findFirst() + .orElse(key); + } + + private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class clazz) throws IllegalAccessException { + TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); + Client fakeClient = mocks.getFakeClient(); + + FieldUtils.writeStaticField(clazz, "client", fakeClient, true); + + return mocks; + } + + private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException { + TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); + Client fakeClient = mocks.getFakeClient(); + + FieldUtils.writeField(instance, "client", fakeClient, true); + + return mocks; + } + + @FunctionalInterface + public interface ThrowingConsumer extends Consumer { + @Override + default void accept(T t) { + try { + acceptThrows(t); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + void acceptThrows(T t) throws Exception; + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java deleted file mode 100644 index 197bfe75..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.onap.vid.mso.rest; - -import com.google.common.collect.ImmutableList; -import org.apache.commons.lang3.reflect.FieldUtils; -import org.mockito.*; -import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; -import org.onap.vid.mso.RestMsoImplementation; -import org.onap.vid.mso.RestObject; -import org.onap.vid.testUtils.TestUtils; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.core.MultivaluedMap; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - - -public class OutgoingRequestIdTest { - - - @InjectMocks - private RestMsoImplementation restMsoImplementation; - - @InjectMocks - private AAIRestInterface aaiRestInterface; - - - @Captor - private ArgumentCaptor> multivaluedMapArgumentCaptor; - - @BeforeClass - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @BeforeMethod - private void putRequestInSpringContext() { - RequestContextHolder.setRequestAttributes(new ServletRequestAttributes((HttpServletRequest) PromiseEcompRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest()))); - } - - @DataProvider - public Object[][] msoMethods() { - return Stream.>of( - - client -> client.Get(new Object(), "whatever source id", "/any path", new RestObject<>()), - client -> client.GetForObject("whatever source id", "/any path", Object.class), - client -> client.Post(new Object(), "some payload", "whatever source id", "/any path", new RestObject<>()), - client -> client.PostForObject("some payload", "whatever source id", "/any path", Object.class), - client -> client.Put(Object.class, new RequestDetailsWrapper(), "whatever source id", "/any path", new RestObject<>()) - - ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); - } - - @Test(dataProvider = "msoMethods") - public void mso(Consumer f) throws Exception { - final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); - - f.accept(restMsoImplementation); - - verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder()); - } - - @DataProvider - public Object[][] aaiMethods() { - return Stream.>of( - - client -> client.RestGet("from app id", "some transId", "/any path", false), - client -> client.Delete("whatever source id", "some transId", "/any path"), - client -> client.RestPost("from app id", "/any path", "some payload", false), - client -> client.RestPut("from app id", "/any path", "some payload", false) - - ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); - } - - //@Test(dataProvider = "aaiMethods") - public void aai(Consumer f) throws Exception { - final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface); - - f.accept(aaiRestInterface); - - verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder()); - } - -// @Test(dataProvider = "schedulerMethods") -// public void scheduler(Consumer f) throws Exception { -// -// This test os not feasible in the wat acheduler is implemented today, -// as Scheduler's client is rewritten in every call. -// -// :-( -// -// } - - private void verifyRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) { - final String requestIdHeader = "x-ecomp-requestid"; - final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; - - // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid) - // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid)) - - Object requestId; - // The 'verify()' will capture the request id. If no match -- AssertionError will - // catch for a second chance -- another 'verify()'. - try { - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Object.class); - Mockito.verify(fakeBuilder) - .header( - Matchers.argThat(s -> equalsIgnoreCase(s, requestIdHeader)), - argumentCaptor.capture() - ); - requestId = argumentCaptor.getValue(); - - } catch (AssertionError e) { - Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture()); - - final MultivaluedMap headersMap = multivaluedMapArgumentCaptor.getValue(); - final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), requestIdHeader); - - assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader)); - requestId = headersMap.getFirst(thisRequestIdHeader); - } - - assertThat("header '" + requestIdHeader + "' should be a uuid", requestId, - allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex)))); - } - - private String getFromSetCaseInsensitive(Set set, String key) { - return set.stream() - .filter(anotherString -> anotherString.equalsIgnoreCase(key)) - .findFirst() - .orElse(key); - } - - private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class clazz) throws IllegalAccessException { - TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); - Client fakeClient = mocks.getFakeClient(); - - FieldUtils.writeStaticField(clazz, "client", fakeClient, true); - - return mocks; - } - - private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException { - TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); - Client fakeClient = mocks.getFakeClient(); - - FieldUtils.writeField(instance, "client", fakeClient, true); - - return mocks; - } - - @FunctionalInterface - public interface ThrowingConsumer extends Consumer { - @Override - default void accept(T t) { - try { - acceptThrows(t); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - void acceptThrows(T t) throws Exception; - } - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java index 4b35430e..1bedc191 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedInstanceTest.java @@ -1,9 +1,9 @@ package org.onap.vid.mso.rest; -import java.util.Map; - import org.junit.Test; -import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.mso.model.ModelInfo; + +import java.util.Map; public class RelatedInstanceTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java deleted file mode 100644 index 91d61bd9..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RelatedModelTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.onap.vid.mso.rest; - -import java.util.Map; - -import org.junit.Test; -import org.onap.vid.domain.mso.ModelInfo; - - -public class RelatedModelTest { - - private RelatedModel createTestSubject() { - return new RelatedModel(); - } - - - @Test - public void testGetModelInfo() throws Exception { - RelatedModel testSubject; - ModelInfo result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getModelInfo(); - } - - - @Test - public void testSetModelInfo() throws Exception { - RelatedModel testSubject; - ModelInfo modelInfo = null; - - // default test - testSubject = createTestSubject(); - testSubject.setModelInfo(modelInfo); - } - - - @Test - public void testToString() throws Exception { - RelatedModel testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } - - - @Test - public void testGetAdditionalProperties() throws Exception { - RelatedModel testSubject; - Map result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAdditionalProperties(); - } - - - @Test - public void testSetAdditionalProperty() throws Exception { - RelatedModel testSubject; - String name = ""; - Object value = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAdditionalProperty(name, value); - } - - - @Test - public void testHashCode() throws Exception { - RelatedModel testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.hashCode(); - } - - - @Test - public void testEquals() throws Exception { - RelatedModel testSubject; - Object other = null; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.equals(other); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java index e4716d58..f6b7c584 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java @@ -1,11 +1,13 @@ package org.onap.vid.mso.rest; +import org.junit.Test; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.mso.model.RequestInfo; + import java.util.List; import java.util.Map; -import org.junit.Test; -import org.onap.vid.domain.mso.*; - public class RequestDetailsTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java index f07fd1ab..9250340a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestTest.java @@ -1,8 +1,6 @@ package org.onap.vid.mso.rest; import org.junit.Test; -import org.onap.vid.domain.mso.InstanceIds; -import org.onap.vid.domain.mso.RequestStatus; public class RequestTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java deleted file mode 100644 index 4e2676c6..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyResponseWrapperTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.onap.vid.policy; - -import org.junit.Test; - -public class PolicyResponseWrapperTest { - - private PolicyResponseWrapper createTestSubject() { - return new PolicyResponseWrapper(); - } - - @Test - public void testGetEntity() throws Exception { - PolicyResponseWrapper testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getEntity(); - } - - @Test - public void testGetStatus() throws Exception { - PolicyResponseWrapper testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getStatus(); - } - - @Test - public void testSetStatus() throws Exception { - PolicyResponseWrapper testSubject; - int v = 0; - - // default test - testSubject = createTestSubject(); - testSubject.setStatus(v); - } - - @Test - public void testSetEntity() throws Exception { - PolicyResponseWrapper testSubject; - String v = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setEntity(v); - } - - @Test - public void testToString() throws Exception { - PolicyResponseWrapper testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } - - @Test - public void testGetResponse() throws Exception { - PolicyResponseWrapper testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getResponse(); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java deleted file mode 100644 index b94d21b9..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestIntTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.onap.vid.policy; - -import org.junit.Test; -import org.onap.vid.policy.rest.RequestDetails; - -public class PolicyRestIntTest { - - private PolicyRestInt createTestSubject() { - return new PolicyRestInt(); - } - - @Test - public void testLogRequest() throws Exception { - PolicyRestInt testSubject; - RequestDetails r = null; - - // test 1 - testSubject = createTestSubject(); - r = null; - testSubject.logRequest(r); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java deleted file mode 100644 index bb21c89f..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceFactoryTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.onap.vid.policy; - -import org.junit.Test; - -public class PolicyRestInterfaceFactoryTest { - - private PolicyRestInterfaceFactory createTestSubject() { - return new PolicyRestInterfaceFactory(); - } - - @Test - public void testGetInstance() throws Exception { - PolicyRestInterfaceIfc result; - - // default test - result = PolicyRestInterfaceFactory.getInstance(); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java deleted file mode 100644 index 05191fc5..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyRestInterfaceTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.onap.vid.policy; - -import org.json.simple.JSONObject; -import org.junit.Test; -import org.onap.vid.policy.rest.RequestDetails; - -public class PolicyRestInterfaceTest { - - private PolicyRestInterface createTestSubject() { - return new PolicyRestInterface(); - } - - @Test - public void testLogRequest() throws Exception { - PolicyRestInterface testSubject; - RequestDetails r = null; - - // default test - testSubject = createTestSubject(); - testSubject.logRequest(r); - } - - /*@Test - public void testInitRestClient() throws Exception { - PolicyRestInterface testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.initRestClient(); - }*/ - -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java deleted file mode 100644 index 1629081a..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/PolicyUtilTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.onap.vid.policy; - -import org.glassfish.jersey.client.ClientResponse; -import org.junit.Assert; -import org.junit.Test; - -public class PolicyUtilTest { - - private PolicyUtil createTestSubject() { - return new PolicyUtil(); - } - - @Test - public void testWrapResponse() throws Exception { - String body = ""; - int statusCode = 0; - PolicyResponseWrapper result; - - // default test - result = PolicyUtil.wrapResponse(body, statusCode); - } - - - @Test - public void testWrapResponse_2() throws Exception { - RestObject rs = null; - PolicyResponseWrapper result; - - // test 1 - rs = null; - result = PolicyUtil.wrapResponse(rs); - Assert.assertNotNull(result); - } - - @Test - public void testConvertPojoToString() throws Exception { - String result; - - // test 1 - result = PolicyUtil.convertPojoToString(null); - Assert.assertEquals("", result); - } - - @Test - public void testMain() throws Exception { - String[] args = new String[] { "" }; - - // default test - PolicyUtil.main(args); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java deleted file mode 100644 index eab343ab..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/RestObjectTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.onap.vid.policy; - -import org.junit.Test; - -public class RestObjectTest { - - private RestObject createTestSubject() { - return new RestObject(); - } - - @Test - public void testSet() throws Exception { - RestObject testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.set(null); - } - - @Test - public void testGet() throws Exception { - RestObject testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.get(); - } - - @Test - public void testSetStatusCode() throws Exception { - RestObject testSubject; - int v = 0; - - // default test - testSubject = createTestSubject(); - testSubject.setStatusCode(v); - } - - @Test - public void testGetStatusCode() throws Exception { - RestObject testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getStatusCode(); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java deleted file mode 100644 index 3c17a66a..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/policy/rest/RequestDetailsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.onap.vid.policy.rest; - -import org.junit.Test; - - -public class RequestDetailsTest { - - private RequestDetails createTestSubject() { - return new RequestDetails(); - } - - - @Test - public void testGetPolicyName() throws Exception { - RequestDetails testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getPolicyName(); - } - - - @Test - public void testSetPolicyName() throws Exception { - RequestDetails testSubject; - String policyName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setPolicyName(policyName); - } -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java index b023bc26..6fdc21f7 100644 --- a/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java @@ -1,9 +1,5 @@ package org.onap.vid.roles; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - import org.junit.Test; @@ -14,16 +10,6 @@ public class RoleProviderTest { } - @Test - public void testExtractRoleFromSession() throws Exception { - HttpServletRequest request = null; - List result; - - // default test - result = RoleProvider.extractRoleFromSession(request); - } - - // @Test // public void testGetUserRoles() throws Exception { // RoleProvider testSubject; diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java index 8c8642e3..36e2b33d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjectTest.java @@ -1,6 +1,7 @@ package org.onap.vid.scheduler; import org.junit.Test; +import org.onap.vid.mso.RestObject; public class RestObjectTest { @@ -46,23 +47,4 @@ public class RestObjectTest { result = testSubject.getStatusCode(); } - @Test - public void testSetUUID() throws Exception { - RestObject testSubject; - String uuid = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setUUID(uuid); - } - - @Test - public void testGetUUID() throws Exception { - RestObject testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getUUID(); - } } \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java index 13fc57f3..31335edf 100644 --- a/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/RestObjects/RestObjectTest.java @@ -1,6 +1,7 @@ package org.onap.vid.scheduler.RestObjects; import org.junit.Test; +import org.onap.vid.mso.RestObject; public class RestObjectTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java index 0655aca9..3e1c89c7 100644 --- a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java @@ -31,7 +31,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.mso.RestObject; import org.onap.vid.testUtils.StubServerUtil; import org.testng.annotations.AfterMethod; @@ -82,19 +82,19 @@ public class SchedulerRestInterfaceTest { RestObject sampleRestObj = new RestObject<>(); serverUtil.prepareGetCall("/test", RESPONSE_CONTENT, Action.ok()); - schedulerInterface.Get("", SAMPLE_SOURCE_ID, "", sampleRestObj); + schedulerInterface.Get("", "", sampleRestObj); assertResponseHasExpectedBodyAndStatus(sampleRestObj, RESPONSE_CONTENT, 200); } - @Test(expected = GenericUncheckedException.class) + @Test(expected = org.onap.vid.aai.ExceptionWithRequestInfo.class) public void shouldRaiseExceptionWhenErrorOccursDuringGet() throws JsonProcessingException { prepareEnvForTest(); RestObject sampleRestObj = new RestObject<>(); serverUtil.prepareGetCall("/test", ERROR_RESPONSE, Action.status(HttpStatus.INTERNAL_SERVER_ERROR_500)); - schedulerInterface.Get("", SAMPLE_SOURCE_ID, "", sampleRestObj); + schedulerInterface.Get("", "", sampleRestObj); } @Test @@ -125,7 +125,6 @@ public class SchedulerRestInterfaceTest { assertThat(sampleRestObj.getStatusCode()).isEqualTo(expectedStatusCode); assertThat(parsedResult).isInstanceOf(String.class).isEqualTo(expectedResponse); - assertThat(sampleRestObj.getUUID()).isNull(); } diff --git a/vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java b/vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java deleted file mode 100644 index e3ccdd96..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/selenium/FirstClass.java +++ /dev/null @@ -1,605 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.selenium; - -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - - -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.support.ui.Select; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.apache.log4j.Logger; -import org.testng.Assert; -import org.testng.asserts.*; - -/** - * The Class FirstClass. - */ -public class FirstClass { - - /** The login button. */ - WebElement loginButton; - - /** The eg. */ - String eg; - - /** The login. */ - WebElement login; - - /** The pwd. */ - WebElement pwd; - - /** The log. */ - Logger log; - - /** The errormessage. */ - WebElement errormessage; - - - /** The driver. */ - WebDriver driver=new FirefoxDriver(); - - - - /** The config prop. */ - private final Properties configProp = new Properties(); - - - /** - * Instantiates a new first class. - */ - private FirstClass() { - // TODO Auto-generated constructor stub - // - try{ - // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties"); - //FileInputStream input1 = new FileInputStream("objectmap.properties"); - - InputStream input =new FileInputStream("objectconfig.properties"); - System.out.println("Read all properties from file"); - configProp.load(input); - System.out.println("Read all properties from file completed"); - } - catch(IOException e) { - - e.printStackTrace(); - } - } - - - /* - - - @BeforeClass - public void setUp() { - System.out.println("*******************"); - System.out.println("launching IE browser"); - System.setProperty("webdriver.ie.driver", driverPath+"IEDriverServer.exe"); - driver = new InternetExplorerDriver(); - driver.findElement(By.className()); - driver.manage().window().maximize(); - - - login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']")); - pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']")); - loginButton = driver.findElement(By.id("loginBtn")); - } - - - */ - /** - * Sets the up. - */ - // TODO Auto-generated method stub - @BeforeClass - public void setUp() - { - - - //WebDriver driver=new FirefoxDriver(); - - log = Logger.getLogger(FirstClass.class.getName()); - - - - // Get url - driver.get(configProp.getProperty("baseURL")); - driver.manage().window().maximize(); - - - login = driver.findElement(By.xpath(configProp.getProperty("login"))); - - pwd = driver.findElement(By.xpath(configProp.getProperty("pwd"))); - loginButton = driver.findElement(By.id(configProp.getProperty("loginButton"))); - } - - - /** - * Empty username password. - */ - @Test(priority=1) - public void emptyUsernamePassword() - { - - - //User Name and Password field is empty - log.info("-----VID-11 TC-8----Username and password empty"); - loginButton.click(); - errormessage=driver.findElement(By.xpath("//*[@id='errorInfo']/span")); - String errmsg= errormessage.getText(); - //System.out.println("Error message is"+errmsg); - //String expected = "Invaild username or password, Please try again"; - - //Assert.assertEquals(errmsg,expected); - - Boolean str = driver.getPageSource().contains("Invalid username or password, Please try again"); - System.out.println(driver.getPageSource().contains("Invalid username or password, Please try again")); - - if(str==true) - { - log.info("Error message validated"); - log.info("VID-11 TC-8 PASSED"); - - }else - log.error("Failed validation"); - - } - - - - /** - * Invalid user name. - */ - @Test(priority=2) - public void invalidUserName() - { - - log.info("-----VID-11 TC-6----Invalid Username and Valid Password"); - - - login.sendKeys("xxx"); - pwd.sendKeys("abc123"); - loginButton.click(); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - String errmsg= errormessage.getText(); - String expected = "Invalid username or password, Please try again"; - Assert.assertEquals(errmsg,expected); - //Boolean str1 = driver.getPageSource().contains("Invalid username or password, Please try again"); - //System.out.print(str1); - - log.info("VID-11 TC-6 PASSED"); - - } - - - /** - * Invalid password. - */ - @Test(priority=3) - public void invalidPassword() - { - log.info("-----VID-11 TC-7----Valid Username and Invalid Password"); - // Valid user name and Invalid password. - login.clear(); - pwd.clear(); - login.sendKeys("testuser"); - pwd.sendKeys("xxx"); - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - - String errmsg= errormessage.getText(); - String expected = "Invalid username or password, Please try again"; - Assert.assertEquals(errmsg,expected); - - //Boolean str2 = driver.getPageSource().contains("Invaild username or password, Please try again"); - //System.out.print(str2); - - log.info("VID-11 TC-7 PASSED"); - } - - - /** - * Login successful. - */ - @Test(priority=4) - public void loginSuccessful() - { - log.info("-----VID-11 TC-1----Valid Username and Valid Password"); - //Login with valid user name and password. - login.clear(); - login.sendKeys("su"); - pwd.clear(); - pwd.sendKeys("fusion"); - - - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - try { - Thread.sleep(6000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances")); - log.info("VID-11 TC-1 PASSED"); - - } - - - /** - * Verify home page elements left pane. - */ - @Test(priority=5) - public void verifyHomePageElementsLeftPane() - - { - - - log.info("VID-10 TC 1 "); - //VID Home - log.info("VID 11 TC-2"); - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[1]/a/span")).isDisplayed(); - //Create New Service Instance - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[2]/a/span")).isDisplayed(); - - //Browse Service Type - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[3]/a/span")).isDisplayed(); - //View Log - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[4]/a/span")).isDisplayed(); - - //Profile - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[5]/a/span")).isDisplayed(); - //Admin - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).isDisplayed(); - //Logout - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a/span")).isDisplayed(); - - //Infrastructure Subscriber Name - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[1]/div/label")).isDisplayed(); - //Infrastructure Subscriber Name Select Drop down - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")).isDisplayed(); - //Infrastructure Service Type - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[1]/div/label")).isDisplayed(); - //Infrastructure Service Type Select Drop down - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")).isDisplayed(); - //Submit button - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).isDisplayed(); - - //Login Snippet Icon - driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).isDisplayed(); - - - //String bodyText = driver.findElement(By.tagName("body")).getText(); - //Assert.assertTrue("Text not found!", bodyText.contains("Search Existing Service Instances")); - //Assert.IsTrue(driver.getPageSource.Contains("Search Existing Service Instances")); - - log.info("VID-12 TC-1"); - Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances")); - Assert.assertTrue(driver.getPageSource().contains("Please search by the Subscriber name or Service Type from below:")); - log.info("VID-12 TC-1 PASSED"); - log.info("VID-10 TC 1 PASSED"); - log.info("VID-11 TC-2 PASSED"); - } - - - /** - * Disabled submit button. - */ - @Test(priority=6) - public void disabledSubmitButton() - { - log.info("VID-12 TC-13"); - //Assert submit button disabled. - Assert.assertFalse(driver.findElement(By.xpath(configProp.getProperty("submitButton"))).isEnabled()); - log.info("VID-12 TC-13 PASSED"); - - } - - /** - * Default list box value. - */ - @Test(priority=7) - public void defaultListBoxValue() - { - log.info("VID-12 TC-2"); - - - //WebElement subscribername =driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")); - - Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))); - Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown")))); - - - WebElement ielement=iSelect.getFirstSelectedOption(); - WebElement oelement=oSelect.getFirstSelectedOption(); - String defaultsubscribername=oelement.getText(); - String defaultservicetype=ielement.getText(); - - Assert.assertEquals(defaultsubscribername,"Select Subscriber Name"); - Assert.assertEquals(defaultservicetype,"Select Service Type"); - - - - - //Verify Select Subscriber Name isDisplayed. - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select/option[1]")).isSelected(); - - //Verify Select Service Type isDisplayed. - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select/option[1]")).isSelected(); - - - log.info("VID-12 TC-2 PASSED"); - - } - - - - /** - * Select subscriber name drop down. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=8) - public void selectSubscriberNameDropDown() throws InterruptedException - { - log.info("------------------VID-10 TC-2,VID-12 TC-11, VID-12 TC-9, VID 12 TC-10,VID-12 TC-6, VID 12 TC-5--------------------"); - - - driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown"))); - - driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown"))); - Thread.sleep(5000); - - //Infrastructure Subscriber Name - Select oSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))); - - List elementCount = oSelect.getOptions(); - log.info("Select Element Count of Service Name"); - System.out.println(elementCount.size()); - - - //Verifying getInfrastructureSubscribersList - log.info("VID-29 TC-1"); - Assert.assertTrue(elementCount.size()>0); - log.info("VID-29 TC-1 PASSED"); - - oSelect.selectByIndex(2); - String selectedOption = new Select(driver.findElement(By.xpath(configProp.getProperty("subscriberNameDropDown")))).getFirstSelectedOption().getText(); - - System.out.println("Service Name selected is " +selectedOption); - log.info("VID-10 TC-2 PASSED"); - - //Submit button is clicked - driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click(); - - - //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed(); - //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:")) - - - //Verify whether the page header is displayed "Global Customer ID" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed(); - Assert.assertTrue(driver.getPageSource().contains("Global Customer ID")); - Assert.assertTrue(driver.getPageSource().contains("Subscriber Name")); - Assert.assertTrue(driver.getPageSource().contains("Service Type")); - Assert.assertTrue(driver.getPageSource().contains("Service Instance ID")); - - log.info("VID-12 TC-5 PASSED"); - log.info("VID-12 TC-11 PASSED"); - - WebElement serviceinstancetable =driver.findElement(By.xpath("//table[@class='tablesorter tablesorter-default ng-isolate-scope']")); - - List rows_table = serviceinstancetable.findElements(By.tagName("tr")); - //To calculate no of rows In table. - int rows_count = rows_table.size(); - - //Loop will execute till the last row of table. - for (int row=0; row Columns_row = rows_table.get(row).findElements(By.tagName("td")); - //To calculate no of columns(cells) In that specific row. - int columns_count = Columns_row.size(); - //System.out.println("Number of cells In Row "+row+" are "+columns_count); - - //Loop will execute till the last cell of that specific row. - for (int column=0; column exx= rows_table.get(1).findElements(By.tagName("td")); - eg=Columns_row.get(2).getText(); - // System.out.println("Cell value of row 1 and column 2 is" +eg); - } - } - - - - - //Verify View/Edit isDisplayed and Click - - driver.findElement(By.xpath("//a[@alt='View/Edit']")).isDisplayed(); - - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/tbody/tr[1]/td[1]/div/a")).click(); - - log.info("User clicked View/Edit"); - - //Verify the Subscriber Name displayed. - String header= driver.findElement(By.xpath("//h1[@class='heading1 ng-binding']")).getText(); - //System.out.println(header); - - - if(header.contains(eg)) - { - System.out.println("Header contains the subscriber name"); - }else - System.out.println("Header does not contain the subscriber name"); - - - - Assert.assertTrue(driver.getPageSource().contains("PerfTest Subscriber00020021")); - log.info("VID-12 TC-6 PASSED"); - - - - driver.navigate().back(); - //Cancel button isDisplayed - driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).isDisplayed(); - log.info("VID-12 TC-9 PASSED"); - - //Cancel button is clicked - driver.findElement(By.xpath("//button[@class='button button--small button--primary']")).click(); - log.info("Cancel button is clicked"); - - //Verifying VID Home page is displayed - Assert.assertTrue(driver.getPageSource().contains("Search Existing Service Instances")); - log.info("VID-12 TC-10 PASSED"); - - } - - - /** - * Refresh subscriber name. - */ - @Test(priority=9) - public void refreshSubscriberName() - { - log.info("VID-10 TC-4"); - - - driver.findElement(By.xpath(configProp.getProperty("refreshButtonSubscriberName"))).isDisplayed(); - - log.info("VID-10 TC-4 PASSED"); - - - } - - - /** - * Select subscriber type drop down. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=9) - public void selectSubscriberTypeDropDown() throws InterruptedException - { - Thread.sleep(5000); - log.info("------------------VID-10 TC-3, VID-12 TC-12,--------------------"); - //Infrastructure Subscriber Type - Select iSelect = new Select(driver.findElement(By.xpath(configProp.getProperty("serviceTypeDropDown")))); - - List ielementCount = iSelect.getOptions(); - log.info("Select Element Count of Service type"); - System.out.println(ielementCount.size()); - iSelect.selectByIndex(1); - - log.info("VID-10 TC-3 PASSED"); - - - //Submit button is clicked - driver.findElement(By.xpath(configProp.getProperty("submitButton"))).click(); - - //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed(); - //Assert.assertTrue(driver.getPageSource().contains("Selected Subscriber's Service Instance Details:")) - log.info("Page Header: Selected Subscriber's Service Instance Details"); - - - //Verify whether the page header is displayed "Global Customer ID" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/div/table/thead/tr/th[2]/div")).isDisplayed(); - - //Assert.assertTrue(driver.getPageSource().contains("Global Customer ID")); - log.info("Table is displayed"); - - log.info("VID-12 TC-12 PASSED"); - - } - - - - /** - * Logout under profile. - */ - @Test(priority=10) - public void logoutUnderProfile() - { - - log.info("-----------VID-11 TC-5---------------------"); - //driver.findElement(By.partialLinkText("Click here to login")).click(); - //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - - driver.findElement(By.xpath(".//*[@class='icon-user-small login-snippet-icon']")).click(); - driver.findElement(By.xpath(".//*[@id='reg-logout-div']/a")).click(); - //Validate that the user has logged out of VID. Displays "Portal" - Assert.assertTrue(driver.getPageSource().contains("Portal")); - - log.info("VID-11 TC-5 PASSED"); - - } - - - - /** - * Tear down. - */ - @AfterClass - public void tearDown() - { - driver.close(); - - } - - - - } - - - - diff --git a/vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java b/vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java deleted file mode 100644 index 19c6b199..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/selenium/LogOutLeftPane.java +++ /dev/null @@ -1,242 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * 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.vid.selenium; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.apache.log4j.Logger; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.openqa.selenium.support.ui.Select; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -/** - * The Class LogOutLeftPane. - */ -@Test(enabled=false) -public class LogOutLeftPane { - - /** The login button. */ - WebElement loginButton; - - /** The login. */ - WebElement login; - - /** The pwd. */ - WebElement pwd; - - /** The log. */ - Logger log; - - /** The errormessage. */ - WebElement errormessage; - - /** The driver. */ - WebDriver driver=new FirefoxDriver(); - - - /** The config prop. */ - private final Properties configProp = new Properties(); - - - /** - * Instantiates a new log out left pane. - */ - private LogOutLeftPane() { - // TODO Auto-generated constructor stub - // - try{ - // InputStream input =this.getClass().getClassLoader().getResourceAsStream("objectmap.properties"); - //FileInputStream input1 = new FileInputStream("objectmap.properties"); - - InputStream input =new FileInputStream("objectconfig.properties"); - System.out.println("Read all properties from file"); - configProp.load(input); - System.out.println("Read all properties from file completed"); - } - catch(IOException e) { - - e.printStackTrace(); - } - } - - - - - /** - * Do before test. - */ - // TODO Auto-generated method stub - @BeforeTest - public void doBeforeTest() - { - //WebDriver driver=new FirefoxDriver(); - - log = Logger.getLogger(LogOutLeftPane.class.getName()); - - - - // Get url - driver.get("http://vid.onap.org:9080/vid/login_external.htm"); - driver.manage().window().maximize(); - - - login = driver.findElement(By.xpath("//input[@class='fn-ebz-text ng-pristine ng-valid']")); - pwd = driver.findElement(By.xpath("//input[@class='span3 ng-pristine ng-valid']")); - loginButton = driver.findElement(By.id("loginBtn")); - } - - - /** - * Expand collapse panel. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=1) - public void expandCollapsePanel() throws InterruptedException - { - - - - login.clear(); - login.sendKeys("su"); - pwd.clear(); - pwd.sendKeys("fusion"); - //driver.findElement(By.partialLinkText("Click here to login")).click(); - //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - - log.info("Clicking Profile link from left pane"); - Thread.sleep(3000); - System.out.println("properties file details --->"+configProp.getProperty("profilelink")); - driver.findElement(By.xpath(configProp.getProperty("profilelink"))).click(); - Thread.sleep(3000); - - //Verify whether the sub panel is displayed - //To verify the following :Search import from webphone and Self - driver.findElement(By.xpath(".//*[@id='panel4']")).isDisplayed(); - log.info("Expand and collapse passed for Profile link"); - - //For Admin - //Verify expand and collapse working for ADMIN - log.info("Clicking Admin link from left pane"); - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[6]/a/span")).click(); - //To verify the following: Roles, Roles Functions, Usages - driver.findElement(By.xpath(".//*[@id='panel5']")).isDisplayed(); - - - log.info("Expand and collapse passed for ADMIN link"); - - log.info("VID-11 TC-3 PASSED"); - - } - - - /** - * Drop down list. - * - * @throws InterruptedException the interrupted exception - */ - @Test(priority=2) - public void dropDownList() throws InterruptedException - { - //VID-12 TC-3 - log.info("VID-12 TC-3"); - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select")); - - //driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select")); - Thread.sleep(5000); - - //Infrastructure Subscriber Name - Select oSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"))); - Select iSelect = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[2]/td[2]/div/select"))); - - List elementCount = oSelect.getOptions(); - log.info("Subscriber Name Drop Down"); - System.out.println(elementCount.size()); - oSelect.selectByIndex(1); - log.info("Subscriber name selected"); - //String selectedOption = new Select(driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[1]/td[2]/div/select"))).getFirstSelectedOption().getText(); - - - List count = iSelect.getOptions(); - log.info("Subscriber type drop down"); - System.out.println(count.size()); - oSelect.selectByIndex(1); - log.info("Subscriber type selected"); - - - - //Submit button is clicked - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/table/tbody/tr[3]/td/div/button")).click(); - - - //Verify whether the page header is displayed "Selected Subscriber's Service Instance Details:" - driver.findElement(By.xpath(".//*[@id='mContent']/div/div/div/h1")).isDisplayed(); - log.info("VID-12 TC-3 PASSED"); - } - - - - - /** - * Logout left pane. - */ - @Test(priority=3) - public void logoutLeftPane() - { - //To Verify if the logout link redirects to Login page when clicked. - - - /*log.info("----------------VID-11 TC-4----------------"); - login.clear(); - login.sendKeys("testuser"); - pwd.clear(); - pwd.sendKeys("abc123"); - //driver.findElement(By.partialLinkText("Click here to login")).click(); - //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); - - loginButton.click(); - driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);*/ - log.info("----------------VID-11 TC-4----------------"); - driver.findElement(By.xpath("html/body/div[1]/div[1]/div/div/div[2]/div/div/div[1]/div/div/accordion/div/div[7]/a")).click(); - //Validate that the user has logged out of VID. Displays "Portal" - Assert.assertTrue(driver.getPageSource().contains("Portal")); - - log.info("VID 11 TC-4 PASSED"); - - driver.close(); - - } - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java new file mode 100644 index 00000000..815c6b9e --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java @@ -0,0 +1,160 @@ +package org.onap.vid.services; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Streams; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.jetbrains.annotations.NotNull; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.asdc.parser.ServiceModelInflator; +import org.onap.vid.asdc.parser.ServiceModelInflator.Names; +import org.onap.vid.model.aaiTree.AAITreeNode; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.util.List; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static java.util.stream.Collectors.toList; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +public class AAIServiceTreeTest { + + @Mock + private VidService sdcService; + @Mock + private ServiceModelInflator serviceModelInflator; + @InjectMocks + private AAIServiceTree aaiServiceTree; + + @BeforeTest + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + private final static String nullString = "null placeholder"; + + + + @Test + public void enrichNodesWithModelCustomizationName_simple3NodesCase_nodesEnriched() { + + when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(ImmutableMap.of( + "version id a", new Names("name a", "key a"), + "version id b", new Names("name b", "key b"), + "version id c", new Names("name c", "key c") + )); + + final ImmutableList versionIds = ImmutableList.of("version id a", "version id b", "version id c"); + final ImmutableList expectedNames = ImmutableList.of( + new Names("name a", "key a"), + new Names("name b", "key b"), + new Names("name c", "key c")); + + + final List nodesUnderTest = nodesWithVersionIds(versionIds); + aaiServiceTree.enrichNodesWithModelCustomizationName(nodesUnderTest, null); + + assertThat(toStrings(nodesUnderTest), containsInAnyOrder(toStringsArray(nodesWithVersionIdsAndCustomizationNames(versionIds, expectedNames)))); + } + + @Test + public void enrichNodesWithModelCustomizationName_noNodes_noError() { + + when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(ImmutableMap.of( + "11c6dc3e-cd6a-41b3-a50e-b5a10f7157d0", new Names("my model cust name", "my key") + )); + + aaiServiceTree.enrichNodesWithModelCustomizationName(emptyList(), null); + } + + @Test + public void enrichNodesWithModelCustomizationName_nothingInModel_nodesUnchanged() { + + when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(emptyMap()); + + final ImmutableList versionIds = ImmutableList.of("version id a", "version id b", "version id c"); + final Names nullNames = new Names(nullString, nullString); + final ImmutableList expectedNames = ImmutableList.of(nullNames, nullNames, nullNames); + + + final List nodesUnderTest = nodesWithVersionIds(versionIds); + + aaiServiceTree.enrichNodesWithModelCustomizationName(nodesUnderTest, null); + + assertThat(toStrings(nodesUnderTest), containsInAnyOrder(toStringsArray(nodesWithVersionIdsAndCustomizationNames(versionIds, expectedNames)))); + } + + @Test + public void enrichNodesWithModelCustomizationName_staggered4NodesAndNull_3nodesEnriched2isNull() { + + when(serviceModelInflator.toNamesByVersionId(any())).thenReturn(ImmutableMap.of( + "version id Z", new Names("name Z", "key Z"), + "version id d", new Names(null, "key d"), + "version id c", new Names("name c", null), + "version id a", new Names("name a", "key a") + )); + + final ImmutableList versionIds = ImmutableList.of("version id a", "version id b", "version id c", "version id d", nullString); + final ImmutableList expectedNames = ImmutableList.of( + new Names("name a", "key a"), + new Names(nullString, nullString), + new Names("name c", nullString), + new Names(nullString, "key d"), + new Names(nullString, nullString) + ); + + + final List nodesUnderTest = nodesWithVersionIds(versionIds); + + aaiServiceTree.enrichNodesWithModelCustomizationName(nodesUnderTest, null); + + assertThat(toStrings(nodesUnderTest), containsInAnyOrder(toStringsArray(nodesWithVersionIdsAndCustomizationNames(versionIds, expectedNames)))); + } + + + + @NotNull + private String[] toStringsArray(List nodes) { + return toStrings(nodes).toArray(new String[] {}); + } + + @NotNull + private List toStrings(List nodes) { + return nodes.stream().map(n -> { + final ReflectionToStringBuilder reflectionToStringBuilder = new ReflectionToStringBuilder(n, ToStringStyle.SHORT_PREFIX_STYLE); + reflectionToStringBuilder.setExcludeNullValues(true); + return reflectionToStringBuilder.toString(); + }).collect(toList()); + } + + @NotNull + private List nodesWithVersionIdsAndCustomizationNames(List versionIds, List customizationNames) { + return Streams + .zip(versionIds.stream(), customizationNames.stream(), this::nodeWithVersionIdAndCustomizationName) + .collect(toList()); + } + + @NotNull + private List nodesWithVersionIds(List versionIds) { + return versionIds.stream() + .map(versionId -> nodeWithVersionIdAndCustomizationName(versionId, new Names(nullString, nullString))) + .collect(toList()); + } + + private AAITreeNode nodeWithVersionIdAndCustomizationName(String versionId, Names names) { + AAITreeNode newNode = new AAITreeNode(); + newNode.setModelVersionId(versionId.equals(nullString) ? null : versionId); + newNode.setModelCustomizationName(names.getModelCustomizationName().equals(nullString) ? null : names.getModelCustomizationName()); + newNode.setKeyInModel(names.getModelKey().equals(nullString) ? null : names.getModelKey()); + return newNode; + } + +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java new file mode 100644 index 00000000..0fac65e4 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeConverterTest.java @@ -0,0 +1,222 @@ +package org.opencomp.vid.services; + +import com.google.common.collect.ImmutableList; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.util.AAITreeConverter; +import org.onap.vid.model.Action; +import org.onap.vid.model.aaiTree.*; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE; + +public class AAITreeConverterTest { + + @InjectMocks + private AAITreeConverter aaiTreeConverter; + + @BeforeTest + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testConvertTreeToUIModel_NoChildren() throws Exception { + + AAITreeNode aaiTree = generateAaiTreeToConvert(0, 0); + + ServiceInstance result = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", A_LA_CARTE); + + assertService(result, 0, 0, true); + } + + @Test + public void testConvertTreeToUIModel_MultipleChildren() throws Exception { + + AAITreeNode aaiTree = generateAaiTreeToConvert(2, 2); + + ServiceInstance serviceInstance = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", null); + + assertService(serviceInstance, 2, 2, false); + + int nodesCounter = 0; + assertThat(serviceInstance.getVnfs().entrySet(), hasSize(2)); + assertVnf(serviceInstance.getVnfs().get("vnf-model-version-id:00"+(nodesCounter++)), 0, 0, false); + assertVnf(serviceInstance.getVnfs().get("vnf-model-version-id:00"+(nodesCounter++)), 0, 0, false); + + assertThat(serviceInstance.getNetworks().entrySet(), hasSize(2)); + assertNetwork(serviceInstance.getNetworks().get("network-model-version-id:00"+(nodesCounter++)), false); + assertNetwork(serviceInstance.getNetworks().get("network-model-version-id:00"+(nodesCounter)), false); + } + + @DataProvider + public static Object[][] vnfWithChildren() { + return new Object[][]{ + {ImmutableList.of(), ImmutableList.of()}, + {ImmutableList.of(true, false), ImmutableList.of()}, + {ImmutableList.of(), ImmutableList.of(false)} + }; + } + + @Test(dataProvider = "vnfWithChildren") + public void testComplexVnfConversion(List vfModules, List networks) { + + AAITreeNode vnfTreeNode = createVnf(1, false); + int nodesCounter = 0; + + for (Boolean customizationName: vfModules) { + vnfTreeNode.getChildren().add(createVfModule(nodesCounter++, customizationName)); + } + + for (Boolean customizationName: networks) { + vnfTreeNode.getChildren().add(createNetwork(nodesCounter++, customizationName)); + } + + Vnf actualVnf = Vnf.from(vnfTreeNode); + + assertVnf(actualVnf, vfModules.size(), networks.size(), false); + + nodesCounter = 0; + for (Boolean customizationName: vfModules) { + String key = customizationName ? "vfModule key in model" : "vfModule-model-version-id"; + + assertThat(actualVnf.getVfModules(), hasKey(key)); + assertThat(actualVnf.getVfModules().get(key), hasKey(key + ":00" + nodesCounter)); + VfModule actualVfModule = actualVnf.getVfModules().get(key).get(key + ":00" + nodesCounter); + assertVfModule(actualVfModule, customizationName); + nodesCounter++; + } + + for (Boolean customizationName: networks) { + String key = customizationName ? "network key in model" : "network-model-version-id"; + + assertThat(actualVnf.getNetworks(), hasKey(key + ":00" + nodesCounter)); + Network actualNetwork = actualVnf.getNetworks().get(key + ":00" + nodesCounter); + assertNetwork(actualNetwork, customizationName); + nodesCounter++; + } + } + + @Test + public void testNetworkConversion() { + AAITreeNode networkTreeNode = createNetwork(1, true); + + Network actualNetwork = Network.from(networkTreeNode); + + assertNetwork(actualNetwork, true); + } + + private AAITreeNode createVnf(int uniqueNumber, boolean hasCustomizationName) { + AAITreeNode vnfTreeNode = new AAITreeNode(); + vnfTreeNode.setId("vnf-instance-id"); + vnfTreeNode.setName("vnf-instance-name"); + vnfTreeNode.setType("generic-vnf"); + vnfTreeNode.setModelVersionId("vnf-model-version-id"); + if (hasCustomizationName) { + vnfTreeNode.setModelCustomizationName("vnf model customization name"); + vnfTreeNode.setKeyInModel("vnf key in model"); + } + vnfTreeNode.setUniqueNumber(uniqueNumber); + return vnfTreeNode; + } + + private AAITreeNode createVfModule(int uniqueNumber, boolean hasCustomizationName) { + AAITreeNode vfModuleTreeNode = new AAITreeNode(); + vfModuleTreeNode.setId("vfModule-instance-id"); + vfModuleTreeNode.setName("vfModule-instance-name"); + vfModuleTreeNode.setType("vf-module"); + vfModuleTreeNode.setModelVersionId("vfModule-model-version-id"); + if (hasCustomizationName) { + vfModuleTreeNode.setModelCustomizationName("vfModule model customization name"); + vfModuleTreeNode.setKeyInModel("vfModule key in model"); + } + vfModuleTreeNode.setUniqueNumber(uniqueNumber); + + return vfModuleTreeNode; + } + + private AAITreeNode createNetwork(int uniqueNumber, boolean hasCustomizationName) { + AAITreeNode networkTreeNode = new AAITreeNode(); + networkTreeNode.setId("network-instance-id"); + networkTreeNode.setName("network-instance-name"); + networkTreeNode.setType("l3-network"); + networkTreeNode.setModelVersionId("network-model-version-id"); + if (hasCustomizationName) { + networkTreeNode.setModelCustomizationName("network model customization name"); + networkTreeNode.setKeyInModel("network key in model"); + } + networkTreeNode.setUniqueNumber(uniqueNumber); + + return networkTreeNode; + } + + private void assertService(ServiceInstance serviceInstance, int expectedVnfs, int expectedNetworks, boolean isALaCarte) { + assertThat(serviceInstance.getInstanceId(), is("service-instance-id")); + assertThat(serviceInstance.getInstanceName(), is("service-instance-name")); + assertThat(serviceInstance.getAction(), is(Action.None)); + assertThat(serviceInstance.getGlobalSubscriberId(), is("global-customer-id")); + assertThat(serviceInstance.getSubscriptionServiceType(), is("service-type")); + assertThat(serviceInstance.getModelInfo().getModelType(), is("service")); + assertThat(serviceInstance.getVnfs().entrySet(), hasSize(expectedVnfs)); + assertThat(serviceInstance.getNetworks().entrySet(), hasSize(expectedNetworks)); + assertThat(serviceInstance.getIsALaCarte(), is(isALaCarte)); + } + + private void assertVnf(Vnf actualVnf, int expectedVfModules, int expectedNetworks, boolean hasCustomizationName) { + assertThat(actualVnf.getInstanceId(), is("vnf-instance-id")); + assertThat(actualVnf.getInstanceName(), is("vnf-instance-name")); + assertThat(actualVnf.getAction(), is(Action.None)); + assertThat(actualVnf.getModelInfo().getModelType(), is("vnf")); + assertThat(actualVnf.getModelInfo().getModelVersionId(), is("vnf-model-version-id")); + assertThat(actualVnf.getVfModules().entrySet(), hasSize(expectedVfModules)); + assertThat(actualVnf.getNetworks().entrySet(), hasSize(expectedNetworks)); + assertThat(actualVnf.getTrackById(), is(not(emptyOrNullString()))); + String expectedCustomizationName = hasCustomizationName ? "vnf model customization name" : null; + assertThat(actualVnf.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName)); + } + + private void assertVfModule(VfModule actualVfModule, boolean hasCustomizationName) { + assertThat(actualVfModule.getInstanceId(), is("vfModule-instance-id")); + assertThat(actualVfModule.getInstanceName(), is("vfModule-instance-name")); + assertThat(actualVfModule.getAction(), is(Action.None)); + assertThat(actualVfModule.getModelInfo().getModelType(), is("vfModule")); + assertThat(actualVfModule.getModelInfo().getModelVersionId(), is("vfModule-model-version-id")); + assertThat(actualVfModule.getTrackById(), is(not(emptyOrNullString()))); + String expectedCustomizationName = hasCustomizationName ? "vfModule model customization name" : null; + assertThat(actualVfModule.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName)); + } + + private void assertNetwork(Network actualNetwork, boolean hasCustomizationName) { + assertThat(actualNetwork.getInstanceId(), is("network-instance-id")); + assertThat(actualNetwork.getInstanceName(), is("network-instance-name")); + assertThat(actualNetwork.getAction(), is(Action.None)); + assertThat(actualNetwork.getModelInfo().getModelType(), is("network")); + assertThat(actualNetwork.getModelInfo().getModelVersionId(), is("network-model-version-id")); + assertThat(actualNetwork.getTrackById(), is(not(emptyOrNullString()))); + String expectedCustomizationName = hasCustomizationName ? "network model customization name" : null; + assertThat(actualNetwork.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName)); + } + + private AAITreeNode generateAaiTreeToConvert(int numberOfVnfs, int numberOfNetworks) { + int counter = 0; + AAITreeNode aaiTree = new AAITreeNode(); + aaiTree.setId("service-instance-id"); + aaiTree.setName("service-instance-name"); + + for (int i = 0; i < numberOfVnfs; i++) { + aaiTree.getChildren().add(createVnf(counter++, false)); + } + + for (int i = 0; i < numberOfNetworks; i++) { + aaiTree.getChildren().add(createNetwork(counter++, false)); + } + + return aaiTree; + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java new file mode 100644 index 00000000..5eac5f92 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java @@ -0,0 +1,131 @@ +package org.onap.vid.services; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.model.aaiTree.AAITreeNode; +import org.onap.vid.utils.Unchecked; +import org.testng.Assert; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicInteger; + +import static java.util.Comparator.comparing; +import static org.mockito.Mockito.when; +import static org.onap.vid.services.AAIServiceTree.AAI_TREE_PATHS; + +public class AAITreeNodeBuilderTest { + + AAITreeNodeBuilder aaiTreeNodeBuilder; + + @Mock + AaiClientInterface aaiClientMock; + + @Mock + ThreadPoolExecutor threadPoolMock; + + + @BeforeTest + public void initMocks() { + MockitoAnnotations.initMocks(this); + aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClientMock); + } + + @Test + public void buildNode_buildGroupNode_NodeIsAsExpected(){ + ConcurrentSkipListSet nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + ConcurrentLinkedQueue visitedNodes = new ConcurrentLinkedQueue<>(); + when(aaiClientMock.typedAaiGet(Unchecked.toURI("anyUrl"), JsonNode.class)).thenReturn(createGroupJson()); + + AAITreeNode groupNode = aaiTreeNodeBuilder.buildNode("instance-group", + "anyUrl", + nodesAccumulator, + threadPoolMock, + visitedNodes, + new AtomicInteger(0), + AAI_TREE_PATHS).get(0); + + AAITreeNode expectedGroupNode = createExpectedGroupNode(); + assertNodeIsAsExpected(expectedGroupNode,groupNode); + } + + private void assertNodeIsAsExpected(AAITreeNode expectedGroupNode, AAITreeNode groupNode) { + Assert.assertEquals(groupNode.getId(), expectedGroupNode.getId()); + Assert.assertEquals(groupNode.getType(), expectedGroupNode.getType()); + Assert.assertEquals(groupNode.getName(), expectedGroupNode.getName()); + Assert.assertEquals(groupNode.getModelVersionId(), expectedGroupNode.getModelVersionId()); + Assert.assertEquals(groupNode.getModelInvariantId(), expectedGroupNode.getModelInvariantId()); + Assert.assertEquals(groupNode.getInMaint(), expectedGroupNode.getInMaint()); + Assert.assertEquals(groupNode.getAdditionalProperties(), expectedGroupNode.getAdditionalProperties()); + } + + private AAITreeNode createExpectedGroupNode() { + AAITreeNode expectedNode = new AAITreeNode(); + expectedNode.setId("c4fcf022-31a0-470a-b5b8-c18335b7af32"); + expectedNode.setType("instance-group"); + expectedNode.setName("Test vE-Flex"); + expectedNode.setModelVersionId("Test vE-Flex"); + expectedNode.setModelInvariantId("dd182d7d-6949-4b90-b3cc-5befe400742e"); + expectedNode.setInMaint(false); + HashMap additionalProperties = new HashMap<>(); + additionalProperties.put("inMaint","false"); + additionalProperties.put("description","Test vE-Flex instance-group"); + additionalProperties.put("instance-group-type","ha"); + additionalProperties.put("instance-group-role","test-IG-role"); + additionalProperties.put("resource-version","1533315433086"); + additionalProperties.put("instance-group-function","vTSBC Customer Landing Network Collection"); + expectedNode.setAdditionalProperties(additionalProperties); + + + return expectedNode; + } + + private JsonNode createGroupJson() { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode groupNode = null; + try { + groupNode = objectMapper.readTree("" + + "{" + + " \"id\": \"c4fcf022-31a0-470a-b5b8-c18335b7af32\"," + + " \"instance-group-role\": \"test-IG-role\"," + + " \"description\": \"Test vE-Flex instance-group\"," + + " \"instance-group-type\": \"ha\"," + + " \"resource-version\": \"1533315433086\"," + + " \"instance-group-name\": \"Test vE-Flex\"," + + " \"model-invariant-id\": \"dd182d7d-6949-4b90-b3cc-5befe400742e\"," + + " \"model-version-id\": \"Test vE-Flex\"," + + " \"inMaint\": \"false\"," + + " \"instance-group-function\": \"vTSBC Customer Landing Network Collection\"," + + " \"relationship-list\": {" + + " \"relationship\": [{" + + " \"related-to\": \"generic-vnf\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.MemberOf\" ," + + " \"related-link\": \"/aai/v14/network/generic-vnfs/generic-vnf/8c54c369-2876-4423-9b33-80f783f29082\" ," + + " \"relationship-data\": [{" + + " \"relationship-key\": \"generic-vnf.vnf-id\"," + + " \"relationship-value\": \"8c54c369-2876-4423-9b33-80f783f29082\"" + + " }" + + " ]," + + " \"related-to-property\": [{" + + " \"property-key\": \"generic-vnf.vnf-name\"," + + " \"property-value\": \"zrdm5bffad01\"" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + " }"); + } catch (IOException e) { + e.printStackTrace(); + } + return groupNode; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java index 04890e33..841ea10a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java @@ -1,7 +1,7 @@ package org.onap.vid.services; -import org.codehaus.jackson.JsonNode; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.onap.vid.aai.AaiResponseTranslator; import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; @@ -13,7 +13,6 @@ import java.io.IOException; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; -@Test public class AaiResponseTranslatorTest { private static final ObjectMapper objectMapper = new ObjectMapper(); diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java index 5ead3fce..ed8d91fe 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java @@ -1,52 +1,25 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. 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.vid.services; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import io.joshworks.restclient.http.HttpResponse; -import jersey.repackaged.com.google.common.collect.ImmutableList; -import org.apache.http.HttpStatus; -import org.apache.http.HttpVersion; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.DefaultHttpResponseFactory; -import org.apache.http.message.BasicStatusLine; -import org.onap.vid.aai.AaiOverTLSClientInterface; -import org.onap.vid.aai.AaiResponse; -import org.onap.vid.aai.model.AaiNodeQueryResponse; -import org.onap.vid.aai.model.ResourceType; -import org.onap.vid.domain.mso.ModelInfo; -import org.onap.vid.domain.mso.RequestStatus; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.model.serviceInstantiation.VfModule; -import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.model.Action; +import org.onap.vid.model.serviceInstantiation.*; import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.mso.rest.RequestStatus; +import org.onap.vid.utils.TimeUtils; +import org.springframework.http.HttpMethod; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.togglz.core.manager.FeatureManager; import javax.inject.Inject; -import java.io.UnsupportedEncodingException; +import java.time.ZonedDateTime; import java.util.*; +import static java.util.Collections.emptyMap; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -65,6 +38,14 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests public static final String TENANT_NAME = "USP-SIP-IC-24335-T-01"; public static final String AIC_ZONE_ID = "NFT1"; public static final String AIC_ZONE_NAME = "NFTJSSSS-NFT1"; + public static final String TEST_API = "GR_API"; + public static final String SERVICE_MODEL_VERSION_ID = "3c40d244-808e-42ca-b09a-256d83d19d0a"; + public static final String VF_MODULE_0_MODEL_CUSTOMIZATION_NAME = "a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f"; + public static final String VF_MODULE_1_MODEL_CUSTOMIZATION_NAME = "72d9d1cd-f46d-447a-abdb-451d6fb05fa8"; + public static final String VF_MODULE_0_MODEL_VERSION_ID = "4c75f813-fa91-45a4-89d0-790ff5f1ae79"; + public static final String VF_MODULE_1_MODEL_VERSION_ID = "56e2b103-637c-4d1a-adc8-3a7f4a6c3240"; + public static final String VNF_NAME = "vmxnjr001"; + public static final String VNF_GROUP_NAME = "VNF_GROUP_NAME"; protected HashMap instanceParamsMapWithoutParams; protected HashMap vfModuleInstanceParamsMapWithParamsToRemove; @@ -74,34 +55,53 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests protected FeatureManager featureManager; @Inject - protected AaiOverTLSClientInterface aaiClient; + protected AaiClientInterface aaiClient; + + @Inject + protected CloudOwnerService cloudOwnerService; + + public ServiceInstantiation generateMockMacroServiceInstantiationPayload(boolean isPause, Map vnfs, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure) { + return generateMockServiceInstantiationPayload(isPause, vnfs, Collections.EMPTY_MAP, Collections.EMPTY_MAP, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, false, null, Action.Create, null); + } - public ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map vnfs, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure) { + public ServiceInstantiation generateMockALaCarteServiceInstantiationPayload(boolean isPause, Map vnfs, Map networks, Map vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi) { + return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, true, testApi, Action.Create, null); + } + + public ServiceInstantiation generateMockALaCarteServiceDeletionPayload(boolean isPause, Map vnfs, Map networks, Map vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi, String instanceId) { + return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, true, testApi, Action.Delete, instanceId); + } + private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map vnfs, Map networks, Map vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, boolean isAlacarte, String testApi, Action action, String instanceId) { ModelInfo modelInfo = createModelInfo(); List> instanceParams = createInstanceParams(); - return new ServiceInstantiation ( - modelInfo, + return new ServiceInstantiation ( modelInfo, AsyncInstantiationBusinessLogicTest.OWNING_ENTITY_ID, AsyncInstantiationBusinessLogicTest.PACKET_CORE, projectName, AsyncInstantiationBusinessLogicTest.SUBSCRIBER_ID, AsyncInstantiationBusinessLogicTest.SUBSCRIBER_NAME, AsyncInstantiationBusinessLogicTest.PRODUCT_FAMILY_ID, - isUserProvidedNaming ? AsyncInstantiationBusinessLogicTest.INSTANCE_NAME : "" , - isUserProvidedNaming, + isUserProvidedNaming ? AsyncInstantiationBusinessLogicTest.INSTANCE_NAME : null, AsyncInstantiationBusinessLogicTest.SUBSCRIPTION_SERVICE_TYPE, AsyncInstantiationBusinessLogicTest.LCP_CLOUD_REGION_ID, + null, AsyncInstantiationBusinessLogicTest.A6CA3EE0394ADE9403F075DB23167E, AsyncInstantiationBusinessLogicTest.TENANT_NAME, AsyncInstantiationBusinessLogicTest.AIC_ZONE_ID, AsyncInstantiationBusinessLogicTest.AIC_ZONE_NAME, vnfs, + networks, + vnfGroups, instanceParams, isPause, bulkSize, - rollbackOnFailure + rollbackOnFailure, + isAlacarte, + testApi, + instanceId, + action.name() ); } @@ -114,30 +114,58 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests return instanceParams; } - private VfModule createVfModule(String modelName, String modelVersionId, String modelCustomizationId, - List> instanceParams, String instanceName, String volumeGroupInstanceName) { + protected VfModule createVfModule(String modelName, String modelVersionId, String modelCustomizationId, + List> instanceParams, Map supplementaryParams, String instanceName, String volumeGroupInstanceName, boolean isAlacarte) { ModelInfo vfModuleInfo = new ModelInfo(); vfModuleInfo.setModelType("vfModule"); vfModuleInfo.setModelName(modelName); vfModuleInfo.setModelVersionId(modelVersionId); vfModuleInfo.setModelCustomizationId(modelCustomizationId); - return new VfModule(vfModuleInfo , instanceName, volumeGroupInstanceName, instanceParams); + vfModuleInfo.setModelCustomizationName(modelName); + + if (isAlacarte) { + vfModuleInfo.setModelInvariantId("22222222-f63c-463e-ba94-286933b895f9"); + vfModuleInfo.setModelVersion("10.0"); + return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false, true, null); + } + + return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), null, null, null, instanceParams, supplementaryParams, false, false, null); } - private ModelInfo createVnfModelInfo() { + protected ModelInfo createVnfModelInfo(boolean isAlacarte) { ModelInfo vnfModelInfo = new ModelInfo(); vnfModelInfo.setModelType("vnf"); vnfModelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L"); vnfModelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8"); vnfModelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0"); vnfModelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04"); + //added two conditional fields according to MSO AID - needed only in alacarte + if (isAlacarte) { + vnfModelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9"); + vnfModelInfo.setModelVersion("10.0"); + } + return vnfModelInfo; + } + + private ModelInfo createNetworkModelInfo(boolean isAlacarte) { + ModelInfo vnfModelInfo = new ModelInfo(); + vnfModelInfo.setModelType("network"); + vnfModelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L"); + vnfModelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8"); + vnfModelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0"); + vnfModelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04"); + //added two conditional fields according to MSO AID - needed only in alacarte + if (isAlacarte) { + vnfModelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9"); + vnfModelInfo.setModelVersion("10.0"); + } return vnfModelInfo; } private ModelInfo createModelInfo() { ModelInfo modelInfo = new ModelInfo(); modelInfo.setModelType("service"); - modelInfo.setModelVersionId("3c40d244-808e-42ca-b09a-256d83d19d0a"); + modelInfo.setModelVersionId(SERVICE_MODEL_VERSION_ID); modelInfo.setModelVersion("10.0"); modelInfo.setModelInvariantId("5d48acb5-097d-4982-aeb2-f4a3bd87d31b"); modelInfo.setModelName("MOW AVPN vMX BV vPE 1 Service"); @@ -145,29 +173,68 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests } protected Map createVnfList(HashMap vfModuleInstanceParamsMap, List vnfInstanceParams, boolean isUserProvidedNaming) { + return createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, isUserProvidedNaming, false); + } + + protected Map createVnfList(HashMap vfModuleInstanceParamsMap, List vnfInstanceParams, boolean isUserProvidedNaming, boolean isAlacarte) { Map vnfs = new HashMap<>(); - ModelInfo vnfModelInfo = createVnfModelInfo(); + ModelInfo vnfModelInfo = createVnfModelInfo(isAlacarte); Map> vfModules = new HashMap<>(); - List> instanceParams1 =ImmutableList.of((ImmutableMap.of("vmx_int_net_len", "24"))); - VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", "4c75f813-fa91-45a4-89d0-790ff5f1ae79", "a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f", instanceParams1, "vmxnjr001_AVPN_base_vPE_BV_base", null); + List> instanceParams1 = ImmutableList.of((ImmutableMap.of("vmx_int_net_len", "24"))); + VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME, instanceParams1, new HashMap<>(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vPE_BV_base" : null), null, isAlacarte); List> instanceParams2 = ImmutableList.of(vfModuleInstanceParamsMap); - VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams2, "vmxnjr001_AVPN_base_vRE_BV_expansion", "myVgName"); + VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", VF_MODULE_1_MODEL_VERSION_ID, VF_MODULE_1_MODEL_CUSTOMIZATION_NAME, instanceParams2, new HashMap<>(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), (isUserProvidedNaming ? "myVgName" : null), isAlacarte); String vfModuleModelName = vfModule1.getModelInfo().getModelName(); vfModules.put(vfModuleModelName, new LinkedHashMap<>()); - vfModules.get(vfModuleModelName).put(vfModule1.getInstanceName(),vfModule1); - vfModules.get(vfModuleModelName).put(vfModule2.getInstanceName(), vfModule2); + vfModules.get(vfModuleModelName).put(vfModuleModelName + ":001", vfModule1); + vfModules.get(vfModuleModelName).put(vfModuleModelName + ":002", vfModule2); - Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", "vmxnjr001", isUserProvidedNaming, - "platformName", "mdt1", "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" ,vfModules); + Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", (isUserProvidedNaming ? VNF_NAME : null), Action.Create.name(), + "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null, vfModules); - vnfs.put(vnf.getInstanceName(), vnf); + vnfs.put(vnf.getModelInfo().getModelName(), vnf); return vnfs; } + protected Map createNetworkList(List vnfInstanceParams, boolean isUserProvidedNaming, boolean isALaCarte) { + Map networks = new HashMap<>(); + ModelInfo networkModelInfo = createNetworkModelInfo(isALaCarte); + + Network network = new Network(networkModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", isUserProvidedNaming ? VNF_NAME : null, Action.Create.name(), + "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null); + + networks.put(network.getModelInfo().getModelName(), network); + return networks; + } + + protected InstanceGroup createInstanceGroup(boolean isUserProvidedNaming, Action action) { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType("instanceGroup"); + modelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L"); + modelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8"); + modelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0"); + modelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04"); + modelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9"); + modelInfo.setModelVersion("10.0"); + + return new InstanceGroup(modelInfo, (isUserProvidedNaming ? VNF_GROUP_NAME : null), action.name(), false, null); + } + + protected ModelInfo createServiceModelInfo() { + ModelInfo siModelInfo = new ModelInfo(); + siModelInfo.setModelName("sriov"); + siModelInfo.setModelType("service"); + siModelInfo.setModelInvariantId("ff3514e3-5a33-55df-13ab-12abad84e7ff"); + siModelInfo.setModelVersionId("fe6985cd-ea33-3346-ac12-ab121484a3fe"); + siModelInfo.setModelVersion("1.0"); + + return siModelInfo; + } + protected void createInstanceParamsMaps() { instanceParamsMapWithoutParams = new HashMap<>(); instanceParamsMapWithoutParams.put("availability_zone_0" , "mtpocdv-kvm-az01"); @@ -182,10 +249,11 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests vnfInstanceParamsMapWithParamsToRemove.put(AsyncInstantiationBusinessLogic.PARAMS_TO_IGNORE.get(1), "should be removed"); } - protected AsyncRequestStatus asyncRequestStatusResponse(String msoStatus) { + public static AsyncRequestStatus asyncRequestStatusResponse(String msoStatus) { AsyncRequestStatus asyncRequestStatus = new AsyncRequestStatus(new AsyncRequestStatus.Request(new RequestStatus())); asyncRequestStatus.request.requestStatus.setRequestState(msoStatus); asyncRequestStatus.request.requestId = UUID.randomUUID().toString(); + asyncRequestStatus.request.startTime = TimeUtils.zonedDateTimeToString(ZonedDateTime.now()); return asyncRequestStatus; } @@ -200,23 +268,31 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests return restObject; } - protected void mockAaiClientAnyNameFree() throws UnsupportedEncodingException { - when(aaiClient.searchNodeTypeByName(any(), any())).thenReturn(aaiNodeQueryResponseNameFree()); + protected void mockAaiClientAnyNameFree() { + when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(false); } - protected HttpResponse aaiNodeQueryResponseNameFree() throws UnsupportedEncodingException { - org.apache.http.HttpResponse response = new DefaultHttpResponseFactory().newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null); - response.setEntity(new StringEntity("")); - - return HttpResponse.fallback(new AaiNodeQueryResponse(null)); + protected ExceptionWithRequestInfo aaiNodeQueryBadResponseException() { + return new ExceptionWithRequestInfo(HttpMethod.GET, "url", "raw data", 500, null); } - protected AaiResponse aaiNodeQueryBadResponse() { - return new AaiResponse<>(null,"", 404); + protected ServiceInstantiation generateALaCarteWithVnfsServiceInstantiationPayload() { + Map vnfs = createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove) , true); + ServiceInstantiation serviceInstantiation = generateMockALaCarteServiceInstantiationPayload(false, vnfs, emptyMap(), emptyMap(), 1, true, PROJECT_NAME, false, "VNF_API"); + return serviceInstantiation; } - protected AaiResponse aaiNodeQueryResponseNameUsed(ResourceType type) { - AaiNodeQueryResponse mockAaiNodeQuery = new AaiNodeQueryResponse(ImmutableList.of(new AaiNodeQueryResponse.ResultData(type, "/some/mocked/link"))); - return new AaiResponse<>(mockAaiNodeQuery,"", 200); + protected ServiceInstantiation generateALaCarteUpdateWith1ExistingGroup2NewGroupsPayload() { + final InstanceGroup instanceGroup1 = createInstanceGroup(true, Action.None); + final InstanceGroup instanceGroup2 = createInstanceGroup(false, Action.Create); + final InstanceGroup instanceGroup3 = createInstanceGroup(true, Action.Create); + Map groups = ImmutableMap.of( + "foo:001", instanceGroup1, + "foo:002", instanceGroup2, + "foo:003", instanceGroup3 + ); + return generateMockServiceInstantiationPayload(false, emptyMap(), emptyMap(), groups, + 1, true, PROJECT_NAME, false, true, "VNF_API", + Action.None, "1234567890"); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java index 9711fa85..96b39bcb 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java @@ -1,29 +1,96 @@ package org.onap.vid.services; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import net.javacrumbs.jsonunit.JsonAssert; +import org.apache.commons.io.IOUtils; +import org.hibernate.SessionFactory; +import org.json.JSONException; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.stubbing.Answer; +import org.onap.portalsdk.core.domain.FusionObject; +import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.config.DataSourceConfig; import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.MaxRetriesException; +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.impl.JobDaoImpl; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.model.JobAuditStatus.SourceStatus; +import org.onap.vid.model.NameCounter; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.*; +import org.onap.vid.mso.MsoOperationalEnvironmentTest; +import org.onap.vid.mso.model.*; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.properties.Features; +import org.onap.vid.testUtils.TestUtils; +import org.onap.vid.utils.DaoUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; +import org.testng.Assert; +import org.testng.annotations.*; + +import javax.inject.Inject; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Optional; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static com.google.common.collect.Maps.newHashMap; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.core.Every.everyItem; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; +import static org.onap.vid.job.Job.JobStatus.*; +import static org.testng.Assert.*; @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class}) public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest { -/* -TO BE FIXED + @Inject private DataAccessService dataAccessService; @Mock - private JobAdapter jobAdapter; + private JobAdapter jobAdapterMock; @Mock - private JobsBrokerService jobsBrokerService; - + private JobsBrokerService jobsBrokerServiceMock; @Autowired private SessionFactory sessionFactory; - private AsyncInstantiationBusinessLogic asyncInstantiationBL; + private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL; private int serviceCount = 0; @@ -36,13 +103,27 @@ TO BE FIXED @BeforeClass void initServicesInfoService() { MockitoAnnotations.initMocks(this); - asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient); + asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService); createInstanceParamsMaps(); } @BeforeMethod void defineMocks() { + Mockito.reset(aaiClient); + Mockito.reset(jobAdapterMock); + Mockito.reset(jobsBrokerServiceMock); mockAaiClientAnyNameFree(); + enableAddCloudOwnerOnMsoRequest(); + } + + private void enableAddCloudOwnerOnMsoRequest() { + enableAddCloudOwnerOnMsoRequest(true); + } + + private void enableAddCloudOwnerOnMsoRequest(boolean isActive) { + // always turn on the feature flag + when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isActive); + when(aaiClient.getCloudOwnerByCloudRegionId(anyString())).thenReturn("att-aic"); } @BeforeMethod @@ -187,7 +268,7 @@ TO BE FIXED dataAccessService.saveDomainObject(jobDao, getPropsMap()); } - @Test + @Test(enabled = false) public void testServiceInfoAreOrderedAsExpected() { int userId = 2222; createNewTestServicesInfo(String.valueOf(userId)); @@ -196,7 +277,7 @@ TO BE FIXED assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo)); } - @Test + @Test(enabled = false) public void testServiceInfoAreFilteredAsExpected() { int userId = 2222; createNewTestServicesInfoForFilter(String.valueOf(userId)); @@ -212,29 +293,32 @@ TO BE FIXED assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser)); } - @Test(dataProvider = "pauseAndInstanceParams", enabled = false) //Test is irrelevant with unique names feature - public void createServiceInstantiationMsoRequest(Boolean isPause, HashMap vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception { - ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true)); - final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request.json"); - RequestDetailsWrapper result = - asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); - String expected = IOUtils.toString(resource, "UTF-8"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @Test(dataProvider = "pauseAndInstanceParams") - public void createServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception { - Mockito.reset(aaiClient); - mockAaiClientAnyNameFree(); - ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true)); + @Test(enabled = false, dataProvider = "pauseAndInstanceParams") + public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception { + defineMocks(); + ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true), 2, true, PROJECT_NAME, false); final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json"); - List uuids = new ArrayList<>(); + when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> { + Object[] args = invocation.getArguments(); + return new MockedJob((String)args[4]); + }); + + when(jobsBrokerServiceMock.add(any(MockedJob.class))).thenAnswer((Answer) invocation -> { + Object[] args = invocation.getArguments(); + MockedJob job = (MockedJob) args[0]; + MockedJob.putJob(job.uuid, job); + return job.getUuid(); + }); + + when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true); + + List uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016"); for (int i = 0; i < 2; i++) { - UUID currentUuid = createJobAndServiceInfo(); - uuids.add(currentUuid); + UUID currentUuid = uuids.get(i); RequestDetailsWrapper result = - asyncInstantiationBL.generateServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, "az2016"); - String unique = String.format("00%s", i + 1); + asyncInstantiationBL.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, + MockedJob.getJob(currentUuid).getOptimisticUniqueServiceInstanceName(), "az2016"); + String unique = i==0 ? "" : String.format("_00%s", i); String expected = IOUtils.toString(resource, "UTF-8") .replace("{SERVICE_UNIQENESS}", unique) .replace("{VNF_UNIQENESS}", unique) @@ -243,17 +327,17 @@ TO BE FIXED .replace("{VG_UNIQUENESS}", unique); MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); Optional optionalServiceInfo = getJobById(currentUuid); - assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service_" + unique)); - verifySearchNodeTypeByName(unique, "vPE_Service_", ResourceType.SERVICE_INSTANCE); - verifySearchNodeTypeByName(unique, "vmxnjr001_", ResourceType.GENERIC_VNF); - verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base_", ResourceType.VF_MODULE); - verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion_", ResourceType.VF_MODULE); - verifySearchNodeTypeByName(unique, "myVgName_", ResourceType.VOLUME_GROUP); + assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service" + unique)); + verifySearchNodeTypeByName(unique, "vPE_Service", ResourceType.SERVICE_INSTANCE); + verifySearchNodeTypeByName(unique, VNF_NAME, ResourceType.GENERIC_VNF); + verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base", ResourceType.VF_MODULE); + verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion", ResourceType.VF_MODULE); + verifySearchNodeTypeByName(unique, "myVgName", ResourceType.VOLUME_GROUP); } } protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) { - verify(aaiClient, times(1)).searchNodeTypeByName(resourceName + unique, serviceInstance); + verify(aaiClient, times(1)).isNodeTypeExistsByName(resourceName + unique, serviceInstance); } private HashMap getPropsMap() { @@ -262,40 +346,37 @@ TO BE FIXED return props; } - @Test(enabled = false) //probably not needed with name uniqueness feature - public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected() { + + @DataProvider + public static Object[][] dataProviderForInstanceNames() { + return new Object[][]{ + {true, ImmutableList.of("vPE_Service", "vPE_Service_001", "vPE_Service_002")}, + {false, ImmutableList.of("", "", "")}, + }; + } + + @Test(enabled = false, dataProvider="dataProviderForInstanceNames") + public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List expectedNames) { int bulkSize = 3; - final ServiceInstantiation request = generateMockServiceInstantiationPayload( + final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload( false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), - bulkSize, true,PROJECT_NAME, true + bulkSize, isUserProvidedNaming, PROJECT_NAME, true ); - // in "createJob()" we will probe the service, with the generated names - final Job job = mock(Job.class); - when(job.getStatus()).thenReturn(PENDING); - when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job); - - - final List uuids = asyncInstantiationBL.pushBulkJob(request, "myUserId"); - + // in "createServiceInstantiationJob()" we will probe the service, with the generated names + configureMockitoWithMockedJob(); - ArgumentCaptor serviceInstantiationCaptor = new ArgumentCaptor(); - verify(jobAdapter, times(bulkSize)).createJob(any(), serviceInstantiationCaptor.capture(), any(), any(), any()); - assertThat(serviceInstantiationCaptor.getAllValues().stream().map(v -> v.getInstanceName()).collect(Collectors.toList()), - containsInAnyOrder("vPE_Service_001", "vPE_Service_002", "vPE_Service_003")); + asyncInstantiationBL.pushBulkJob(request, "myUserId"); - assertThat(uuids, hasSize(bulkSize)); + List serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); + assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames); } - @Test - public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame() throws IOException { - ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload( - false, - createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true), - 2, false,PROJECT_NAME, false); + @Test(enabled = false, dataProvider = "aLaCarteAndMacroPayload") + public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame(ServiceInstantiation serviceInstantiationPayload) throws IOException { ObjectMapper mapper = new ObjectMapper(); final String asString = mapper.writeValueAsString(serviceInstantiationPayload); @@ -305,6 +386,20 @@ TO BE FIXED JsonAssert.assertJsonEquals(asString, asString2); } + @DataProvider + public Object[][] aLaCarteAndMacroPayload() { + ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload( + false, + createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true), + 2, false,PROJECT_NAME, false); + ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload(); + + return new Object[][]{ + {macroPayload}, + {aLaCartePayload} + }; + } + public static class ServiceInfoComparator implements Comparator { @Override @@ -356,13 +451,13 @@ TO BE FIXED }; } - private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map vnfs) { - return generateMockServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false); + private ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map vnfs) { + return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false); } - @Test + @Test(enabled = false) public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() { - UUID uuid = createJobAndServiceInfo(); + UUID uuid = createFakedJobAndServiceInfo(); final String STEPH_CURRY = "Steph Curry"; asyncInstantiationBL.updateServiceInfo(uuid, x -> { x.setServiceInstanceName(STEPH_CURRY); @@ -378,7 +473,7 @@ TO BE FIXED return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst(); } - private UUID createJobAndServiceInfo() { + private UUID createFakedJobAndServiceInfo() { UUID uuid = UUID.randomUUID(); addNewJob(uuid); ServiceInfo serviceInfo = new ServiceInfo(); @@ -389,14 +484,14 @@ TO BE FIXED return uuid; } - @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) + @Test(enabled = false, expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) public void testUpdateServiceInfo_WithNonExisting_ThrowException() { asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter")); } - @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) + @Test(enabled = false, expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() { - UUID uuid = createJobAndServiceInfo(); + UUID uuid = createFakedJobAndServiceInfo(); ServiceInfo serviceInfo = new ServiceInfo(); serviceInfo.setJobId(uuid); dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); @@ -404,36 +499,45 @@ TO BE FIXED } + @DataProvider + public static Object[][] isPauseAndPropertyDataProvider() { + return new Object[][]{ + {true, "mso.restapi.serviceInstanceAssign"}, + {false, "mso.restapi.serviceInstanceCreate"}, + }; + } + - @Test - public void testRequestPath_WithPauseFlagTrue_RequestPathIsAsExpected() { - ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMockServiceInstantiationPayload(true, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true)); + @Test(enabled = false, dataProvider = "isPauseAndPropertyDataProvider") + public void testServiceInstantiationPath_RequestPathIsAsExpected(boolean isPause, String expectedProperty) { + ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMacroMockServiceInstantiationPayload(isPause, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true)); String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue); - Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceAssign")); + Assert.assertEquals(path, SystemProperties.getProperty(expectedProperty)); } - @Test - public void testRequestPath_WithPauseFlagFalse_RequestPathIsAsExpected() { - ServiceInstantiation serviceInstantiationPauseFlagFalse = generateMockServiceInstantiationPayload(false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true)); - String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagFalse); - Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceCreate")); + @Test(enabled = false) + public void testCreateVnfEndpoint_useProvidedInstanceId() { + String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId"); + assertThat(path, equalTo("/serviceInstances/v7/myGreatId/vnfs")); } - @Test + @Test(enabled = false) public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException { - createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true); + createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true); } - @Test + @Test(enabled = false) public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException { - createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false); + createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false); } - private void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException { - ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true, + private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException { + when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true); + + ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true, createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), 1, - false,PROJECT_NAME, true); + false, PROJECT_NAME, true); URL resource; if (withVfmodules) { resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json"); @@ -444,27 +548,183 @@ TO BE FIXED } RequestDetailsWrapper result = - asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); String expected = IOUtils.toString(resource, "UTF-8"); MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); } - @Test + @Test(enabled = false) + public void createALaCarteService_WithUserProvidedNamingFalse_RequestDetailsIsAsExpected() throws IOException { + ServiceInstantiation serviceInstantiationPayload = generateMockALaCarteServiceInstantiationPayload(false, + newHashMap(), + newHashMap(), + newHashMap(), + 1, + false, PROJECT_NAME, true, null); + + RequestDetailsWrapper result = + asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); + + URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request_naming_false.json"); + String expected = IOUtils.toString(resource, "UTF-8"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(enabled = false) + public void generateALaCarteServiceInstantiationRequest_withVnfList_HappyFllow() throws IOException { + ServiceInstantiation serviceInstantiationPayload = generateALaCarteWithVnfsServiceInstantiationPayload(); + RequestDetailsWrapper result = + asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); + + String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result); + } + + @Test(enabled = false, dataProvider = "createVnfParameters") + public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String file) throws IOException { + + final List vnfList = new ArrayList<>(createVnfList(new HashMap<>(), null, isUserProvidedNaming, true).values()); + ModelInfo siModelInfo = createServiceModelInfo(); + String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; + + //we validate that the asyncInstantiationBL call to getUniqueName by simulate that aai retrun that original + //vnf name is used, and only next picked name is free. + Mockito.reset(aaiClient); + mockAaiClientAaiStatusOK(); + when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.GENERIC_VNF))).thenReturn(true); + when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.GENERIC_VNF))).thenReturn(false); + enableAddCloudOwnerOnMsoRequest(isFlagAddCloudOwnerActive); + + String expected = IOUtils.toString(this.getClass().getResource(file), "UTF-8"); + final RequestDetailsWrapper result = asyncInstantiationBL.generateVnfInstantiationRequest(vnfList.get(0), siModelInfo, serviceInstanceId, "pa0916"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @DataProvider + public static Object[][] createVnfParameters() { + return new Object[][]{ + {true, true, "/payload_jsons/bulk_vnf_request.json"}, + {false, true, "/payload_jsons/bulk_vnf_request_without_cloud_owner.json"}, + {true, false, "/payload_jsons/bulk_vnf_request_without_instance_name.json"}, + }; + } + + @DataProvider + public static Object[][] vfModuleRequestDetails(Method test) { + return new Object[][]{ + {"cc3514e3-5a33-55df-13ab-12abad84e7cc", true, "/payload_jsons/vfmodule_instantiation_request.json"}, + {null, true, "/payload_jsons/vfmodule_instantiation_request_without_volume_group.json"}, + {null, false, "/payload_jsons/vfmodule_instantiation_request_without_instance_name.json"} + }; + } + + @Test(enabled = false, dataProvider = "vfModuleRequestDetails") + public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException { + + ModelInfo siModelInfo = createServiceModelInfo(); + ModelInfo vnfModelInfo = createVnfModelInfo(true); + List> instanceParams = ImmutableList.of(ImmutableMap.of("vmx_int_net_len", "24", + "vre_a_volume_size_0" , "120")); + Map supplementaryParams = ImmutableMap.of("vre_a_volume_size_0" , "100", + "availability_zone_0" , "mtpocdv-kvm-az01"); + VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", + "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams, supplementaryParams, + (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), "myVgName", true); + + String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; + String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb"; + + Mockito.reset(aaiClient); + mockAaiClientAaiStatusOK(); + enableAddCloudOwnerOnMsoRequest(); + when(aaiClient.isNodeTypeExistsByName(eq("vmxnjr001_AVPN_base_vRE_BV_expansion"), eq(ResourceType.VF_MODULE))).thenReturn(false); + + String expected = IOUtils.toString(this.getClass().getResource(fileName), "UTF-8"); + final RequestDetailsWrapper result = asyncInstantiationBL.generateVfModuleInstantiationRequest( + vfModule, siModelInfo, serviceInstanceId, + vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @DataProvider + public static Object[][] expectedAggregatedParams() { + return new Object[][]{ + {ImmutableMap.of("a", "b", "c", "d"), ImmutableMap.of("e", "f", "g", "h"), ImmutableList.of(ImmutableMap.of("c", "d", "a", "b", "e", "f", "g", "h"))}, + {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("a", "b", "c", "d", "e", "f"))}, + {ImmutableMap.of(), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("c", "d", "e", "f"))}, + {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of(), ImmutableList.of(ImmutableMap.of("a", "b", "c", "g"))}, + {ImmutableMap.of(), ImmutableMap.of(), ImmutableList.of()}, + {null, ImmutableMap.of(), ImmutableList.of()}, + {ImmutableMap.of(), null, ImmutableList.of()}, + }; + } + + @Test(enabled = false, dataProvider = "expectedAggregatedParams") + public void testAggregateInstanceParamsAndSuppFile(Map instanceParams, Map suppParams, List> expected) { + List> aggParams = ((AsyncInstantiationBusinessLogicImpl)asyncInstantiationBL).aggregateAllInstanceParams(instanceParams, suppParams); + assertThat("Aggregated params are not as expected", aggParams, equalTo(expected)); + } + + @DataProvider + public static Object[][] expectedNetworkRequestDetailsParameters() { + return new Object[][]{ + {true, "/payload_jsons/network_instantiation_request.json"}, + {false, "/payload_jsons/network_instantiation_request_without_instance_name.json"} + }; + } + + @Test(enabled = false, dataProvider = "expectedNetworkRequestDetailsParameters") + public void createNetworkRequestDetails_detailsAreAsExpected(boolean isUserProvidedNaming, String filePath) throws IOException { + + final List networksList = new ArrayList<>(createNetworkList(null, isUserProvidedNaming, true).values()); + ModelInfo siModelInfo = createServiceModelInfo(); + String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; + + Mockito.reset(aaiClient); + mockAaiClientAaiStatusOK(); + enableAddCloudOwnerOnMsoRequest(); + when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.L3_NETWORK))).thenReturn(true); + when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.L3_NETWORK))).thenReturn(false); + + String expected = IOUtils.toString(this.getClass().getResource(filePath), "UTF-8"); + final RequestDetailsWrapper result = asyncInstantiationBL.generateNetworkInstantiationRequest(networksList.get(0), siModelInfo, serviceInstanceId, "pa0916"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(enabled = false) + public void createInstanceGroupRequestDetails_detailsAreAsExpected() throws IOException { + + final InstanceGroup instanceGroup = createInstanceGroup(true, Action.Create); + ModelInfo siModelInfo = createServiceModelInfo(); + String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; + + Mockito.reset(aaiClient); + mockAaiClientAaiStatusOK(); + enableAddCloudOwnerOnMsoRequest(); + when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME), eq(ResourceType.INSTANCE_GROUP))).thenReturn(true); + when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME+"_001"), eq(ResourceType.INSTANCE_GROUP))).thenReturn(false); + + String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/instance_group_instantiation_request.json"), "UTF-8"); + final RequestDetailsWrapper result = asyncInstantiationBL.generateInstanceGroupInstantiationRequest(instanceGroup, siModelInfo, serviceInstanceId, "az2018"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(enabled = false) public void checkIfNullProjectNameSentToMso(){ - ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true, + ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true, createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), 1, false,null,false); RequestDetailsWrapper result = - asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails); Assert.assertTrue(jsonNode.get("project").isNull()); - serviceInstantiationPayload = generateMockServiceInstantiationPayload(true, + serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true, createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), 1, false,"not null",false); - result = asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + result = asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); jsonNode = new ObjectMapper().valueToTree(result.requestDetails); Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null")); @@ -472,19 +732,40 @@ TO BE FIXED } - @Test - public void pushBulkJob_verifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() { + @Test(enabled = false) + public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() { LocalDateTime startTestDate = LocalDateTime.now().withNano(0); - final ServiceInstantiation request = generateMockServiceInstantiationPayload( + final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload( false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), 100, true,PROJECT_NAME, true ); - // in "createJob()" we will probe the service, with the generated names - final Job job = mock(Job.class); - when(job.getStatus()).thenReturn(PENDING); - when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job); + pushJobAndAssertDates(startTestDate, request); + } + + @Test(enabled = false) + public void whenCreateServiceInfo_thenModelId_isModelVersionId() { + ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID", + generateALaCarteWithVnfsServiceInstantiationPayload(), + UUID.randomUUID(), + UUID.randomUUID(), + new Date(), + "myName", ServiceInfo.ServiceAction.INSTANTIATE); + assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId()); + + } + + @Test(enabled = false) + public void pushBulkJob_aLaCarteServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() { + LocalDateTime startTestDate = LocalDateTime.now().withNano(0); + final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload(); + pushJobAndAssertDates(startTestDate, request); + } + + protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) { + // in "createServiceInstantiationJob()" we will probe the service, with the generated names + configureMockitoWithMockedJob(); asyncInstantiationBL.pushBulkJob(request, "myUserId"); List serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); @@ -502,6 +783,13 @@ TO BE FIXED assertFalse(creationDate.isAfter(endTestDate)); } + protected void configureMockitoWithMockedJob() { + Mockito.reset(jobAdapterMock); + final Job job = mock(Job.class); + when(job.getStatus()).thenReturn(PENDING); + when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any())).thenReturn(job); + } + @DataProvider public static Object[][] msoToJobStatusDataProvider() { return new Object[][]{ @@ -519,8 +807,8 @@ TO BE FIXED }; } - @Test(dataProvider = "msoToJobStatusDataProvider") - void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) { + @Test(enabled = false, dataProvider = "msoToJobStatusDataProvider") + public void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) { AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus); assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus)); } @@ -564,7 +852,7 @@ TO BE FIXED } - @Test(dataProvider = "auditStatuses") + @Test(enabled = false, dataProvider = "auditStatuses") public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){ UUID jobUuid = UUID.randomUUID(); List auditStatusList = com.google.common.collect.ImmutableList.of( @@ -582,7 +870,7 @@ TO BE FIXED - @Test + @Test(enabled = false) public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){ ImmutableList statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED); UUID jobUuid = UUID.randomUUID(); @@ -627,7 +915,7 @@ TO BE FIXED }; } - @Test(dataProvider = "msoAuditStatuses") + @Test(enabled = false, dataProvider = "msoAuditStatuses") public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList msoStatuses, ImmutableList expectedStatuses, String assertionReason) { msoStatuses.forEach(status -> { asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo()); @@ -636,7 +924,7 @@ TO BE FIXED assertThat( assertionReason, statusesFromDB, is(expectedStatuses)); } - @Test + @Test(enabled = false) public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){ UUID jobUuid = UUID.randomUUID(); JobStatus sameStatus = IN_PROGRESS; @@ -650,45 +938,35 @@ TO BE FIXED assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString())))); } - @Test - public void verifyAsyncRequestStatus_canBeReadFromSample() throws IOException { - String body = "{" + - " \"request\": {" + - " \"requestId\": \"c0011670-0e1a-4b74-945d-8bf5aede1d9c\"," + - " \"startTime\": \"Mon, 11 Dec 2017 07:27:49 GMT\"," + - " \"requestScope\": \"service\"," + - " \"requestType\": \"createInstance\"," + - " \"instanceReferences\": {" + - " \"serviceInstanceId\": \"f8791436-8d55-4fde-b4d5-72dd2cf13cfb\"," + - " \"serviceInstanceName\": \"asdfasdf234234asdf\"," + - " \"requestorId\": \"il883e\"" + - " }," + - " \"requestStatus\": {" + - " \"requestState\": \"COMPLETE\"," + - " \"statusMessage\": \"Service Instance was created successfully.\"," + - " \"percentProgress\": 100," + - " \"finishTime\": \"Mon, 11 Dec 2017 07:27:53 GMT\"" + - " }" + - " }" + - "}"; - ObjectMapper objectMapper = new ObjectMapper(); - AsyncRequestStatus asyncRequestStatus = objectMapper.readValue(body, AsyncRequestStatus.class); - assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE")); + @DataProvider + public static Object[][] msoRequestStatusFiles(Method test) { + return new Object[][]{ + {"/responses/mso/orchestrationRequestsServiceInstance.json"}, + {"/responses/mso/orchestrationRequestsVnf.json"}, + {"/responses/mso/orchestrationRequestsMockedMinimalResponse.json"} + }; + } + @Test(enabled = false, dataProvider="msoRequestStatusFiles") + public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException { + AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject( + msoResponseFile, + AsyncRequestStatus.class); + assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE")); } - @Test + @Test(enabled = false) public void deleteJobInfo_pending_deleted() { - doNothing().when(jobsBrokerService).delete(any()); + doNothing().when(jobsBrokerServiceMock).delete(any()); UUID uuid = createServicesInfoWithDefaultValues(PENDING); asyncInstantiationBL.deleteJob(uuid); assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted"); } - @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE) + @Test(enabled = false, expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE) public void deleteJobInfo_notAllowdStatus_shouldSendError() { UUID uuid = createServicesInfoWithDefaultValues(COMPLETED); - doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerService).delete(any()); + doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerServiceMock).delete(any()); try { asyncInstantiationBL.deleteJob(uuid); } catch (Exception e) { @@ -704,7 +982,7 @@ TO BE FIXED .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); } - @Test(dataProvider = "jobStatusesFinal") + @Test(enabled = false, dataProvider = "jobStatusesFinal") public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) { UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus); UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus); @@ -729,7 +1007,7 @@ TO BE FIXED .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); } - @Test( dataProvider = "jobStatusesNotFinal", + @Test(enabled = false, dataProvider = "jobStatusesNotFinal", expectedExceptions = OperationNotAllowedException.class, expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*") public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) { @@ -742,14 +1020,14 @@ TO BE FIXED } } - @Test + @Test(enabled = false) public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException { int SIZE = 200; ExecutorService executor = Executors.newFixedThreadPool(SIZE); - List> tasks = IntStream.rangeClosed(1, SIZE) + List> tasks = IntStream.rangeClosed(0, SIZE) .mapToObj(x-> ((Callable)() -> asyncInstantiationBL.getCounterForName("a"))) .collect(Collectors.toList()); - Set expectedResults = IntStream.rangeClosed(1, SIZE).boxed().collect(Collectors.toSet()); + Set expectedResults = IntStream.rangeClosed(0, SIZE).boxed().collect(Collectors.toSet()); executor.invokeAll(tasks) .forEach(future -> { try { @@ -763,23 +1041,23 @@ TO BE FIXED assertThat(expectedResults.size(), is(0)); } - @Test + @Test(enabled = false) public void whenUseGetCounterForSameName_numbersReturnedByOrder() { String name = UUID.randomUUID().toString(); int SIZE=10; - for (int i=1; i<=SIZE; i++) { + for (int i=0; i argumentCaptor = ArgumentCaptor.forClass(JobType.class); + asyncInstantiationBL.pushBulkJob(request, "myUserId"); + verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt()); + assertTrue(argumentCaptor.getValue().equals(JobType.ALaCarteServiceInstantiation)); + } + + @Test(enabled = false) + public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){ + final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap()); + + // in "createServiceInstantiationJob()" we will probe the service, with the generated names + configureMockitoWithMockedJob(); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(JobType.class); + asyncInstantiationBL.pushBulkJob(request, "myUserId"); + verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt()); + assertTrue(argumentCaptor.getValue().equals(JobType.MacroServiceInstantiation)); + } + + @Test(enabled = false) + public void generateALaCarteServiceInstantiationRequest_verifyRequestIsAsExpected() throws IOException { + ServiceInstantiation serviceInstantiationPayload = generateALaCarteServiceInstantiationPayload(); + final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"); + RequestDetailsWrapper result = + asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); + String expected = IOUtils.toString(resource, "UTF-8"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(enabled = false) + public void generateALaCarteServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException { + final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_deletion_request.json"); + String expected = IOUtils.toString(resource, "UTF-8"); + + ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload(); + RequestDetailsWrapper result = + asyncInstantiationBL.generateALaCarteServiceDeletionRequest(null, serviceDeletionPayload, "az2016"); + + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(enabled = false) + public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() throws IOException { + + String expected = "/serviceInstantiation/v7/serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1"; + + String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1"); + + assertThat(expected,equalTo(result)); + } + + @Test(enabled = false) + public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected() { + + assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"), + "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b"); + } + + @DataProvider + public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) { + return new Object[][]{ + { + Collections.EMPTY_LIST, + ImmutableList.of( + ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), + ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")) + ), + true, + ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3")) + }, + { + ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), //vnf_name, vf_module_name are excluded + ImmutableList.of( + ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), + ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")), + ImmutableList.of(Collections.EMPTY_MAP), + Collections.singletonList(null) + ), + true, + ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3","j1", "w1")) + }, + { + Collections.EMPTY_LIST, + Arrays.asList(null, null), + true, + Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map + }, + { + ImmutableList.of(Collections.EMPTY_MAP), + ImmutableList.of( + ImmutableList.of(Collections.EMPTY_MAP), + ImmutableList.of(Collections.EMPTY_MAP) + ), + true, + Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map + }, + { + Collections.EMPTY_LIST, + ImmutableList.of( + ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), + ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")) + ), + false, + Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map + }, + { + ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), + ImmutableList.of( + ImmutableList.of(Collections.EMPTY_MAP) + ), + false, + ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1")) + }, + { + ImmutableList.of(ImmutableMap.of("vnf_name","w2", "vf_module_name", "w3", "j2", "w2", "j4","w4")), + ImmutableList.of( + ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), + ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")) + ), + false, + ImmutableList.of(ImmutableMap.of("j2", "w2", "j4","w4")) + }, + + }; + } + + @Test(enabled = false, dataProvider="testBuildVnfInstanceParamsDataProvider") + public void testBuildVnfInstanceParams(List> currentVnfInstanceParams, + List>> vfModulesInstanceParams, + boolean isFeatureActive, + List> expectedResult){ + when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(isFeatureActive); + List vfModules = + vfModulesInstanceParams.stream().map(params-> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList()); + List> actual = asyncInstantiationBL.buildVnfInstanceParams(currentVnfInstanceParams, vfModules); + assertThat(actual, equalTo(expectedResult)); + + } + + @Test(enabled = false) + public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() { + String legacyCloudRegion = "legacyCloudRegion"; + Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion, null, null, null, false, null, null); + assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion)); + + + } + + @Test(enabled = false) + public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() { + String legacyCloudRegion = "legacyCloudRegion"; + ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, + null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null, + false, 1,false, false, null, null, Action.Create.name()); + assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion)); + } + + @Test(enabled = false) + public void createVolumeGroup_verifyResultAsExpected() throws IOException { + final URL resource = this.getClass().getResource("/payload_jsons/volumegroup_instantiation_request.json"); + VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", + "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", + "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", + Collections.emptyList(), + Collections.emptyMap(), + "vmxnjr001_AVPN_base_vRE_BV_expansion", + "myVgName", + true); + vfModule.getModelInfo().setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff"); + vfModule.getModelInfo().setModelVersion("1"); + ModelInfo vnfModelInfo = createVnfModelInfo(true); + RequestDetailsWrapper result = + asyncInstantiationBL.generateVolumeGroupInstantiationRequest(vfModule, + createServiceModelInfo(), + "ff3514e3-5a33-55df-13ab-12abad84e7ff", + vnfModelInfo, + "vnfInstanceId", + "az2016"); + String expected = IOUtils.toString(resource, "UTF-8"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(enabled = false) + public void getJobTypeByRequest_verifyResultAsExpected(){ + ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + false, 1,false, false, null, null, Action.Create.name()); + JobType jobType = asyncInstantiationBL.getJobType(service) ; + assertThat(jobType, equalTo(JobType.MacroServiceInstantiation)); + service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + false, 1,false, true, null, null, Action.Create.name()); + jobType = asyncInstantiationBL.getJobType(service); + assertThat(jobType, equalTo(JobType.ALaCarteServiceInstantiation)); + service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, + false, 1,false, true, null, null, Action.Delete.name()); + jobType = asyncInstantiationBL.getJobType(service); + assertThat(jobType, equalTo(JobType.ALaCarteService)); + } + + protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() { + return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API"); + } + + private ServiceInstantiation generateALaCarteServiceDeletionPayload() { + return generateMockALaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890"); + } + + static class MockedJob implements Job { + + private static Map uuidToJob = new HashMap<>(); + + public static void putJob(UUID uuid, MockedJob job) { + uuidToJob.put(uuid, job); + } + + public static MockedJob getJob(UUID uuid) { + return uuidToJob.get(uuid); + } + + + private String optimisticUniqueServiceInstanceName; + + public MockedJob(String optimisticUniqueServiceInstanceName) { + this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName; + } + + private UUID uuid = UUID.randomUUID(); + + @Override + public UUID getUuid() { + return uuid; + } + + @Override + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + @Override + public JobStatus getStatus() { + return JobStatus.PENDING; + } + + @Override + public void setStatus(JobStatus status) { + + } + + @Override + public Map getData() { + return null; + } + + @Override + public JobSharedData getSharedData() { + return new JobSharedData(uuid, "", null); + } + + @Override + public void setTypeAndData(JobType jobType, Map commandData) { + + } + + @Override + public UUID getTemplateId() { + return null; + } + + @Override + public void setTemplateId(UUID templateId) { + + } + + @Override + public Integer getIndexInBulk() { + return null; + } + + @Override + public void setIndexInBulk(Integer indexInBulk) { + + } + + @Override + public JobType getType() { + return null; + } + + public String getOptimisticUniqueServiceInstanceName() { + return optimisticUniqueServiceInstanceName; + } + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java index 3d2a20b6..a1e027f8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java @@ -19,18 +19,28 @@ */ package org.onap.vid.services; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.util.UUID; import org.glassfish.grizzly.http.util.HttpStatus; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.mso.rest.AsyncRequestStatusList; +import org.onap.vid.testUtils.TestUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.io.IOException; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import static java.util.stream.Collectors.toList; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + public class AuditServiceImplTest { @Mock private AsyncInstantiationBusinessLogic asyncInstantiationBL; @@ -60,4 +70,20 @@ public class AuditServiceImplTest { Mockito.anyString(), Mockito.anyString()); } + + @Test + public void testConvertMsoResponseStatusToJobAuditStatus_missingDateFromMso_shouldNoError() throws IOException { + final AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject("/orchestrationRequestsByServiceInstanceId.json", AsyncRequestStatusList.class); + + AuditServiceImpl auditService = new AuditServiceImpl(null, null); + + final List jobAuditStatuses = auditService.convertMsoResponseStatusToJobAuditStatus(asyncRequestStatusList.getRequestList(), "foo"); + + final List dates = jobAuditStatuses.stream().map(JobAuditStatus::getCreatedDate).collect(toList()); + final List statuses = jobAuditStatuses.stream().map(JobAuditStatus::getJobStatus).collect(toList()); + + assertThat(dates, containsInAnyOrder(notNullValue(), notNullValue(), nullValue())); + assertThat(statuses, containsInAnyOrder("COMPLETE", "COMPLETE", "IN_PROGRESS")); + } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java index 6677da35..76963fac 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java @@ -19,17 +19,6 @@ */ package org.onap.vid.services; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import javax.ws.rs.NotFoundException; import org.mockito.InjectMocks; import org.mockito.Mock; import org.onap.vid.job.Job; @@ -43,6 +32,14 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; +import javax.ws.rs.NotFoundException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.initMocks; + public class BulkInstantiationServiceImplTest { @Mock @@ -65,23 +62,6 @@ public class BulkInstantiationServiceImplTest { reset(jobAdapter); } - @Test - public void saveBulkTest() { - UUID uuid = UUID.randomUUID(); - Map bulkRequest = new HashMap<>(); - List jobList = new ArrayList<>(); - jobList.add(createJob(uuid)); - when(jobAdapter.createBulkOfJobs(bulkRequest)).thenReturn(jobList); - - JobBulk jobBulk = createJobBulk(jobList); - when(jobAdapter.toModelBulk(jobList)).thenReturn(jobBulk); - - JobBulk result = testSubject.saveBulk(bulkRequest); - - Assert.assertEquals(result.getJobs().size(), jobList.size()); - Assert.assertEquals(result.getJobs().get(0).getUuid(), uuid); - } - @Test public void getJobTest() { UUID uuid = UUID.randomUUID(); diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java index 00d9e173..47411e2a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java @@ -15,7 +15,6 @@ import static org.mockito.Mockito.verify; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; -@Test public class ChangeManagementServiceImplTest { @Mock @@ -27,6 +26,9 @@ public class ChangeManagementServiceImplTest { @Mock SchedulerRestInterfaceIfc schedulerRestInterface; + @Mock + CloudOwnerService cloudOwnerService; + @BeforeMethod public void initMocks(){ MockitoAnnotations.initMocks(this); @@ -34,14 +36,14 @@ public class ChangeManagementServiceImplTest { @Test public void doChangeManagement_requestIsNull_returnsNull() throws Exception { - ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface); + ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface, cloudOwnerService); ResponseEntity result = changeManagementService.doChangeManagement(null,"anyString"); assertNull(result); } @Test public void doChangeManagement_currentRequestDetailsIsNull_returnsNull() throws Exception { - ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface); + ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface, cloudOwnerService); ChangeManagementServiceImpl changeManagementServiceSpied = Mockito.spy(changeManagementService); Mockito.doReturn(null).when(changeManagementServiceSpied).findRequestByVnfName(Matchers.anyList(),Mockito.anyString()); @@ -59,7 +61,7 @@ public class ChangeManagementServiceImplTest { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); verify(msoBusinessLogicMock).updateVnf(argumentCaptor.capture(),Mockito.any(),Mockito.any()); - assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId()); } @Test @@ -71,7 +73,7 @@ public class ChangeManagementServiceImplTest { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); verify(msoBusinessLogicMock).replaceVnf(argumentCaptor.capture(),Mockito.any(),Mockito.any()); - assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId()); } @Test @@ -83,7 +85,7 @@ public class ChangeManagementServiceImplTest { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); verify(msoBusinessLogicMock).updateVnfSoftware(argumentCaptor.capture(),Mockito.any(),Mockito.any()); - assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId()); } @Test @@ -95,11 +97,11 @@ public class ChangeManagementServiceImplTest { ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); verify(msoBusinessLogicMock).updateVnfConfig(argumentCaptor.capture(),Mockito.any(),Mockito.any()); - assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(), requestDetails.getVnfInstanceId()); } private RequestDetails callChangeManagement(String requestType) throws Exception { - ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface); + ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface, cloudOwnerService); ChangeManagementServiceImpl changeManagementServiceSpied = Mockito.spy(changeManagementService); ChangeManagementRequest updateRequest = new ChangeManagementRequest(); @@ -109,7 +111,7 @@ public class ChangeManagementServiceImplTest { Mockito.doReturn("fakeId").when(changeManagementServiceSpied).extractServiceInstanceId(Mockito.any(),Mockito.any()); Mockito.doReturn(requestDetails).when(changeManagementServiceSpied).findRequestByVnfName(Matchers.any(),Mockito.any()); - changeManagementServiceSpied.doChangeManagement(updateRequest,"anyVnfName"); + changeManagementServiceSpied.doChangeManagement(updateRequest, "anyVnfName"); return requestDetails; } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java deleted file mode 100644 index f3df4c6a..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.onap.vid.services; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.vid.changeManagement.ChangeManagementRequest; -import org.onap.vid.changeManagement.ChangeManagementResponse; -import org.springframework.http.ResponseEntity; - -import junit.framework.Assert; - -import static org.junit.Assert.*; - - -public class ChangeManagementServiceTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void doChangeManagement_requestTypeIsUpdateVnfNotFound_doUpdateAndReturnNull() throws Exception { - - } - -} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java index d849869b..9d11ad32 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java @@ -29,8 +29,8 @@ import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.client.SyncRestClient; -import org.onap.vid.controllers.MsoConfig; -import org.onap.vid.controllers.WebConfig; +import org.onap.vid.controller.MsoConfig; +import org.onap.vid.controller.WebConfig; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoInterface; @@ -116,15 +116,14 @@ public class ChangeManagementServiceUnitTest extends AbstractTestNGSpringContext @Configuration public static class TestMsoConfig extends MsoConfig { - @Override public MsoRestClientNew getMsoClient() { MsoRestClientNew spyClient = spy(new MsoRestClientNew(new SyncRestClient(), "")); return spyClient; } @Bean - public ChangeManagementService getChangeManagementService(DataAccessService dataAccessService, MsoBusinessLogic msoInterface, SchedulerRestInterfaceIfc schedulerRestInterface) { - return new ChangeManagementServiceImpl(dataAccessService, msoInterface, schedulerRestInterface); + public ChangeManagementService getChangeManagementService(DataAccessService dataAccessService, MsoBusinessLogic msoInterface, SchedulerRestInterfaceIfc schedulerRestInterface, CloudOwnerService cloudOwnerService) { + return new ChangeManagementServiceImpl(dataAccessService, msoInterface, schedulerRestInterface, cloudOwnerService); } } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java new file mode 100644 index 00000000..d6148bf2 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/CloudOwnerServiceTest.java @@ -0,0 +1,125 @@ +package org.onap.vid.services; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.properties.Features; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.HashMap; +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +public class CloudOwnerServiceTest { + + @Mock + private AaiClientInterface aaiClient; + + @Mock + private FeatureManager featureManager; + + @InjectMocks + private CloudOwnerServiceImpl cloudOwnerService; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @AfterMethod + public void resetMocks() { + Mockito.reset(aaiClient); + Mockito.reset(featureManager); + } + + @DataProvider + public static Object[][] testEnrichRequestDataProvider() { + return new Object[][]{{true}, {false}}; + } + + @Test(dataProvider = "testEnrichRequestDataProvider") + public void whenCloudConfigurationInAdditionalProperties_cloudConfigurationIsEnrichedWithCloudOwner(boolean isFeatureActive) { + when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isFeatureActive); + String lcpCloudRegionId = "lcp1"; + RequestDetails requestDetails = createRequestDetailsWithCloudConfigurationInAdditionalProperties(lcpCloudRegionId); + String aaiCloudOwner = "myCloudOwner"; + when(aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId)).thenReturn(aaiCloudOwner); + cloudOwnerService.enrichRequestWithCloudOwner(requestDetails); + if (isFeatureActive) { + assertEquals(aaiCloudOwner, requestDetails.extractValueByPathUsingAdditionalProperties( + ImmutableList.of("requestDetails", "cloudConfiguration", "cloudOwner"), String.class)); + } + else { + Map cloudConfiguration = requestDetails.extractValueByPathUsingAdditionalProperties( + ImmutableList.of("requestDetails", "cloudConfiguration"), Map.class); + assertThat(cloudConfiguration, not(hasKey("cloudOwner"))); + } + } + + @Test(dataProvider = "testEnrichRequestDataProvider") + public void whenCloudConfigurationInRequestDetailsField_cloudConfigurationIsEnrichedWithCloudOwner(boolean isFeatureActive) { + when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isFeatureActive); + String lcpCloudRegionId = "lcp1"; + RequestDetails requestDetails = createRequestDetailsWithCloudField(lcpCloudRegionId); + String aaiCloudOwner = "myCloudOwner"; + when(aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId)).thenReturn(aaiCloudOwner); + cloudOwnerService.enrichRequestWithCloudOwner(requestDetails); + if (isFeatureActive) { + assertEquals(aaiCloudOwner, requestDetails.getCloudConfiguration().getCloudOwner()); + } + else { + assertNull(requestDetails.getCloudConfiguration().getCloudOwner()); + } + } + + private RequestDetails createRequestDetailsWithCloudConfigurationInAdditionalProperties(String lcpCloudRegionId) { + RequestDetails requestDetails = new RequestDetails(); + Map cloudConfiguration = new HashMap<>(); + cloudConfiguration.put("lcpCloudRegionId", lcpCloudRegionId); + requestDetails.setAdditionalProperty("requestDetails", + ImmutableMap.of("cloudConfiguration", cloudConfiguration)); + return requestDetails; + } + + private RequestDetails createRequestDetailsWithCloudField(String lcpCloudRegionId) { + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setLcpCloudRegionId(lcpCloudRegionId); + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setCloudConfiguration(cloudConfiguration); + return requestDetails; + } + + @Test(expectedExceptions= GenericUncheckedException.class) + public void whenAaiClientThrowException_thenExceptionIsPopulatedByEnrichMethod() { + when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true); + String lcpCloudRegionId = "lcp1"; + RequestDetails requestDetails = createRequestDetailsWithCloudConfigurationInAdditionalProperties(lcpCloudRegionId); + when(aaiClient.getCloudOwnerByCloudRegionId(lcpCloudRegionId)).thenThrow(new RuntimeException()); + cloudOwnerService.enrichRequestWithCloudOwner(requestDetails); + } + + @Test + public void whenThereIsNoCloudConfiguration_enrichmentMethodNotFailed() { + when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true); + RequestDetails requestDetails = new RequestDetails(); + cloudOwnerService.enrichRequestWithCloudOwner(requestDetails); + //if no exception was thrown test success + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java index 051a1cf4..d231de8b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/CsvServiceTest.java @@ -1,80 +1,82 @@ -//package org.onap.vid.services; -//import org.apache.commons.io.IOUtils; -//import org.onap.vid.services.CsvServiceImpl; -//import org.skyscreamer.jsonassert.JSONAssert; -//import org.skyscreamer.jsonassert.JSONCompareMode; -//import org.testng.Assert; -//import org.testng.annotations.DataProvider; -//import org.testng.annotations.Test; -//import org.json.JSONObject; -// -//import javax.ws.rs.BadRequestException; -//import java.io.IOException; -//import java.lang.reflect.Method; -//import java.net.URL; -//import java.util.List; -// -//@Test -//public class CsvServiceTest { -// -// private CsvServiceImpl csvService = new CsvServiceImpl(); -// private final static String CSV_FOLDER = "csv_files/{CSV_FILE}"; -// private final static String VALID_CSV = "csv_to_json.csv"; -// private final static String ONE_LINE_CSV = "one_line.csv"; -// private final static String EMPTY_CSV = "empty_file.csv"; -// private final static String MISSING_CONTENT_CSV = "missing_content.csv"; -// private final static String MISSING_VALUES_CSV = "missing_values.csv"; -// -// -///* -// @Test -// public void parseValidCsv() throws IllegalAccessException, IOException, InstantiationException { -// String expectedJson = getExpectation("vnfConfigUpdatePayload.json"); -// readAndParse(VALID_CSV,16,expectedJson); -// -// }*/ -// -// private String getExpectation(String modelFileName) throws IOException { -// // load expected result -// final URL resource = this.getClass().getResource("/" + modelFileName); -// String expected = IOUtils.toString(resource, "UTF-8"); -// return expected; -// } -///* -// @Test -// public void parseOneLineCsv() throws IllegalAccessException, IOException, InstantiationException { -// String expectedJson ="{\"payload\":{\"request-parameters\":{\"vnf-name\":\"ibcx0099v\"}}}"; -// readAndParse(ONE_LINE_CSV,1,expectedJson); -// }*/ -// -// @DataProvider -// public static Object[][] invalidFiles(Method test) { -// return new Object[][]{ -// {MISSING_CONTENT_CSV}, {MISSING_VALUES_CSV} -// }; -// } -///* -// @Test(dataProvider = "invalidFiles", expectedExceptions = {BadRequestException.class}, expectedExceptionsMessageRegExp = "Invalid csv file") -// public void parseMissingContentCsv(String invalidFile) throws IllegalAccessException, IOException, InstantiationException { -// readAndParse(invalidFile, 2, null); -// } -// -// -// @Test -// public void parseEmptyCsv() throws IllegalAccessException, IOException, InstantiationException { -// String expectedJson ="{}"; -// readAndParse(EMPTY_CSV,0,expectedJson); -// } -// -// private void readAndParse(String fileName, int expectedNumRows, String expectedJson) throws IllegalAccessException, IOException, InstantiationException { -// final URL resource = CsvServiceTest.class.getClassLoader().getResource(CSV_FOLDER.replaceFirst("\\{CSV_FILE\\}", fileName)); -// Assert.assertNotNull(resource, "The csv file was not found"); -// List content = csvService.readCsv(resource.getPath()); -// Assert.assertEquals(content.size(), expectedNumRows, "The number of non-empty lines in file is wrong"); -// JSONObject json = csvService.convertCsvToJson (content); -// JSONAssert.assertEquals(expectedJson, json, JSONCompareMode.STRICT); -// -// }*/ -// -// -//} +package org.onap.vid.services; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.skyscreamer.jsonassert.JSONAssert; +import org.skyscreamer.jsonassert.JSONCompareMode; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import javax.ws.rs.BadRequestException; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLDecoder; +import java.util.List; + +public class CsvServiceTest { + + private CsvServiceImpl csvService = new CsvServiceImpl(); + private final static String CSV_FOLDER = "csv_files/{CSV_FILE}"; + private final static String VALID_CSV = "csv_to_json.csv"; + private final static String ONE_LINE_CSV = "one_line.csv"; + private final static String EMPTY_CSV = "empty_file.csv"; + private final static String MISSING_CONTENT_CSV = "missing_content.csv"; + private final static String MISSING_VALUES_CSV = "missing_values.csv"; + + + + @Test + public void parseValidCsv() throws IllegalAccessException, IOException, InstantiationException { + String expectedJson = getExpectation("vnfConfigUpdatePayload.json"); + readAndParse(VALID_CSV,16,expectedJson); + + } + + private String getExpectation(String modelFileName) throws IOException { + // load expected result + final URL resource = this.getClass().getResource("/" + modelFileName); + String expected = IOUtils.toString(resource, "UTF-8"); + return expected; + } + + @Test + public void parseOneLineCsv() throws IllegalAccessException, IOException, InstantiationException { + String expectedJson ="{\"payload\":{\"request-parameters\":{\"vnf-name\":\"ibcx0099v\"}}}"; + readAndParse(ONE_LINE_CSV,1,expectedJson); + } + + @DataProvider + public static Object[][] invalidFiles(Method test) { + return new Object[][]{ + {MISSING_CONTENT_CSV}, {MISSING_VALUES_CSV} + }; + } + + @Test(dataProvider = "invalidFiles", expectedExceptions = {BadRequestException.class}, expectedExceptionsMessageRegExp = "Invalid csv file") + public void parseMissingContentCsv(String invalidFile) throws IllegalAccessException, IOException, InstantiationException { + readAndParse(invalidFile, 2, null); + } + + + @Test + public void parseEmptyCsv() throws IllegalAccessException, IOException, InstantiationException { + String expectedJson ="{}"; + readAndParse(EMPTY_CSV,0,expectedJson); + } + + private void readAndParse(String fileName, int expectedNumRows, String expectedJson) throws IllegalAccessException, IOException, InstantiationException { + final URL resource = CsvServiceTest.class.getClassLoader().getResource(CSV_FOLDER.replaceFirst("\\{CSV_FILE\\}", fileName)); + Assert.assertNotNull(resource, "The csv file was not found"); + //using URLDecoder.decode to convert special characters from %XX to real character + //see https://stackoverflow.com/questions/32251251/java-classloader-getresource-with-special-characters-in-path + List content = csvService.readCsv(URLDecoder.decode(resource.getPath(), "UTF-8")); + Assert.assertEquals(content.size(), expectedNumRows, "The number of non-empty lines in file is wrong"); + JSONObject json = csvService.convertCsvToJson (content); + JSONAssert.assertEquals(expectedJson, json, JSONCompareMode.STRICT); + + } + + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java index ff4b34f5..3686dc26 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java @@ -1,616 +1,675 @@ package org.onap.vid.services; -// -//import com.google.common.collect.ImmutableList; -//import com.google.common.collect.ImmutableMap; -//import org.apache.commons.lang.RandomStringUtils; -//import org.apache.commons.lang3.RandomUtils; -//import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -//import org.apache.commons.lang3.builder.ToStringStyle; -//import org.hibernate.SessionFactory; -//import org.onap.vid.exceptions.GenericUncheckedException; -//import org.onap.vid.exceptions.OperationNotAllowedException; -//import org.onap.vid.job.Job; -//import org.onap.vid.job.JobAdapter; -//import org.onap.vid.job.JobType; -//import org.onap.vid.job.JobsBrokerService; -//import org.onap.vid.job.impl.JobDaoImpl; -//import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; -//import org.onap.vid.utils.DaoUtils; -//import org.onap.vid.config.DataSourceConfig; -//import org.onap.vid.config.JobAdapterConfig; -//import org.onap.portalsdk.core.domain.support.DomainVo; -//import org.onap.portalsdk.core.service.DataAccessService; -//import org.onap.portalsdk.core.util.SystemProperties; -//import org.springframework.test.context.ContextConfiguration; -//import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -//import org.testng.Assert; -//import org.testng.annotations.AfterMethod; -//import org.testng.annotations.BeforeMethod; -//import org.testng.annotations.DataProvider; -//import org.testng.annotations.Test; -// -//import javax.inject.Inject; -//import java.lang.reflect.Method; -//import java.time.LocalDateTime; -//import java.time.ZoneId; -//import java.util.*; -//import java.util.concurrent.*; -//import java.util.stream.Collectors; -//import java.util.stream.IntStream; -//import java.util.stream.Stream; -// -//import static java.util.concurrent.TimeUnit.MILLISECONDS; -//import static org.hamcrest.CoreMatchers.equalTo; -//import static org.hamcrest.CoreMatchers.is; -//import static org.hamcrest.MatcherAssert.assertThat; -//import static org.hamcrest.Matchers.both; -//import static org.hamcrest.Matchers.containsInAnyOrder; -//import static org.onap.vid.job.Job.JobStatus.*; -//import static org.onap.vid.utils.Streams.not; -//import static org.testng.Assert.assertNotNull; -//import static org.testng.AssertJUnit.assertEquals; -// -//@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, JobAdapterConfig.class}) -//public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { -// -// private static final int JOBS_COUNT = 127; -// private static final boolean DELETED = true; -// private final ExecutorService executor = Executors.newFixedThreadPool(90); -// -// private final Set threadsIds = new ConcurrentSkipListSet<>(); -// -// private final long FEW = 500; -// -// private final String JOBS_SHOULD_MATCH = "the jobs that added and those that pulled must be the same"; -// private final String JOBS_PEEKED_SHOULD_MATCH = "the jobs that added and those that peeked must be the same"; -// private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = "Service status does not allow deletion from the queue"; -// private static final String DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE = "Service does not exist"; -// private JobsBrokerService broker; -// -// @Inject -// JobAdapter jobAdapter; -// @Inject -// private DataAccessService dataAccessService; -// @Inject -// private SessionFactory sessionFactory; -// -// /* -// - pulling jobs is limited to inserted ones -// - putting back allows getting the job again -// - multi threads safety -// - any added job should be visible with view -// -// - edges: -// - pulling with empty repo should return empty optional -// - pulling more than expected should return empty optional -// - putting one, over-pulling from a different thread -// - take before inserting, then insert while waiting -// -// */ -// -// private class NoJobException extends RuntimeException { -// } -// -// private Future newJobAsync(JobsBrokerService b) { -// return newJobAsync(b, createMockJob("user id")); -// } -// -// private Future newJobAsync(JobsBrokerService b, Job.JobStatus status) { -// return newJobAsync(b, createMockJob("user id", status)); -// } -// -// private Job createMockJob(String userId) { -// return jobAdapter.createJob( -// JobType.NoOp, -// new JobAdapter.AsyncJobRequest() { -// public int nothing = 42; -// }, -// UUID.randomUUID(), -// userId, -// RandomUtils.nextInt()); -// } -// -// private Job createMockJob(String userId, Job.JobStatus jobStatus) { -// Job job = createMockJob(userId); -// job.setStatus(jobStatus); -// return job; -// } -// -// private Future newJobAsync(JobsBrokerService b, Job job) { -// final Future jobFuture = executor.submit(() -> { -// accountThreadId(); -// -// b.add(job); -// -// return job; -// }); -// return jobFuture; -// } -// -// private void pushBackJobAsync(JobsBrokerService b, Job job) { -// executor.submit(() -> { -// accountThreadId(); -// b.pushBack(job); -// return job; -// }); -// } -// -// private Future> pullJobAsync(JobsBrokerService broker) { -// final Future> job = executor.submit(() -> { -// accountThreadId(); -// // Pull only pending jobs, as H2 database does not support our SQL for in-progress jobs -// return broker.pull(Job.JobStatus.PENDING, UUID.randomUUID().toString()); -// }); -// return job; -// } -// -// private Job waitForFutureOptionalJob(Future> retrievedOptionalJobFuture) { -// try { -// return retrievedOptionalJobFuture.get(FEW, MILLISECONDS).orElseThrow(NoJobException::new); -// } catch (TimeoutException | InterruptedException | ExecutionException e) { -// throw new RuntimeException(e); -// } -// } -// -// private Job waitForFutureJob(Future retrievedJobFuture) { -// try { -// return retrievedJobFuture.get(FEW, MILLISECONDS); -// } catch (TimeoutException | InterruptedException | ExecutionException e) { -// throw new RuntimeException(e); -// } -// } -// -// private List putAndGetALotOfJobs(JobsBrokerService broker) { -// final List originalJobs = putALotOfJobs(broker); -// final List retrievedJobs = getAlotOfJobs(broker); -// -// assertThat(JOBS_SHOULD_MATCH, retrievedJobs, containsInAnyOrder(originalJobs.toArray())); -// -// return retrievedJobs; -// } -// -// private List putALotOfJobs(JobsBrokerService broker) { -// int n = JOBS_COUNT; -// return IntStream.range(0, n) -// .mapToObj(i -> newJobAsync(broker)) -// .map(this::waitForFutureJob) -// .collect(Collectors.toList()); -// } -// -// private List getAlotOfJobs(JobsBrokerService broker) { -// int n = JOBS_COUNT; -// return IntStream.range(0, n) -// .mapToObj(i -> pullJobAsync(broker)) -// .map(this::waitForFutureOptionalJob) -// .collect(Collectors.toList()); -// } -// -// private void pushBackJobs(List jobs, JobsBrokerService broker) { -// jobs.forEach(job -> pushBackJobAsync(broker, job)); -// } -// -// private void accountThreadId() { -// threadsIds.add(Thread.currentThread().getId()); -// } -// -// @AfterMethod -// public void threadsCounter() { -// System.out.println("participating threads count: " + threadsIds.size()); -// threadsIds.clear(); -// } -// -// @BeforeMethod -// public void initializeBroker() { -// broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0); -// ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll(); -// } -// -// @Test -// public void givenSingleJob_getIt_verifySameJob() { -// final Job originalJob = waitForFutureJob(newJobAsync(broker)); -// -// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); -// assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(originalJob)); -// } -// -// @Test -// public void givenManyJobs_getJobsAndPushThemBack_alwaysSeeAllOfThemWithPeek() throws InterruptedException { -// final List originalJobs = putALotOfJobs(broker); -// -// MILLISECONDS.sleep(FEW); -// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); -// -// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); -// -// MILLISECONDS.sleep(FEW); -// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); -// -// pushBackJobAsync(broker, retrievedJob); -// -// MILLISECONDS.sleep(FEW); -// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); -// } -// -// @Test -// public void givenManyJobs_getThemAll_verifySameJobs() { -// putAndGetALotOfJobs(broker); -// } -// -// @Test -// public void givenManyJobs_getThemAllThenPushBackandGet_verifySameJobs() { -// final List retrievedJobs1 = putAndGetALotOfJobs(broker); -// -// pushBackJobs(retrievedJobs1, broker); -// final List retrievedJobs2 = getAlotOfJobs(broker); -// -// assertThat(JOBS_SHOULD_MATCH, retrievedJobs2, containsInAnyOrder(retrievedJobs1.toArray())); -// } -// -// private static Date toDate(LocalDateTime localDateTime) { -// return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); -// } -// -// private void setModifiedDateToJob(UUID jobUuid, Date date) { -// DomainVo job = dataAccessService.getDomainObject(JobDaoImpl.class, jobUuid, DaoUtils.getPropsMap()); -// job.setModified(date); -// DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { -// session.saveOrUpdate(job); -// return 1; -// }); -// } -// -// -// public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date) { -// return createNewJob(indexInBulk, templateId, userId, status, takenBy, date, false); -// } -// -// public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date, boolean deleted){ -// JobDaoImpl job = new JobDaoImpl(); -// job.setTypeAndData(JobType.NoOp, ImmutableMap.of("x", RandomStringUtils.randomAlphanumeric(15))); -// job.setIndexInBulk(indexInBulk); -// job.setTemplateId(templateId); -// job.setType(JobType.NoOp); -// job.setStatus(status); -// job.setTakenBy(takenBy); -// job.setCreated(toDate(date)); -// job.setModified(toDate(date)); -// job.setUserId(userId); -// if (deleted) { -// job.setDeletedAt(new Date()); -// } -// return job; -// } -// -// @DataProvider -// public static Object[][] jobs(Method test) { -// LocalDateTime oldestDate = LocalDateTime.now().minusHours(30); -// UUID sameTemplate = UUID.randomUUID(); -// return new Object[][]{ -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, oldestDate), -// createNewJob(22, UUID.randomUUID(), "userId", PENDING, null, oldestDate), -// createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)), -// createNewJob(44, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(5))), -// 4, -// 0, -// PENDING, -// "Broker should pull the first pending job by oldest date then by job index" -// }, -// { ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", COMPLETED,null, oldestDate), -// createNewJob(11, UUID.randomUUID(), "userId", PENDING,null, oldestDate, DELETED),createNewJob(12, UUID.randomUUID(), "userId", FAILED,null, oldestDate), -// createNewJob(13, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate), -// createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate), -// createNewJob(22, UUID.randomUUID(), "userId", PENDING,null, oldestDate), -// createNewJob(33, UUID.randomUUID(), "userId", PENDING,null, LocalDateTime.now().minusHours(2))), -// 6, -// 5, -// PENDING, -// "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), -// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), -// 2, -// -1, -// PENDING, -// "Broker should not pull any job when it exceeded mso limit with count (in-progress) statuses" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), -// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), -// 2, -// -1, -// PENDING, -// "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), -// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), -// 3, -// 2, -// PENDING, -// "Broker should pull first job when it doesn't exceeded mso limit with count(in-progress or pending && taken) statuses" -// }, -// {ImmutableList.of( -// createNewJob(11, sameTemplate, "userId", PENDING, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate), -// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), -// 3, -// -1, -// PENDING, -// "Broker should not pull any job when there is another job from this template that was taken" -// }, -// {ImmutableList.of( -// createNewJob(11, sameTemplate, "userId", IN_PROGRESS, null, oldestDate), -// createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate), -// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), -// 3, -// -1, -// PENDING, -// "Broker should not pull any job when there is another job from this template that in progress" -// }, -// {ImmutableList.of( -// createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate), -// createNewJob(22, sameTemplate, "userId", STOPPED, null, oldestDate), -// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), -// 3, -// -1, -// PENDING, -// "Broker should not pull any job when there is another job from this template that was failed" -// }, -// {ImmutableList.of( -// createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate, DELETED), -// createNewJob(22, sameTemplate, "userId", STOPPED,null, oldestDate), -// createNewJob(33, sameTemplate, "userId", PENDING,null, LocalDateTime.now().minusHours(2))), -// 3, -// 2, -// PENDING, -// "Broker should pull pending job when there is another job from this template that was deleted, although failed" -// }, -// { ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, null, oldestDate), -// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate), -// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))), -// 3, -// 2, -// PENDING, -// "Broker should prioritize jobs of user that has no in-progress jobs" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userA", PENDING, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate), -// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))), -// 3, -// 2, -// PENDING, -// "Broker should prioritize jobs of user that has no taken jobs" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, LocalDateTime.now().minusHours(2)), -// createNewJob(31, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), -// createNewJob(32, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), -// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, oldestDate)), -// 5, -// 4, -// PENDING, -// "Broker should take oldest job when there is one in-progress job to each user" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate), -// createNewJob(22, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate), -// createNewJob(33, UUID.randomUUID(), UUID.randomUUID().toString(), PENDING, null, LocalDateTime.now().minusHours(2))), -// 2, -// -1, -// PENDING, -// "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), -// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate), -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), -// createNewJob(44, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(5))), -// 20, -// 1, -// IN_PROGRESS, -// "Broker with in progress topic should pull the first in progress and not taken job by oldest date" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate), -// createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate), -// createNewJob(13, UUID.randomUUID(), "userId", PENDING,null, oldestDate), -// createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate), -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate, DELETED),createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate), -// createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS,null, LocalDateTime.now().minusHours(2))), -// 20, -// 5, -// IN_PROGRESS, -// "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore deleted,completed, failed, pending and stopped statuses" -// }, -// {ImmutableList.of( -// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now()), -// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)), -// createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))), -// 20, -// -1, -// IN_PROGRESS, -// "Broker with in progress topic should not pull any job if its modified date is smaller than now-interval (20 seconds)" -// } -// -// }; -// } -// -// -// @Test(dataProvider = "jobs") -// public void givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(List jobs, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) { -// JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20); -// for (JobDaoImpl job : jobs) { -// Date modifiedDate = job.getModified(); -// broker.add(job); -// setModifiedDateToJob(job.getUuid(), modifiedDate); -// } -// Optional nextJob = broker.pull(topic, UUID.randomUUID().toString()); -// boolean shouldAnyBeSelected = expectedIndexSelected >= 0; -// Assert.assertEquals(nextJob.isPresent(), shouldAnyBeSelected, assertionReason); -// if (shouldAnyBeSelected) { -// Assert.assertEquals(jobs.get(expectedIndexSelected), nextJob.get(), assertionReason); -// } -// } -// -// @DataProvider -// public Object[][] topics() { -// return Arrays.stream(Job.JobStatus.values()) -// .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS).contains(t))) -// .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); -// } -// -// @Test(dataProvider = "topics", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Unsupported topic.*") -// public void pullUnexpectedTopic_exceptionIsThrown(Job.JobStatus topic) { -// broker.pull(topic, UUID.randomUUID().toString()); -// } -// -// @Test(expectedExceptions = NoJobException.class) -// public void givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved() { -// Stream.of(Job.JobStatus.values()) -// .filter(not(s -> s.equals(PENDING))) -// .map(s -> createMockJob("some user id", s)) -// .map(job -> newJobAsync(broker, job)) -// .map(this::waitForFutureJob) -// .collect(Collectors.toList()); -// -// waitForFutureOptionalJob(pullJobAsync(broker)); -// } -// -// @Test -// public void givenPendingAndNonPendingJobs_getJobAsPendingTopic_verifyAJobRetrieved() { -// newJobAsync(broker); // this negated the expected result of the call below -// givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved(); -// } -// -// @Test(expectedExceptions = NoJobException.class) -// public void givenManyJobs_pullThemAllAndAskOneMore_verifyFinallyNothingRetrieved() { -// putAndGetALotOfJobs(broker); -// waitForFutureOptionalJob(pullJobAsync(broker)); -// } -// -// @Test(expectedExceptions = NoJobException.class) -// public void givenNoJob_requestJob_verifyNothingRetrieved() throws InterruptedException, ExecutionException, TimeoutException { -// final Future> futureOptionalJob = pullJobAsync(broker); -// assertThat("job should not be waiting yet", futureOptionalJob.get(FEW, MILLISECONDS).isPresent(), is(false)); -// waitForFutureOptionalJob(futureOptionalJob); -// } -// -// @Test(expectedExceptions = IllegalStateException.class) -// public void givenSinglePulledJob_pushBackDifferentJob_verifyPushingRejected() { -// waitForFutureJob(newJobAsync(broker)); -// waitForFutureJob(newJobAsync(broker)); -// waitForFutureOptionalJob(pullJobAsync(broker)); -// -// Job myJob = createMockJob("user id"); -// myJob.setUuid(UUID.randomUUID()); -// -// broker.pushBack(myJob); //Should fail -// } -// -// @Test -// public void givenSingleJob_pushBackModifiedJob_verifyPulledIsVeryVeryTheSame() { -// final ImmutableMap randomDataForMostRecentJobType = -// ImmutableMap.of("42", 42, "complex", ImmutableList.of("a", "b", "c")); -// -// waitForFutureJob(newJobAsync(broker)); -// final Job job = waitForFutureOptionalJob(pullJobAsync(broker)); -// -// job.setStatus(Job.JobStatus.PENDING); -// job.setTypeAndData(JobType.NoOp, ImmutableMap.of("good", "morning")); -// job.setTypeAndData(JobType.HttpCall, ImmutableMap.of()); -// job.setTypeAndData(JobType.ServiceInstantiation, randomDataForMostRecentJobType); -// -// broker.pushBack(job); -// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); -// -// assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(job)); -// assertThat(JOBS_SHOULD_MATCH, retrievedJob.getData(), both(equalTo(job.getData())).and(equalTo(randomDataForMostRecentJobType))); -// assertThat(JOBS_SHOULD_MATCH, jobDataReflected(retrievedJob), is(jobDataReflected(job))); -// } -// -// private static String jobDataReflected(Job job) { -// return new ReflectionToStringBuilder(job, ToStringStyle.SHORT_PREFIX_STYLE) -// .setExcludeFieldNames("created", "modified", "takenBy") -// .toString(); -// } -// -// @Test(expectedExceptions = IllegalStateException.class) -// public void givenSingleJob_pushBackTwice_verifyPushingRejected() { -// waitForFutureJob(newJobAsync(broker)); -// final Job job = waitForFutureOptionalJob(pullJobAsync(broker)); -// -// broker.pushBack(job); -// broker.pushBack(job); //Should fail -// } -// -// @Test -// public void addJob_PeekItById_verifySameJobWasPeeked() { -// String userId = UUID.randomUUID().toString(); -// Job myJob = createMockJob(userId); -// UUID uuid = broker.add(myJob); -// Job peekedJob = broker.peek(uuid); -// assertEquals("added testId is not the same as peeked TestsId", -// userId, -// peekedJob.getData().get("userId")); -// } -// -// @Test(dataProvider = "jobStatusesForSuccessDelete", expectedExceptions = NoJobException.class) -// public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) { -// final Job job = waitForFutureJob(newJobAsync(broker, status)); -// broker.delete(job.getUuid()); -// assertNotNull(((JobDaoImpl) broker.peek(job.getUuid())).getDeletedAt(), "job should be deleted"); -// waitForFutureOptionalJob(pullJobAsync(broker)); -// } -// -// @DataProvider -// public static Object[][] jobStatusesForSuccessDelete() { -// return new Object[][]{ -// {PENDING}, -// {STOPPED} -// }; -// } -// -// @Test( -// dataProvider = "jobStatusesForFailedDelete", -// expectedExceptions = OperationNotAllowedException.class, -// expectedExceptionsMessageRegExp=DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE -// ) -// public void deleteJob_notAllowedStatus_exceptionIsThrown(Job.JobStatus status, boolean taken) { -// final Job job = waitForFutureJob(newJobAsync(broker, createMockJob("some user id", status))); -// -// if (taken) { -// waitForFutureOptionalJob(pullJobAsync(broker)); -// } -// -// -// broker.delete(job.getUuid()); -// } -// -// @DataProvider -// public static Object[][] jobStatusesForFailedDelete() { -// return new Object[][]{ -// {PENDING, true}, -// {IN_PROGRESS, false}, -// {COMPLETED, false}, -// {PAUSE, false}, -// {FAILED, false}, -// }; -// } -// -// @Test(expectedExceptions = OperationNotAllowedException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE) -// public void deleteJob_notExist_exceptionIsThrown() { -// waitForFutureJob(newJobAsync(broker, createMockJob("some user id", PENDING))); -// broker.delete(new UUID(111, 111)); -// } -// -//} + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang3.RandomUtils; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.hibernate.SessionFactory; +import org.onap.portalsdk.core.domain.support.DomainVo; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.config.DataSourceConfig; +import org.onap.vid.config.JobAdapterConfig; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.command.JobCommandFactoryTest; +import org.onap.vid.job.impl.JobDaoImpl; +import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; +import org.onap.vid.utils.DaoUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import javax.inject.Inject; +import java.lang.reflect.Method; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; +import java.util.concurrent.*; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.stream.Collectors.toList; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.both; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.onap.vid.job.Job.JobStatus.*; +import static org.onap.vid.utils.Streams.not; +import static org.testng.Assert.assertNotNull; +import static org.testng.AssertJUnit.assertEquals; + +@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, JobAdapterConfig.class}) +public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { + + private static final Logger logger = LogManager.getLogger(JobsBrokerServiceTest.class); + + private static final int JOBS_COUNT = 127; + private static final boolean DELETED = true; + private final ExecutorService executor = Executors.newFixedThreadPool(90); + + private final Set threadsIds = new ConcurrentSkipListSet<>(); + + private final long FEW = 500; + + private final String JOBS_SHOULD_MATCH = "the jobs that added and those that pulled must be the same"; + private final String JOBS_PEEKED_SHOULD_MATCH = "the jobs that added and those that peeked must be the same"; + private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = "Service status does not allow deletion from the queue"; + private static final String DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE = "Service does not exist"; + private JobsBrokerService broker; + + @Inject + JobAdapter jobAdapter; + @Inject + private DataAccessService dataAccessService; + @Inject + private SessionFactory sessionFactory; + + /* + - pulling jobs is limited to inserted ones + - putting back allows getting the job again + - multi threads safety + - any added job should be visible with view + + - edges: + - pulling with empty repo should return empty optional + - pulling more than expected should return empty optional + - putting one, over-pulling from a different thread + - take before inserting, then insert while waiting + + */ + + private class NoJobException extends RuntimeException { + } + + private Future newJobAsync(JobsBrokerService b) { + return newJobAsync(b, createMockJob("user id")); + } + + private Future newJobAsync(JobsBrokerService b, Job.JobStatus status) { + return newJobAsync(b, createMockJob("user id", status)); + } + + private Job createMockJob(String userId) { + return jobAdapter.createServiceInstantiationJob( + JobType.NoOp, + new JobCommandFactoryTest.MockedRequest(42,"nothing") , + UUID.randomUUID(), + userId, + "optimisticUniqueServiceInstanceName", + RandomUtils.nextInt()); + } + + private Job createMockJob(String userId, Job.JobStatus jobStatus) { + Job job = createMockJob(userId); + job.setStatus(jobStatus); + return job; + } + + private Future newJobAsync(JobsBrokerService b, Job job) { + final Future jobFuture = executor.submit(() -> { + accountThreadId(); + + b.add(job); + + return job; + }); + return jobFuture; + } + + private void pushBackJobAsync(JobsBrokerService b, Job job) { + executor.submit(() -> { + accountThreadId(); + b.pushBack(job); + return job; + }); + } + + private Future> pullJobAsync(JobsBrokerService broker) { + final Future> job = executor.submit(() -> { + accountThreadId(); + // Pull only pending jobs, as H2 database does not support our SQL for in-progress jobs + return broker.pull(Job.JobStatus.PENDING, UUID.randomUUID().toString()); + }); + return job; + } + + private Job waitForFutureOptionalJob(Future> retrievedOptionalJobFuture) { + try { + return retrievedOptionalJobFuture.get(FEW, MILLISECONDS).orElseThrow(NoJobException::new); + } catch (TimeoutException | InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + } + + private Job waitForFutureJob(Future retrievedJobFuture) { + try { + return retrievedJobFuture.get(FEW, MILLISECONDS); + } catch (TimeoutException | InterruptedException | ExecutionException e) { + throw new RuntimeException(e); + } + } + + private List putAndGetALotOfJobs(JobsBrokerService broker) { + final List originalJobs = putALotOfJobs(broker); + final List retrievedJobs = getAlotOfJobs(broker); + + assertThat(JOBS_SHOULD_MATCH, retrievedJobs, containsInAnyOrder(originalJobs.toArray())); + + return retrievedJobs; + } + + private List putALotOfJobs(JobsBrokerService broker) { + int n = JOBS_COUNT; + return IntStream.range(0, n) + .mapToObj(i -> newJobAsync(broker)) + .map(this::waitForFutureJob) + .collect(toList()); + } + + private List getAlotOfJobs(JobsBrokerService broker) { + int n = JOBS_COUNT; + return IntStream.range(0, n) + .mapToObj(i -> pullJobAsync(broker)) + .map(this::waitForFutureOptionalJob) + .collect(toList()); + } + + private void pushBackJobs(List jobs, JobsBrokerService broker) { + jobs.forEach(job -> pushBackJobAsync(broker, job)); + } + + private void accountThreadId() { + threadsIds.add(Thread.currentThread().getId()); + } + + @AfterMethod + public void threadsCounter() { + logger.info("participating threads count: " + threadsIds.size()); + threadsIds.clear(); + } + + @BeforeMethod + public void initializeBroker() { + broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0); + ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll(); + } + + @Test(enabled = false) + public void givenSingleJob_getIt_verifySameJob() { + final Job originalJob = waitForFutureJob(newJobAsync(broker)); + + final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); + assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(originalJob)); + } + + @Test(enabled = false) + public void givenManyJobs_getJobsAndPushThemBack_alwaysSeeAllOfThemWithPeek() throws InterruptedException { + final List originalJobs = putALotOfJobs(broker); + + MILLISECONDS.sleep(FEW); + assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); + + final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); + + MILLISECONDS.sleep(FEW); + assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); + + pushBackJobAsync(broker, retrievedJob); + + MILLISECONDS.sleep(FEW); + assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); + } + + @Test(enabled = false) + public void givenManyJobs_getThemAll_verifySameJobs() { + putAndGetALotOfJobs(broker); + } + + @Test(enabled = false) + public void givenManyJobs_getThemAllThenPushBackandGet_verifySameJobs() { + final List retrievedJobs1 = putAndGetALotOfJobs(broker); + + pushBackJobs(retrievedJobs1, broker); + final List retrievedJobs2 = getAlotOfJobs(broker); + + assertThat(JOBS_SHOULD_MATCH, retrievedJobs2, containsInAnyOrder(retrievedJobs1.toArray())); + } + + private static Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + private void setModifiedDateToJob(UUID jobUuid, Date date) { + DomainVo job = dataAccessService.getDomainObject(JobDaoImpl.class, jobUuid, DaoUtils.getPropsMap()); + job.setModified(date); + DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { + session.saveOrUpdate(job); + return 1; + }); + } + + + public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date) { + return createNewJob(indexInBulk, templateId, userId, status, takenBy, date, false); + } + + public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date, boolean deleted){ + JobDaoImpl job = new JobDaoImpl(); + job.setUuid(UUID.randomUUID()); + job.setTypeAndData(JobType.NoOp, ImmutableMap.of("x", RandomStringUtils.randomAlphanumeric(15))); + job.setIndexInBulk(indexInBulk); + job.setTemplateId(templateId); + job.setType(JobType.NoOp); + job.setStatus(status); + job.setTakenBy(takenBy); + job.setCreated(toDate(date)); + job.setModified(toDate(date)); + job.setUserId(userId); + if (deleted) { + job.setDeletedAt(new Date()); + } + return job; + } + + @DataProvider + public static Object[][] jobs(Method test) { + LocalDateTime oldestDate = LocalDateTime.now().minusHours(30); + UUID sameTemplate = UUID.randomUUID(); + return new Object[][]{ + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, null, oldestDate), + () -> createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(44, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(5))), + 4, + 0, + PENDING, + "Broker should pull the first pending job by oldest date then by job index" + }, + { ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED,null, oldestDate), + () -> createNewJob(11, UUID.randomUUID(), "userId", PENDING,null, oldestDate, DELETED), + () -> createNewJob(12, UUID.randomUUID(), "userId", FAILED,null, oldestDate), + () -> createNewJob(13, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate), + () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING,null, oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING,null, LocalDateTime.now().minusHours(2))), + 6, + 5, + PENDING, + "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), + 2, + -1, + PENDING, + "Broker should not pull any job when it exceeded mso limit with count (in-progress) statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), + 2, + -1, + PENDING, + "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(12, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, UUID.randomUUID().toString(), oldestDate) + ), + 3, + 2, + PENDING, + "Broker should pull first job when it doesn't exceeded mso limit with count(in-progress or pending && taken) statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, sameTemplate, "userId", PENDING, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate), + () -> createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), + 3, + -1, + PENDING, + "Broker should not pull any job when there is another job from this template that was taken" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, sameTemplate, "userId", IN_PROGRESS, null, oldestDate), + () -> createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate), + () -> createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), + 3, + -1, + PENDING, + "Broker should not pull any job when there is another job from this template that in progress" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate), + () -> createNewJob(22, sameTemplate, "userId", STOPPED, null, oldestDate), + () -> createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), + 3, + -1, + PENDING, + "Broker should not pull any job when there is another job from this template that was failed" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate, DELETED), + () -> createNewJob(22, sameTemplate, "userId", STOPPED,null, oldestDate), + () -> createNewJob(33, sameTemplate, "userId", PENDING,null, LocalDateTime.now().minusHours(2))), + 3, + 2, + PENDING, + "Broker should pull pending job when there is another job from this template that was deleted, although failed" + }, + { ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, null, oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))), + 3, + 2, + PENDING, + "Broker should prioritize jobs of user that has no in-progress jobs" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", PENDING, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))), + 3, + 2, + PENDING, + "Broker should prioritize jobs of user that has no taken jobs" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(31, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(32, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, oldestDate)), + 5, + 4, + PENDING, + "Broker should take oldest job when there is one in-progress job to each user" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate), + () -> createNewJob(22, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate), + () -> createNewJob(33, UUID.randomUUID(), UUID.randomUUID().toString(), PENDING, null, LocalDateTime.now().minusHours(2))), + 2, + -1, + PENDING, + "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), + () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate), + () -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(44, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(5))), + 20, + 1, + IN_PROGRESS, + "Broker with in progress topic should pull the first in progress and not taken job by oldest date" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate), + () -> createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate), + () -> createNewJob(13, UUID.randomUUID(), "userId", PENDING, null, oldestDate), + () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED, null, oldestDate), + () -> createNewJob(15, UUID.randomUUID(), "userId", CREATING, null, oldestDate), + () -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate, DELETED), + () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(16, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate) + ), + 20, + 6, + IN_PROGRESS, + "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore all other statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate), + () -> createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate), + () -> createNewJob(13, UUID.randomUUID(), "userId", PENDING, null, oldestDate), + () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED, null, oldestDate), + () -> createNewJob(15, UUID.randomUUID(), "userId", CREATING, null, oldestDate), + () -> createNewJob(11, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate, DELETED), + () -> createNewJob(22, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate), + () -> createNewJob(33, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), + () -> createNewJob(16, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate) + ), + 20, + 6, + RESOURCE_IN_PROGRESS, + "Broker with RESOURCE_IN_PROGRESS topic should pull only RESOURCE_IN_PROGRESS jobs - first RESOURCE_IN_PROGRESS job by oldest date - ignore all other statuses" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now()), + () -> createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)), + () -> createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))), + 20, + -1, + IN_PROGRESS, + "Broker with in progress topic should not pull any job if its modified date is smaller than now-interval (20 seconds)" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now()), + () -> createNewJob(22, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)), + () -> createNewJob(33, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))), + 20, + -1, + RESOURCE_IN_PROGRESS, + "Broker with RESOURCE_IN_PROGRESS topic should not pull any job if its modified date is smaller than now-interval (20 seconds)" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now()), + () -> createNewJob(22, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now().minusSeconds(1)), + () -> createNewJob(33, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now().minusHours(2))), + 1, + 2, + CREATING, + "Broker with creating topic should pull oldest creating job and ignore mso limit" + }, + {ImmutableList.of( + (Jobber)() -> createNewJob(33, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now())), + 1, + 0, + CREATING, + "Broker with CREATING topic should pull CREATING job that was just modified" + } + + }; + } + + public interface Jobber { + // Will defer LocalDateTime.now() to test's "real-time" + JobDaoImpl toJob(); + } + + @Test(enabled = false, dataProvider = "jobs") + public void givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(List jobbers, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) { + JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20); + final List jobs = jobbers.stream().map(Jobber::toJob).collect(toList()); + for (JobDaoImpl job : jobs) { + Date modifiedDate = job.getModified(); + broker.add(job); + setModifiedDateToJob(job.getUuid(), modifiedDate); + } + Optional nextJob = broker.pull(topic, UUID.randomUUID().toString()); + boolean shouldAnyBeSelected = expectedIndexSelected >= 0; + String pulledJobDesc = nextJob.map(job -> ". pulled job: " + job.toString()).orElse(". no job pulled"); + Assert.assertEquals(nextJob.isPresent(), shouldAnyBeSelected, assertionReason+pulledJobDesc); + if (shouldAnyBeSelected) { + Assert.assertEquals(jobs.get(expectedIndexSelected), nextJob.get(), assertionReason); + } + } + + @DataProvider + public Object[][] topics() { + return Arrays.stream(Job.JobStatus.values()) + .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS, CREATING, RESOURCE_IN_PROGRESS).contains(t))) + .map(v -> new Object[]{v}).collect(toList()).toArray(new Object[][]{}); + } + + @Test(enabled = false, dataProvider = "topics", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Unsupported topic.*") + public void pullUnexpectedTopic_exceptionIsThrown(Job.JobStatus topic) { + broker.pull(topic, UUID.randomUUID().toString()); + } + + @Test(enabled = false, expectedExceptions = NoJobException.class) + public void givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved() { + Stream.of(Job.JobStatus.values()) + .filter(not(s -> s.equals(PENDING))) + .map(s -> createMockJob("some user id", s)) + .map(job -> newJobAsync(broker, job)) + .map(this::waitForFutureJob) + .collect(toList()); + + waitForFutureOptionalJob(pullJobAsync(broker)); + } + + @Test(enabled = false) + public void givenPendingAndNonPendingJobs_getJobAsPendingTopic_verifyAJobRetrieved() { + newJobAsync(broker); // this negated the expected result of the call below + givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved(); + } + + @Test(enabled = false, expectedExceptions = NoJobException.class) + public void givenManyJobs_pullThemAllAndAskOneMore_verifyFinallyNothingRetrieved() { + putAndGetALotOfJobs(broker); + waitForFutureOptionalJob(pullJobAsync(broker)); + } + + @Test(enabled = false, expectedExceptions = NoJobException.class) + public void givenNoJob_requestJob_verifyNothingRetrieved() throws InterruptedException, ExecutionException, TimeoutException { + final Future> futureOptionalJob = pullJobAsync(broker); + assertThat("job should not be waiting yet", futureOptionalJob.get(FEW, MILLISECONDS).isPresent(), is(false)); + waitForFutureOptionalJob(futureOptionalJob); + } + + @Test(enabled = false, expectedExceptions = IllegalStateException.class) + public void givenSinglePulledJob_pushBackDifferentJob_verifyPushingRejected() { + waitForFutureJob(newJobAsync(broker)); + waitForFutureJob(newJobAsync(broker)); + waitForFutureOptionalJob(pullJobAsync(broker)); + + Job myJob = createMockJob("user id"); + myJob.setUuid(UUID.randomUUID()); + + broker.pushBack(myJob); //Should fail + } + + @Test(enabled = false) + public void givenSingleJob_pushBackModifiedJob_verifyPulledIsVeryVeryTheSame() { + final ImmutableMap randomDataForMostRecentJobType = + ImmutableMap.of("42", 42, "complex", ImmutableList.of("a", "b", "c")); + + waitForFutureJob(newJobAsync(broker)); + final Job job = waitForFutureOptionalJob(pullJobAsync(broker)); + + job.setStatus(Job.JobStatus.PENDING); + job.setTypeAndData(JobType.NoOp, ImmutableMap.of("good", "morning")); + job.setTypeAndData(JobType.HttpCall, ImmutableMap.of()); + job.setTypeAndData(JobType.MacroServiceInstantiation, randomDataForMostRecentJobType); + + broker.pushBack(job); + final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); + + assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(job)); + assertThat(JOBS_SHOULD_MATCH, retrievedJob.getData(), both(equalTo(job.getData())).and(equalTo(randomDataForMostRecentJobType))); + assertThat(JOBS_SHOULD_MATCH, jobDataReflected(retrievedJob), is(jobDataReflected(job))); + } + + private static String jobDataReflected(Job job) { + return new ReflectionToStringBuilder(job, ToStringStyle.SHORT_PREFIX_STYLE) + .setExcludeFieldNames("created", "modified", "takenBy") + .toString(); + } + + @Test(enabled = false, expectedExceptions = IllegalStateException.class) + public void givenSingleJob_pushBackTwice_verifyPushingRejected() { + waitForFutureJob(newJobAsync(broker)); + final Job job = waitForFutureOptionalJob(pullJobAsync(broker)); + + broker.pushBack(job); + broker.pushBack(job); //Should fail + } + + @Test(enabled = false) + public void addJob_PeekItById_verifySameJobWasPeeked() { + String userId = UUID.randomUUID().toString(); + Job myJob = createMockJob(userId); + UUID uuid = broker.add(myJob); + Job peekedJob = broker.peek(uuid); + assertEquals("added testId is not the same as peeked TestsId", + userId, + peekedJob.getSharedData().getUserId()); + } + + @Test(enabled = false, dataProvider = "jobStatusesForSuccessDelete", expectedExceptions = NoJobException.class) + public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) { + final Job job = waitForFutureJob(newJobAsync(broker, status)); + broker.delete(job.getUuid()); + assertNotNull(((JobDaoImpl) broker.peek(job.getUuid())).getDeletedAt(), "job should be deleted"); + waitForFutureOptionalJob(pullJobAsync(broker)); + } + + @DataProvider + public static Object[][] jobStatusesForSuccessDelete() { + return new Object[][]{ + {PENDING}, + {STOPPED} + }; + } + + @Test(enabled = false, + dataProvider = "jobStatusesForFailedDelete", + expectedExceptions = OperationNotAllowedException.class, + expectedExceptionsMessageRegExp=DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE + ) + public void deleteJob_notAllowedStatus_exceptionIsThrown(Job.JobStatus status, boolean taken) { + final Job job = waitForFutureJob(newJobAsync(broker, createMockJob("some user id", status))); + + if (taken) { + waitForFutureOptionalJob(pullJobAsync(broker)); + } + + + broker.delete(job.getUuid()); + } + + @DataProvider + public static Object[][] jobStatusesForFailedDelete() { + return new Object[][]{ + {PENDING, true}, + {IN_PROGRESS, false}, + {COMPLETED, false}, + {PAUSE, false}, + {FAILED, false}, + }; + } + + @Test(enabled = false, expectedExceptions = OperationNotAllowedException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE) + public void deleteJob_notExist_exceptionIsThrown() { + waitForFutureJob(newJobAsync(broker, createMockJob("some user id", PENDING))); + broker.delete(new UUID(111, 111)); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java index cb9eb93d..00497734 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java @@ -1,19 +1,12 @@ package org.onap.vid.services; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; -import org.codehaus.jackson.map.ObjectMapper; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.vid.aai.model.AaiGetPortMirroringSourcePorts; +import org.onap.vid.aai.model.CustomQuerySimpleResult; import org.onap.vid.aai.model.PortDetailsTranslator; import org.onap.vid.aai.model.RelatedTo; import org.onap.vid.aai.model.SimpleResult; -import org.onap.vid.properties.Features; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import org.togglz.core.manager.FeatureManager; import java.io.IOException; import java.util.List; @@ -25,49 +18,38 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.collection.IsEmptyCollection.empty; -import static org.mockito.Mockito.when; public class PortDetailsTranslatorTest { private static final ObjectMapper om = new ObjectMapper(); - @InjectMocks private PortDetailsTranslator portDetailsTranslator = new PortDetailsTranslator(); - @Mock - private FeatureManager featureManager; - - @BeforeMethod - public void initMocks() throws Exception { - MockitoAnnotations.initMocks(this); - when(featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER)).thenReturn(true); - } - @Test public void extractPortDetailsFromProperties_givenValidAaiResponse() throws IOException { - final String aaiResponse = "{\n" + - " \"results\": [\n" + - " {\n" + - " \"id\": \"4876980240\",\n" + - " \"node-type\": \"l-interface\",\n" + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"properties\": {\n" + - " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + - " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + - " \"is-port-mirrored\": false,\n" + - " \"resource-version\": \"1519383879190\",\n" + - " \"in-maint\": false,\n" + - " \"is-ip-unnumbered\": false\n" + - " }\n" + - " }\n" + - " ]\n" + + final String aaiResponse = "{" + + " \"results\": [" + + " {" + + " \"id\": \"4876980240\"," + + " \"node-type\": \"l-interface\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"properties\": {" + + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"macaddr\": \"02:6d:e7:bf:87:6f\"," + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," + + " \"is-port-mirrored\": false," + + " \"resource-version\": \"1519383879190\"," + + " \"in-maint\": false," + + " \"is-ip-unnumbered\": false" + + " }" + + " }" + + " ]" + "}"; - AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); + CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class); PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse); @@ -82,29 +64,29 @@ public class PortDetailsTranslatorTest { @Test public void extractPortDetailsFromProperties_givenAaiResponseWithInstanceNameNull_yieldException() throws IOException { - final String aaiResponse = "{\n" + - " \"results\": [\n" + - " {\n" + - " \"id\": \"4876980240\",\n" + - " \"node-type\": \"l-interface\",\n" + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"properties\": {\n" + - " \"interface-name\": null,\n" + - " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + - " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + - " \"is-port-mirrored\": false,\n" + - " \"resource-version\": \"1519383879190\",\n" + - " \"in-maint\": false,\n" + - " \"is-ip-unnumbered\": false\n" + - " }\n" + - " }\n" + - " ]\n" + + final String aaiResponse = "{" + + " \"results\": [" + + " {" + + " \"id\": \"4876980240\"," + + " \"node-type\": \"l-interface\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"properties\": {" + + " \"interface-name\": null," + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"macaddr\": \"02:6d:e7:bf:87:6f\"," + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," + + " \"is-port-mirrored\": false," + + " \"resource-version\": \"1519383879190\"," + + " \"in-maint\": false," + + " \"is-ip-unnumbered\": false" + + " }" + + " }" + + " ]" + "}"; - AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); - PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse); assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); @@ -115,29 +97,29 @@ public class PortDetailsTranslatorTest { @Test public void extractPortDetailsFromProperties_givenAaiResponseWithInstanceIdNull_yieldException() throws IOException { - final String aaiResponse = "{\n" + - " \"results\": [\n" + - " {\n" + - " \"id\": \"4876980240\",\n" + - " \"node-type\": \"l-interface\",\n" + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"properties\": {\n" + - " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"interface-id\": null,\n" + - " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + - " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + - " \"is-port-mirrored\": false,\n" + - " \"resource-version\": \"1519383879190\",\n" + - " \"in-maint\": false,\n" + - " \"is-ip-unnumbered\": false\n" + - " }\n" + - " }\n" + - " ]\n" + + final String aaiResponse = "{" + + " \"results\": [" + + " {" + + " \"id\": \"4876980240\"," + + " \"node-type\": \"l-interface\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"properties\": {" + + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"interface-id\": null," + + " \"macaddr\": \"02:6d:e7:bf:87:6f\"," + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," + + " \"is-port-mirrored\": false," + + " \"resource-version\": \"1519383879190\"," + + " \"in-maint\": false," + + " \"is-ip-unnumbered\": false" + + " }" + + " }" + + " ]" + "}"; - AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); - PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse); assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); @@ -148,29 +130,29 @@ public class PortDetailsTranslatorTest { @Test public void extractPortDetailsFromProperties_givenAaiResponseWithEmptyInstanceId_yieldException() throws IOException { - final String aaiResponse = "{\n" + - " \"results\": [\n" + - " {\n" + - " \"id\": \"4876980240\",\n" + - " \"node-type\": \"l-interface\",\n" + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"properties\": {\n" + - " \"interface-name\": \"\",\n" + - " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + - " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + - " \"is-port-mirrored\": false,\n" + - " \"resource-version\": \"1519383879190\",\n" + - " \"in-maint\": false,\n" + - " \"is-ip-unnumbered\": false\n" + - " }\n" + - " }\n" + - " ]\n" + + final String aaiResponse = "{" + + " \"results\": [" + + " {" + + " \"id\": \"4876980240\"," + + " \"node-type\": \"l-interface\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"properties\": {" + + " \"interface-name\": \"\"," + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"macaddr\": \"02:6d:e7:bf:87:6f\"," + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," + + " \"is-port-mirrored\": false," + + " \"resource-version\": \"1519383879190\"," + + " \"in-maint\": false," + + " \"is-ip-unnumbered\": false" + + " }" + + " }" + + " ]" + "}"; - AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); - PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse); assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); @@ -181,29 +163,29 @@ public class PortDetailsTranslatorTest { @Test public void extractPortDetailsFromProperties_givenAaiResponseWithIsPortMirroredNull_yieldException() throws IOException { - final String aaiResponse = "{\n" + - " \"results\": [\n" + - " {\n" + - " \"id\": \"4876980240\",\n" + - " \"node-type\": \"l-interface\",\n" + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"properties\": {\n" + - " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + - " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + - " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + - " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + - " \"is-port-mirrored\": null,\n" + - " \"resource-version\": \"1519383879190\",\n" + - " \"in-maint\": false,\n" + - " \"is-ip-unnumbered\": false\n" + - " }\n" + - " }\n" + - " ]\n" + + final String aaiResponse = "{" + + " \"results\": [" + + " {" + + " \"id\": \"4876980240\"," + + " \"node-type\": \"l-interface\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"properties\": {" + + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + + " \"macaddr\": \"02:6d:e7:bf:87:6f\"," + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\"," + + " \"is-port-mirrored\": null," + + " \"resource-version\": \"1519383879190\"," + + " \"in-maint\": false," + + " \"is-ip-unnumbered\": false" + + " }" + + " }" + + " ]" + "}"; - AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); - PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + CustomQuerySimpleResult aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, CustomQuerySimpleResult.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse); assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); @@ -221,17 +203,8 @@ public class PortDetailsTranslatorTest { assertThat("List size if different than expected", result, is(empty())); } - @DataProvider - public static Object[][] trueAndFalse() { - return new Object[][]{ - { Boolean.TRUE }, { Boolean.FALSE } - }; - } - - @Test(dataProvider = "trueAndFalse") - public void getFilteredPortList_givenFeatureFlagIsOff_returnAllLInterfaces(Boolean advancedPortsFilterFlag) throws IOException { - when(featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER)).thenReturn(advancedPortsFilterFlag); - + @Test + public void getFilteredPortList_givenFeatureFlagIsOff_returnAllLInterfaces() { final String relationshipLabelSource = "org.onap.relationships.inventory.Source"; final String nodeTypeLInterface = "l-interface"; @@ -258,22 +231,16 @@ public class PortDetailsTranslatorTest { List result = portDetailsTranslator.getFilteredPortList(input); - if (advancedPortsFilterFlag) { - assertThat("List should contain all l-interfaces with a related source", result, containsInAnyOrder( - lInterfaceWithSource, lInterfaceWithSourceAndMore, - lInterfaceWithTwoSources)); - } else { - assertThat("List should contain all l-interfaces", result, containsInAnyOrder( - lInterfaceWithSource, lInterfaceWithoutSource, - lInterfaceWithoutRelations, lInterfaceWithSourceAndMore, - lInterfaceWithTwoSources)); - } + assertThat("List should contain all l-interfaces with a related source", result, containsInAnyOrder( + lInterfaceWithSource, lInterfaceWithSourceAndMore, + lInterfaceWithTwoSources)); + } private SimpleResult buildSimpleResult(String nodeType, String... relationshipLabels) { SimpleResult simpleResult = new SimpleResult(); - simpleResult.setNodeType(nodeType); - simpleResult.setRelatedTo(Stream.of(relationshipLabels).map(label -> + simpleResult.setJsonNodeType(nodeType); + simpleResult.setJsonRelatedTo(Stream.of(relationshipLabels).map(label -> new RelatedTo("my foo id", label, "logical-link", "foo url")) .collect(Collectors.toList()) ); diff --git a/vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java new file mode 100644 index 00000000..c4f77e3e --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/SchedulerServiceImplTest.java @@ -0,0 +1,179 @@ +package org.onap.vid.services; + +import com.fasterxml.jackson.core.JsonParseException; +import org.apache.xmlbeans.SystemProperties; +import org.hamcrest.Matcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.model.probes.ErrorMetadata; +import org.onap.vid.model.probes.ExternalComponentStatus; +import org.onap.vid.model.probes.HttpRequestMetadata; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.RestObjectWithRequestInfo; +import org.onap.vid.scheduler.SchedulerServiceImpl; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.springframework.test.context.web.WebAppConfiguration; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.vid.model.probes.ExternalComponentStatus.Component.SCHEDULER; + +@ContextConfiguration(classes = {SystemProperties.class}) +@WebAppConfiguration +public class SchedulerServiceImplTest extends AbstractTestNGSpringContextTests { + + @InjectMocks + private SchedulerServiceImpl schedulerService; + + @Mock + private ChangeManagementService changeManagementService; + + + @BeforeTest + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @AfterMethod + public void reset() { + Mockito.reset(changeManagementService); + } + + @Test + public void probeGetSchedulerChangeManegements_verifyGoodRequest(){ + String responseString = "[" + + " {" + + " \"vnfName\": \"dbox0001v\"," + + " \"status\": \"Triggered\"," + + " \"aotsChangeId\": \"CHG000000000001\"," + + " \"aotsApprovalStatus\": \"Approved\"," + + " \"groupId\": \"groupId\"," + + " \"dispatchTime\": \"2018-05-09T14:05:43Z\"," + + " \"msoRequestId\": \"2fb4edd1-01c4-4fee-bd4a-4ae6282aa213\"," + + " \"scheduleRequest\": {" + + " \"id\": 1," + + " \"createDateTime\": \"2018-05-09T14:05:34Z\"," + + " \"optimizerAttemptsToSchedule\": 0," + + " \"optimizerTransactionId\": \"70f05563-6705-4be0-802a-8b6b78a69d63\"," + + " \"scheduleId\": \"70f05563-6705-4be0-802a-8b6b78a69d63\"," + + " \"scheduleName\": \"70f05563-6705-4be0-802a-8b6b78a69d63\"," + + " \"status\": \"Notifications Initiated\"," + + " \"userId\": \"wl849v\"," + + " \"domain\": \"ChangeManagement\"," + + " \"domainData\": [" + + " {" + + " \"id\": 1," + + " \"name\": \"WorkflowName\"," + + " \"value\": \"VNF In Place Software Update\"" + + " }," + + " {" + + " \"id\": 2," + + " \"name\": \"CallbackUrl\"," + + " \"value\": \"https://vid-web-ete-new.ecomp.cci.att.com:8000/vid/change-management/workflow/\"" + + " }," + + " {" + + " \"id\": 3," + + " \"name\": \"CallbackData\"," + + " \"value\": \"{\\\"requestType\\\":\\\"VNF In Place Software Update\\\",\\\"requestDetails\\\":[{\\\"vnfName\\\":\\\"dbox0001v\\\",\\\"vnfInstanceId\\\":\\\"815d38c0-b686-491c-9a74-0b49add524ca\\\",\\\"modelInfo\\\":{\\\"modelType\\\":\\\"vnf\\\",\\\"modelInvariantId\\\":\\\"59f4e0b2-e1b0-4e3b-bae3-e7b8c5d32985\\\",\\\"modelVersionId\\\":\\\"345643c1-3a51-423f-aac1-502e027d8dab\\\",\\\"modelName\\\":\\\"dbox0001v\\\",\\\"modelCustomizationId\\\":\\\"01ce23cb-d276-4d71-a5f1-f9d42d0df543\\\"},\\\"cloudConfiguration\\\":{\\\"lcpCloudRegionId\\\":\\\"dpa2b\\\",\\\"tenantId\\\":\\\"b60da4f71c1d4b35b8113d4eca6deaa1\\\"},\\\"requestInfo\\\":{\\\"source\\\":\\\"VID\\\",\\\"suppressRollback\\\":false,\\\"requestorId\\\":\\\"wl849v\\\"},\\\"relatedInstanceList\\\":[{\\\"relatedInstance\\\":{\\\"instanceId\\\":\\\"eb774932-e9fa-4c7f-bbc1-229b6b2b11e2\\\",\\\"modelInfo\\\":{\\\"modelType\\\":\\\"service\\\",\\\"modelInvariantId\\\":\\\"57dd617b-d64e-4441-a287-4d158b24ba65\\\",\\\"modelVersionId\\\":\\\"345643c1-3a51-423f-aac1-502e027d8dab\\\",\\\"modelName\\\":\\\"control_loop_dbe_svc\\\",\\\"modelVersion\\\":\\\"2.0\\\"}}}],\\\"requestParameters\\\":{\\\"payload\\\":\\\"{\\\\\\\"existing_software_version\\\\\\\":\\\\\\\"2\\\\\\\",\\\\\\\"new_software_version\\\\\\\":\\\\\\\"1\\\\\\\",\\\\\\\"operations_timeout\\\\\\\":\\\\\\\"3\\\\\\\"}\\\",\\\"testApi\\\":\\\"GR_API\\\"}}]}\"" + + " }" + + " ]," + + " \"scheduleApprovals\": []" + + " }," + + " \"schedulesId\": 0" + + " }" + + "]";; + + final RestObject mockedRestObject = mock(RestObject.class); + + final RestObjectWithRequestInfo restObjectWithRequestInfo = new RestObjectWithRequestInfo(HttpMethod.GET, "my pretty url", mockedRestObject, 200, responseString); + + when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenReturn( + restObjectWithRequestInfo + ); + + final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements(); + + assertSchedulerStatus(schedulerStatus, true); + assertMetadata(schedulerStatus, 200, startsWith(responseString.substring(0, 400)), "my pretty url", equalTo("OK")); + } + + @Test + public void probeGetSchedulerChangeManegements_response200OkButEmptyPayload_shouldDescribeCorrectly() { + String responseString = "" + + "[]"; + + final RestObject mockedRestObject = mock(RestObject.class); + + final RestObjectWithRequestInfo restObjectWithRequestInfo = new RestObjectWithRequestInfo(HttpMethod.GET, "my pretty url", mockedRestObject, 200, responseString); + + when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenReturn( + restObjectWithRequestInfo + ); + + final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements(); + + assertSchedulerStatus(schedulerStatus, true); + + assertMetadata(schedulerStatus, 200, equalTo(responseString), "my pretty url", containsString("OK")); + } + + @Test + public void probeGetSchedulerChangeManegements_response200OkButInvalidPayload_shouldDescribeCorrectly() { + String responseString = "this payload is an invalid json"; + + final RestObject mockedRestObject = mock(RestObject.class); + + final RestObjectWithRequestInfo restObjectWithRequestInfo = new RestObjectWithRequestInfo(HttpMethod.GET, "my pretty url", mockedRestObject, 200, responseString); + + when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenThrow(new ExceptionWithRequestInfo(HttpMethod.GET, + "my pretty url", responseString, 200, new JsonParseException(null, "Unrecognized token"))); + + final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements(); + + assertSchedulerStatus(schedulerStatus, false); + + assertMetadata(schedulerStatus, 200, equalTo(responseString), "my pretty url", containsString("JsonParseException: Unrecognized token")); + } + + @Test + public void probeGetSchedulerChangeManegements_throwNotFoundException_resultIsWithErrorMetadata() { + when(changeManagementService.getSchedulerChangeManagementsWithRequestInfo()).thenThrow( + new GenericUncheckedException(new NotFoundException("Get with status = 400"))); + + final ExternalComponentStatus schedulerStatus = schedulerService.probeGetSchedulerChangeManagements(); + + assertThat(schedulerStatus.isAvailable(), is(false)); + assertThat(schedulerStatus.getComponent(), is(SCHEDULER)); + assertThat(schedulerStatus.getMetadata(), instanceOf(ErrorMetadata.class)); + + final ErrorMetadata metadata = ((ErrorMetadata) schedulerStatus.getMetadata()); + org.junit.Assert.assertThat(metadata.getDescription(), containsString("NotFoundException: Get with status = 400")); + } + + private void assertSchedulerStatus(ExternalComponentStatus schedulerStatus, boolean isAvailable) { + assertThat(schedulerStatus.isAvailable(), is(isAvailable)); + assertThat(schedulerStatus.getComponent(), is(SCHEDULER)); + assertThat(schedulerStatus.getMetadata(), instanceOf(HttpRequestMetadata.class)); + } + + private void assertMetadata(ExternalComponentStatus schedulerStatus, int httpCode, Matcher rawData, String url, Matcher descriptionMatcher) { + final HttpRequestMetadata metadata = ((HttpRequestMetadata) schedulerStatus.getMetadata()); + org.junit.Assert.assertThat(metadata.getHttpMethod(), equalTo(HttpMethod.GET)); + org.junit.Assert.assertThat(metadata.getHttpCode(), equalTo(httpCode)); + org.junit.Assert.assertThat(metadata.getUrl(), equalTo(url)); + org.junit.Assert.assertThat(metadata.getRawData(), rawData); + org.junit.Assert.assertThat(metadata.getDescription(), descriptionMatcher); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java index b4c7828b..b80c75e5 100644 --- a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java +++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java @@ -3,6 +3,8 @@ package org.onap.vid.testUtils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Assert; @@ -10,20 +12,26 @@ import org.mockito.MockSettings; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.asdc.beans.Service; +import org.springframework.mock.env.MockEnvironment; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; +import java.net.URI; import java.util.Iterator; import java.util.List; import static fj.parser.Parser.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; /** @@ -31,6 +39,8 @@ import static org.mockito.Mockito.*; */ public class TestUtils { + private static final Logger logger = LogManager.getLogger(TestUtils.class); + /** * The method compares between two jsons. the function assert that the actual object does not reduce or change the functionallity/parsing of the expected json. * This means that if the expected JSON has a key which is null or the JSON doesn't have a key which contained in the expected JSON the assert will succeed and the will pass. @@ -77,7 +87,7 @@ public class TestUtils { } } else { - Assert.assertEquals(expectedValue, actualValue); + Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue); } } } @@ -99,6 +109,7 @@ public class TestUtils { public static class JavaxRsClientMocks { private final javax.ws.rs.client.Client fakeClient; private final javax.ws.rs.client.Invocation.Builder fakeBuilder; + private final javax.ws.rs.client.Invocation fakeInvocation; private final Response fakeResponse; public javax.ws.rs.client.Client getFakeClient() { @@ -118,6 +129,7 @@ public class TestUtils { fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings); fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings); + fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings); fakeResponse = mock(Response.class, mockSettings); final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings); @@ -125,16 +137,16 @@ public class TestUtils { fakeClient, fakeWebTarget, fakeBuilder, + fakeInvocation, fakeResponse ); - Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null); - Mockito.when(fakeBuilder.get(eq(InputStream.class))).thenReturn(new ByteArrayInputStream(new byte[]{})); Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null); - Mockito.when(fakeResponse.getStatus()).thenReturn(200); Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK); Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null); + Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{})); + Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null); } } @@ -155,9 +167,41 @@ public class TestUtils { return availableMocks.stream() .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass())) - //.peek(m -> System.out.println("found a mock: " + m.getClass().getName())) + //.peek(m -> logger.info("found a mock: " + m.getClass().getName())) .findFirst() .orElse(defaultReturn.answer(invocation)); } } + + + //The method mocks only some methods used in my case + //You may add some other when for your test here + public static Response mockResponseForJavaxClient(Client javaxClientMock) { + Response mockResponse = mock(Response.class); + WebTarget webTarget = mock(WebTarget.class); + Invocation.Builder builder = mock(Invocation.Builder.class); + when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget); + when(webTarget.path(any())).thenReturn(webTarget); + when(webTarget.request(any(MediaType.class))).thenReturn(builder); + when(builder.headers(any())).thenReturn(builder); + when(builder.header(any(), any())).thenReturn(builder); + when(builder.get()).thenReturn(mockResponse); + return mockResponse; + } + + + //Please use resetSystemProperties after using this method, so other test won't be affected + public static void mockSystemPropertyWithKeyValue(String key, String value) { + MockEnvironment mockEnvironment = new MockEnvironment(); + mockEnvironment.setProperty(key, value); + + SystemProperties systemProperties = new SystemProperties(); + systemProperties.setEnvironment(mockEnvironment); + } + + public static void resetSystemProperties() { + SystemProperties systemProperties = new SystemProperties(); + systemProperties.setEnvironment(null); + } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java index 2cd0d0cc..7fe25fe6 100644 --- a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingTest.java @@ -1,18 +1,10 @@ package org.onap.vid.utils; -import javax.servlet.http.HttpServletRequest; - -import org.junit.Test; -import org.springframework.http.HttpMethod; - import com.att.eelf.configuration.EELFLogger; +import org.junit.Test; public class LoggingTest { - private Logging createTestSubject() { - return new Logging(); - } - @Test public void testGetMethodName() throws Exception { String result; diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java index 7bc3fca1..ca27a226 100644 --- a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java @@ -1,8 +1,8 @@ package org.onap.vid.utils; +import com.fasterxml.jackson.core.JsonLocation; +import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; -import org.codehaus.jackson.JsonLocation; -import org.codehaus.jackson.JsonParseException; import org.onap.vid.exceptions.GenericUncheckedException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -47,15 +47,15 @@ public class LoggingUtilsTest { " expected a valid value (number, String, array, object, 'true', 'false' or 'null')", new JsonLocation("i'm an error", 25, 1, 1))); String codehausParseDescription = "" + - "org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)):" + + "com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)):" + " expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n" + - " at [Source: i'm an error; line: 1, column: 1]"; + " at [Source: (String)\"i'm an error\"; line: 1, column: 1]"; RuntimeException fasterxmlMappingException = new RuntimeException(new JsonMappingException("Can not deserialize instance of java.lang.String out of START_ARRAY token", new com.fasterxml.jackson.core.JsonLocation("{ example json }", 15, 1, 20))); String fasterxmlMappingDescription = "" + "com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token\n" + - " at [Source: { example json }; line: 1, column: 20]"; + " at [Source: (String)\"{ example json }\"; line: 1, column: 20]"; return new Object[][]{ {"javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No X509TrustManager implementation available", diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java new file mode 100644 index 00000000..274ba236 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/utils/TimeUtilsTest.java @@ -0,0 +1,67 @@ +package org.onap.vid.utils; + +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; + +public class TimeUtilsTest { + private static final Logger logger = LogManager.getLogger(TimeUtilsTest.class); + + @DataProvider + public static Object[][] goodData() { + return new Object[][]{ + {"Wed, 15 Oct 2014 13:01:52 GMT", 1413378112, "Timestamp as described in the documentation"}, + {"Wed, 15 Oct 2014 14:01:52 +0100", 1413378112, "GMT +1"}, + {"Wed, 15 Oct 2014 11:01:52 -0200", 1413378112, "GMT -2"} + }; + } + + @DataProvider + public static Object[][] goodDataToString() { + return new Object[][]{ + {"Wed, 15 Oct 2014 13:01:52 GMT", 1413378112, "UTC", "Timestamp as described in the documentation"}, + {"Wed, 15 Oct 2014 14:01:52 +0100", 1413378112, "+1", "GMT +1"}, + {"Wed, 15 Oct 2014 11:01:52 -0200", 1413378112, "-2", "GMT -2"} + }; + } + + @DataProvider + public static Object[][] badData() { + return new Object[][]{ + {"Wed, 15 Oct 2014 13:01:52", "No offset"}, + {"Wed, 15 Oct 2014 13:01:52 UTC", "UTC"}, + {"Wed, 15 Oct 2014 13:01:52 UT", "UT"}, + {"Wed, 15 Oct 2014 13:01:52Z", "Zulu time"}, + {"Wed, 15 Oct 2014 13:01:52 EST", "EST time"} + }; + } + + @Test(dataProvider = "goodData") + public void parseSuccessTest(String timestamp, long expectedResult, String description) { + logger.info(description); + ZonedDateTime parsedTime = TimeUtils.parseZonedDateTime(timestamp); + Assert.assertEquals(parsedTime.toEpochSecond(), expectedResult); + } + + @Test(expectedExceptions = DateTimeParseException.class, dataProvider = "badData") + public void parseFailedTest(String timestamp, String description) { + logger.info(description); + TimeUtils.parseZonedDateTime(timestamp); + } + + @Test(dataProvider = "goodDataToString") + public void toStringSuccessTest(String expectedResult, long epochTime, String zoneId, String description) { + logger.info(description); + Instant instant = Instant.ofEpochSecond(epochTime); + ZonedDateTime time = ZonedDateTime.ofInstant(instant, ZoneId.of(zoneId)); + String timeStamp = TimeUtils.zonedDateTimeToString(time); + Assert.assertEquals(timeStamp, expectedResult); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java new file mode 100644 index 00000000..8691032b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/utils/TreeTest.java @@ -0,0 +1,63 @@ +package org.onap.vid.utils; + +import com.google.common.collect.ImmutableList; +import org.jetbrains.annotations.NotNull; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.testng.Assert.*; + +public class TreeTest { + + @NotNull + protected Tree buildTreeForTest() { + Tree tree = new Tree<>("a"); + tree.addPath("b","c","d"); + tree.addPath("b","cc","dd"); + tree.addPath("1","2","dd"); + return tree; + } + + @DataProvider + public static Object[][] pathsToFind() { + return new Object[][]{ + {ImmutableList.of("b","c","d"), true}, + {ImmutableList.of("b","c"), true}, + {ImmutableList.of("b","cc","dd"), true}, + {ImmutableList.of("b","cc","d"), false}, + {ImmutableList.of("1","2","dd"), true}, + {ImmutableList.of("b"), true}, + {ImmutableList.of("c"), false}, + {ImmutableList.of("z", "z", "z", "z", "z"), false}, + }; + } + + @Test(dataProvider="pathsToFind") + public void whenBuildTree_nodesFoundsInRoute(List path, boolean isFound) { + Tree tree = buildTreeForTest(); + assertEquals(isFound, tree.isPathExist(path)); + } + + @Test(dataProvider="pathsToFind") + public void whenBuildTree_subTreeGetRight(List path, boolean isFound) { + Tree tree = buildTreeForTest(); + if (isFound) { + assertNotNull(tree.getSubTree(path)); + } + else { + assertNull(tree.getSubTree(path)); + } + } + + @Test + public void whenBuildTree_getSubTreeAsExpected() { + Tree tree = buildTreeForTest(); + Tree subTree = tree.getSubTree("b","c"); + assertEquals(subTree.getRootValue(), "c"); + assertTrue(subTree.isPathExist("d")); + assertFalse(subTree.isPathExist("b","c","d")); + } +} diff --git a/vid-app-common/src/test/resources/WEB-INF/fusion/conf/fusion.properties b/vid-app-common/src/test/resources/WEB-INF/fusion/conf/fusion.properties index 3d8e8155..f35bf2d6 100644 --- a/vid-app-common/src/test/resources/WEB-INF/fusion/conf/fusion.properties +++ b/vid-app-common/src/test/resources/WEB-INF/fusion/conf/fusion.properties @@ -1,50 +1,27 @@ -# domain settings -#domain_class_location = com.att.fusion.domain. - -# validator settings -#default_error_message = Default error message - # login settings -login_method_csp = csp -login_method_web_junction = web_junction login_method_backdoor = backdoor +login_method_web_junction = login_method_web_junction +login_method_csp = login_method_csp login_method_attribute_name = login_method +authentication_mechanism = BOTH +role_function_list = role_funcion_list #login message login.error.hrid.empty = Login failed, please contact system administrator. login.error.hrid.not-found = User not found, please contact system administrator. login.error.user.inactive = Account is disabled, please contact system administrator. -# CSP settings -csp_cookie_name = attESSec -csp_gate_keeper_data_key = MgmtSysCtr -csp_gate_keeper_prod_key = PROD -csp_login_url = https://www.e-access.att.com/empsvcs/hrpinmgt/pagLogin/?sysName=MgmtSysCtr&retURL= -csp_logout_url = https://www.e-access.att.com/empsvcs/hrpinmgt/pagLogout/?retURL= - -authentication_mechanism = BOTH - -#csp_gate_keeper_prod_key = DEVL -user_attribute_name = user -#csp_login_url = https://www.e-access.att.com/empsvcs/hrpinmgt/pagLogin/?sysName=MgmtSysCtr&retURL= -#csp_logout_url = https://webtest.csp.att.com/empsvcs/hrpinmgt/pagLogout/?retURL= - -# Web Junction settings -#web_junction_user_id_header_name = iv-user - # User Session settings -#user_attribute_name = user +user_attribute_name = user roles_attribute_name = roles role_functions_attribute_name = role_functions -role_function_list = role_function_list #client_device_attribute_name = client_device #client_device_emulation = false -#client_device_type_to_emulate = com.att.fusion.web.clientdevice.mobile.IPhoneDevice -# POST settings +# Import-user LDAP settings post_initial_context_factory = com.sun.jndi.ldap.LdapCtxFactory -post_provider_url = ldap://ldap.webphone.att.com:389 -post_security_principal = ou=people,o=att,c=us +post_provider_url = ldap://ldap.mycompany.com:389 +post_security_principal = ou=people,o=mycompany,c=us post_max_result_size = 499 # menu settings diff --git a/vid-app-common/src/test/resources/WEB-INF/fusion/defs/definitions.xml b/vid-app-common/src/test/resources/WEB-INF/fusion/defs/definitions.xml index c9e10a16..caefb19c 100644 --- a/vid-app-common/src/test/resources/WEB-INF/fusion/defs/definitions.xml +++ b/vid-app-common/src/test/resources/WEB-INF/fusion/defs/definitions.xml @@ -2,11 +2,6 @@ - - - @@ -93,11 +88,6 @@ value="/WEB-INF/fusion/jsp/collaborateList.jsp"> - - @@ -138,18 +128,9 @@ --> - - - - - - - + + + - + \ No newline at end of file diff --git a/vid-automation/TestNg-UI-half.xml b/vid-automation/TestNg-UI-half.xml index 025bd3f7..bc51c9fc 100644 --- a/vid-automation/TestNg-UI-half.xml +++ b/vid-automation/TestNg-UI-half.xml @@ -18,18 +18,21 @@ }; String [] classes2 = new String [] { "vid.automation.test.test.AddNetworkTest", - "vid.automation.test.test.ALaCarteflowTest", - "vid.automation.test.test.AssociatePnfTest", "vid.automation.test.test.BrowseASDCTest", "vid.automation.test.test.ChangeManagementTest", - "vid.automation.test.test.CreateNewInstanceTest", - "vid.automation.test.test.CreatePortMirroringConfigurationTest" + "vid.automation.test.test.ALaCarteflowTest", + "vid.automation.test.test.VlanTagSubInterfaceTest", + "vid.automation.test.test.CreateNewInstanceTest" }; + String [] classes3 = new String [] { - "vid.automation.test.test.DrawingBoardTest" + "vid.automation.test.test.NewServiceInstanceTest", + "vid.automation.test.test.CreatePortMirroringConfigurationTest" }; + String [] classes4 = new String [] { - "vid.automation.test.test.NewServiceInstanceTest" + "vid.automation.test.test.DrawingBoardTest", + "vid.automation.test.test.ViewEditServiceInstanceTest" }; int selectPart = 0; diff --git a/vid-automation/TestNg-dev.xml b/vid-automation/TestNg-dev.xml new file mode 100644 index 00000000..b8bc84f9 --- /dev/null +++ b/vid-automation/TestNg-dev.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/vid-automation/TestNg.xml b/vid-automation/TestNg.xml deleted file mode 100644 index a9eac97a..00000000 --- a/vid-automation/TestNg.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/vid-automation/conf/services b/vid-automation/conf/services index c67a3662..85e0552f 100644 --- a/vid-automation/conf/services +++ b/vid-automation/conf/services @@ -43,7 +43,7 @@ "1a80c596-27e5-4ca9-b5bb-e03a7fd4c0fd": { "type" : "pnf", "uuid": "1a80c596-27e5-4ca9-b5bb-e03a7fd4c0fd", - "invariantUuid": "e49fbd11-e60c-4a8e-b4bf-30fbe8f4fcc0", + "invariantUuid": "cdb90b57-ed78-4d44-a5b4-7f43a02ec632", "name": "action-data", "version": "1.0", "category": "Network L1-3", diff --git a/vid-automation/conf/users b/vid-automation/conf/users index e6d3c6ac..e2bc05a8 100644 --- a/vid-automation/conf/users +++ b/vid-automation/conf/users @@ -13,9 +13,9 @@ "userId": "1", "password": "1" }, - "roles": ["USP VOICE___VIRTUAL USP", "MSO_1610_ST___MSO-dev-service-type", "MSO_1610_ST___VIRTUAL USP"], + "roles": ["USP VOICE___VIRTUAL USP", "USP VOICE___HOSTED COMMUNICATIONS", "MSO_1610_ST___HOSTED COMMUNICATIONS", "MSO_1610_ST___MSO-dev-service-type", "MSO_1610_ST___VIRTUAL USP"], "subscriberNames": ["USP VOICE", "MSO_1610_ST"], - "serviceTypes": ["VIRTUAL USP", "MSO-dev-service-type"], + "serviceTypes": ["VIRTUAL USP", "HOSTED COMMUNICATIONS", "MSO-dev-service-type"], "tenants": ["092eb9e8e4b7412e8787dd091bc58e86"] }, "mobilityMobility": { diff --git a/vid-automation/pom.xml b/vid-automation/pom.xml index f8bd6460..dfd61aae 100644 --- a/vid-automation/pom.xml +++ b/vid-automation/pom.xml @@ -6,19 +6,18 @@ automationTest 1.0-SNAPSHOT - 4.2.0.RELEASE + 4.2.9.RELEASE 2.23.1 2.6.3 1.8.10 - com.google.guava guava - + 23.0 org.openecomp.sdc @@ -32,11 +31,11 @@ - + 1.2.17 + org.testng testng diff --git a/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/mso/PresetMSOServiceInstanceGen2WithNames.java b/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/mso/PresetMSOServiceInstanceGen2WithNames.java index 52c3071f..98187b9a 100644 --- a/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/mso/PresetMSOServiceInstanceGen2WithNames.java +++ b/vid-automation/src/main/java/org/onap/simulator/presetGenerator/presets/mso/PresetMSOServiceInstanceGen2WithNames.java @@ -45,7 +45,7 @@ public abstract class PresetMSOServiceInstanceGen2WithNames extends PresetMSOBas " \"productFamilyId\": \"myProductFamilyId\"," + " \"source\": \"VID\"," + " \"suppressRollback\": false," + - " \"requestorId\": \"ab2222\"" + + " \"requestorId\": \"vid1\"" + " }," + " \"requestParameters\": {" + " \"subscriptionServiceType\": \"mySubType\"," + diff --git a/vid-automation/src/main/java/vid/automation/test/services/UsersService.java b/vid-automation/src/main/java/vid/automation/test/services/UsersService.java index 282be906..ac8af451 100644 --- a/vid-automation/src/main/java/vid/automation/test/services/UsersService.java +++ b/vid-automation/src/main/java/vid/automation/test/services/UsersService.java @@ -1,6 +1,5 @@ package vid.automation.test.services; -import com.att.automation.common.report_portal_integration.annotations.Step; import com.google.common.primitives.Ints; import org.apache.commons.lang3.StringUtils; import vid.automation.test.model.User; @@ -38,7 +37,6 @@ public class UsersService { return usersObject.users; } - @Step("${method} with id: ${userId}") public User getUser(String userId) { User res = users.get(userId); System.out.println("getUser userId='" + userId + "' returned: " + res); diff --git a/vid-automation/src/main/java/vid/automation/test/test/VidBaseTestCase.java b/vid-automation/src/main/java/vid/automation/test/test/VidBaseTestCase.java index 5c0206c0..e5a8b578 100644 --- a/vid-automation/src/main/java/vid/automation/test/test/VidBaseTestCase.java +++ b/vid-automation/src/main/java/vid/automation/test/test/VidBaseTestCase.java @@ -1,23 +1,11 @@ package vid.automation.test.test; -import com.att.automation.common.report_portal_integration.annotations.Step; -import com.att.automation.common.report_portal_integration.listeners.ReportPortalListener; -import com.att.automation.common.report_portal_integration.screenshots.WebDriverScreenshotsProvider; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.onap.simulator.presetGenerator.presets.BasePresets.BasePreset; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAICloudRegionAndSourceFromConfigurationPut; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetNetworkZones; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetPortMirroringSourcePorts; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetServicesGet; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubDetailsGet; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetTenants; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIPostNamedQueryForViewEdit; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAISearchNodeQueryEmptyResult; -import org.onap.simulator.presetGenerator.presets.aai.PresetAAIServiceDesignAndCreationPut; +import org.onap.simulator.presetGenerator.presets.aai.*; import org.onap.simulator.presetGenerator.presets.ecompportal_att.PresetGetSessionSlotCheckIntervalGet; import org.onap.simulator.presetGenerator.presets.mso.PresetMSOCreateServiceInstanceGen2; import org.onap.simulator.presetGenerator.presets.mso.PresetMSOCreateServiceInstancePost; @@ -34,7 +22,6 @@ import org.openqa.selenium.WebElement; import org.testng.ITestContext; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Listeners; import org.testng.annotations.Test; import vid.automation.test.Constants; import vid.automation.test.infra.*; @@ -60,7 +47,6 @@ import static org.hamcrest.core.Is.is; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.fail; -@Listeners(com.att.automation.common.report_portal_integration.listeners.ReportPortalListener.class) public class VidBaseTestCase extends SetupCDTest{ protected final UsersService usersService = new UsersService(); @@ -109,7 +95,7 @@ public class VidBaseTestCase extends SetupCDTest{ @BeforeSuite(alwaysRun = true) public void screenShotsForReportPortal(){ try { - ReportPortalListener.setScreenShotsProvider(new WebDriverScreenshotsProvider(getDriver())); + //ReportPortalListener.setScreenShotsProvider(new WebDriverScreenshotsProvider(getDriver())); System.out.println("Called to ReportPortalListener to set ScreenShotsProvider"); } catch (Exception e) { e.printStackTrace(); @@ -301,7 +287,6 @@ public class VidBaseTestCase extends SetupCDTest{ Assert.assertTrue(Constants.ViewEdit.VF_MODULE_CREATION_FAILED_MESSAGE, byText); } - @Step("${method}: ${instanceUUID}") void goToExistingInstanceById(String instanceUUID) { SearchExistingPage searchExistingPage = searchExistingInstanceById(instanceUUID); assertViewEditButtonState( Constants.VIEW_EDIT_BUTTON_TEXT, instanceUUID); diff --git a/vid-automation/src/main/java/vid/automation/test/test/ViewEditServiceInstanceTest.java b/vid-automation/src/main/java/vid/automation/test/test/ViewEditServiceInstanceTest.java index e07acc3a..3b9546fd 100644 --- a/vid-automation/src/main/java/vid/automation/test/test/ViewEditServiceInstanceTest.java +++ b/vid-automation/src/main/java/vid/automation/test/test/ViewEditServiceInstanceTest.java @@ -28,7 +28,6 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.apache.logging.log4j.core.util.Assert.isNonEmpty; import static org.hamcrest.Matchers.equalTo; import static org.testng.AssertJUnit.assertEquals; import static vid.automation.test.infra.Features.FLAG_COLLECTION_RESOURCE_SUPPORT; @@ -359,7 +358,7 @@ public class ViewEditServiceInstanceTest extends VidBaseTestCase { "pending-delete", false); for(Map.Entry entry: vfModulesStatuses.entrySet()) { WebElement vfModule = GeneralUIUtils.getWebElementByClassName("vfModuleTreeNode-" + entry.getKey()); - Assert.assertEquals(isNonEmpty(vfModule.findElements(By.className("resume"))), entry.getValue()); + Assert.assertEquals(!vfModule.findElements(By.className("resume")).isEmpty(), entry.getValue()); } } diff --git a/vid-automation/src/main/java/vid/automation/test/utils/DB_CONFIG.java b/vid-automation/src/main/java/vid/automation/test/utils/DB_CONFIG.java index 18cda6bd..ef562523 100644 --- a/vid-automation/src/main/java/vid/automation/test/utils/DB_CONFIG.java +++ b/vid-automation/src/main/java/vid/automation/test/utils/DB_CONFIG.java @@ -1,7 +1,7 @@ package vid.automation.test.utils; public class DB_CONFIG { - public static String url = String.format("jdbc:mariadb://%s:%d/vid_portal", + public static String url = String.format("jdbc:mariadb://%s:%d/vid_openecomp_epsdk", System.getProperty("DB_HOST", System.getProperty("VID_HOST", "127.0.0.1" )), Integer.valueOf(System.getProperty("DB_PORT", "3306")) ); diff --git a/vid-automation/src/main/resources/META-INF/aop-ajc.xml b/vid-automation/src/main/resources/META-INF/aop-ajc.xml index 7376e329..77505c75 100644 --- a/vid-automation/src/main/resources/META-INF/aop-ajc.xml +++ b/vid-automation/src/main/resources/META-INF/aop-ajc.xml @@ -1,18 +1,2 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/vid-automation/src/test/java/org/onap/vid/api/AsyncInstantiationApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/AsyncInstantiationApiTest.java index 1a0e1c9b..a5b72c26 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/AsyncInstantiationApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/AsyncInstantiationApiTest.java @@ -13,11 +13,7 @@ import org.onap.simulator.presetGenerator.presets.BasePresets.BasePreset; import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet; import org.onap.simulator.presetGenerator.presets.aai.PresetAAISearchNodeQueryEmptyResult; import org.onap.simulator.presetGenerator.presets.ecompportal_att.PresetGetSessionSlotCheckIntervalGet; -import org.onap.simulator.presetGenerator.presets.mso.PresetMSOAssignServiceInstanceGen2WithNames; -import org.onap.simulator.presetGenerator.presets.mso.PresetMSOCreateServiceInstanceGen2WithNames; -import org.onap.simulator.presetGenerator.presets.mso.PresetMSOOrchestrationRequestGet; -import org.onap.simulator.presetGenerator.presets.mso.PresetMSOOrchestrationRequestGetErrorResponse; -import org.onap.simulator.presetGenerator.presets.mso.PresetMSOServiceInstanceGen2ErrorResponse; +import org.onap.simulator.presetGenerator.presets.mso.*; import org.onap.vid.model.asyncInstantiation.JobAuditStatus; import org.onap.vid.model.asyncInstantiation.ServiceInfo; import org.onap.vid.model.mso.MsoResponseWrapper2; @@ -25,7 +21,6 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; - import org.springframework.web.client.RestTemplate; import org.testng.Assert; import org.testng.annotations.DataProvider; @@ -35,8 +30,8 @@ import vid.automation.test.infra.Features; import vid.automation.test.infra.Wait; import vid.automation.test.model.JobStatus; import vid.automation.test.services.SimulatorApi; -import java.util.*; +import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -400,7 +395,7 @@ public class AsyncInstantiationApiTest extends BaseMsoApiTest { List jobIds = createBulkOfInstances(presets, isPause, bulkSize, names); Assert.assertEquals(jobIds.size(),bulkSize); for(String jobId: jobIds) { - ServiceInfo expectedServiceInfo = new ServiceInfo("ab2222", JobStatus.IN_PROGRESS, isPause, "someID", + ServiceInfo expectedServiceInfo = new ServiceInfo("vid1", JobStatus.IN_PROGRESS, isPause, "someID", "someName", "myProject", "NFT1", "NFTJSSSS-NFT1", "greatTenant", "greatTenant", "mtn3", null, "mySubType", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", null, names.get(Keys.SERVICE_NAME), "300adb1e-9b0c-4d52-bfb5-fa5393c4eabb", "AIM_TRANSPORT_00004", "1.0", jobId, null); diff --git a/vid-automation/src/test/java/org/onap/vid/api/BaseApiAaiTest.java b/vid-automation/src/test/java/org/onap/vid/api/BaseApiAaiTest.java index 4ac38a0e..69a6f66c 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/BaseApiAaiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/BaseApiAaiTest.java @@ -15,9 +15,9 @@ import java.net.URI; import java.net.URISyntaxException; import static net.javacrumbs.jsonunit.JsonMatchers.jsonStringEquals; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.either; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; import static vid.automation.test.services.SimulatorApi.registerExpectation; /** diff --git a/vid-automation/src/test/java/org/onap/vid/api/BaseApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/BaseApiTest.java index 22365717..e7c6045a 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/BaseApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/BaseApiTest.java @@ -1,11 +1,10 @@ package org.onap.vid.api; -import com.att.automation.common.report_portal_integration.listeners.ReportPortalListener; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.primitives.Ints; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.glassfish.jersey.client.ClientProperties; @@ -19,7 +18,6 @@ import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.RestTemplate; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; -import org.testng.annotations.Listeners; import vid.automation.test.infra.FeaturesTogglingConfiguration; import vid.automation.test.services.UsersService; import vid.automation.test.utils.CookieAndJsonHttpHeadersInterceptor; @@ -44,7 +42,6 @@ import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; -@Listeners(ReportPortalListener.class) public class BaseApiTest { protected static final Logger LOGGER = LogManager.getLogger(BaseApiTest.class); @@ -100,7 +97,7 @@ public class BaseApiTest { static String password = "euser"; static final int userId = 2222; - static final String loginId = "ab2222"; + static final String loginId = "vid1"; static final int roleId = 2222221; static final int logRoleId = 2222222; } diff --git a/vid-automation/src/test/java/org/onap/vid/api/BaseMsoApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/BaseMsoApiTest.java index 37601a65..1495f185 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/BaseMsoApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/BaseMsoApiTest.java @@ -1,6 +1,5 @@ package org.onap.vid.api; -import com.att.automation.common.report_portal_integration.annotations.Step; import com.google.common.collect.ImmutableMap; import org.json.JSONException; import org.onap.vid.model.mso.MsoResponseWrapper2; @@ -17,8 +16,8 @@ import vid.automation.test.services.SimulatorApi.RegistrationStrategy; import java.io.IOException; import java.lang.reflect.Method; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; public class BaseMsoApiTest extends BaseApiTest { @@ -53,7 +52,6 @@ public class BaseMsoApiTest extends BaseApiTest { } } - @Step(description = "method: ${method}, uri: ${uri}, body: ${body}") protected MsoResponseWrapper2 callMsoForResponseWrapper(HttpMethod method, String uri, String body) { MsoResponseWrapper2 responseWrapper; switch (method) { diff --git a/vid-automation/src/test/java/org/onap/vid/api/ChangeManagementApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/ChangeManagementApiTest.java index 93f72195..2ad68d75 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/ChangeManagementApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/ChangeManagementApiTest.java @@ -20,8 +20,8 @@ import org.onap.vid.model.workflow.VnfWorkflowRelationAllResponse; import org.onap.vid.model.workflow.VnfWorkflowRelationRequest; import org.onap.vid.model.workflow.VnfWorkflowRelationResponse; import org.onap.vid.model.workflow.WorkflowsDetail; -import org.opencomp.vid.model.mso.*; -import org.opencomp.vid.model.workflow.*; +import org.onap.vid.model.mso.*; +import org.onap.vid.model.workflow.*; import org.springframework.http.HttpStatus; import org.springframework.util.StopWatch; import org.testng.Assert; diff --git a/vid-automation/src/test/java/org/onap/vid/api/OperationalEnvironmentControllerApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/OperationalEnvironmentControllerApiTest.java index 222b0f5f..e5df2d3b 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/OperationalEnvironmentControllerApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/OperationalEnvironmentControllerApiTest.java @@ -22,8 +22,8 @@ import java.util.LinkedList; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.METHOD_NOT_ALLOWED; diff --git a/vid-automation/src/test/java/org/onap/vid/api/ProbeApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/ProbeApiTest.java index 54093ec5..931f0004 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/ProbeApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/ProbeApiTest.java @@ -2,6 +2,7 @@ package org.onap.vid.api; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.hamcrest.MatcherAssert; import org.junit.Assert; import org.onap.simulator.presetGenerator.presets.BasePresets.BasePreset; import org.onap.simulator.presetGenerator.presets.aai.PresetAAIGetSubscribersGet; @@ -93,10 +94,10 @@ public class ProbeApiTest extends BaseApiTest { ExternalComponentStatus aaiGetAllSubscribersStatus = aaiGetAllSubscribersResult.get(); Assert.assertEquals(aaiGetAllSubscribersStatus.isAvailable(),expectedStatus.isAvailable()); - Assert.assertThat(requestMetadataReflected(aaiGetAllSubscribersStatus.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata()))); - Assert.assertThat(aaiGetAllSubscribersStatus.getMetadata().getUrl(), both(endsWith(expectedStatus.getMetadata().getUrl())).and(startsWith("http"))); + MatcherAssert.assertThat(requestMetadataReflected(aaiGetAllSubscribersStatus.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata()))); + MatcherAssert.assertThat(aaiGetAllSubscribersStatus.getMetadata().getUrl(), both(endsWith(expectedStatus.getMetadata().getUrl())).and(startsWith("http"))); - Assert.assertThat(aaiGetAllSubscribersStatus.getMetadata().getDescription(), + MatcherAssert.assertThat(aaiGetAllSubscribersStatus.getMetadata().getDescription(), anyOf(equalTo(expectedStatus.getMetadata().getDescription()), startsWith(expectedStatus.getMetadata().getDescription()))); } diff --git a/vid-automation/src/test/java/org/onap/vid/api/SampleApiTest.java b/vid-automation/src/test/java/org/onap/vid/api/SampleApiTest.java index c57a90ae..2b78cdb9 100644 --- a/vid-automation/src/test/java/org/onap/vid/api/SampleApiTest.java +++ b/vid-automation/src/test/java/org/onap/vid/api/SampleApiTest.java @@ -11,8 +11,8 @@ import vid.automation.test.services.SimulatorApi; import java.io.IOException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; public class SampleApiTest extends BaseApiTest { diff --git a/vid-automation/src/test/java/org/onap/vid/model/probe/ExternalComponentStatus.java b/vid-automation/src/test/java/org/onap/vid/model/probe/ExternalComponentStatus.java index 43976494..b247613d 100644 --- a/vid-automation/src/test/java/org/onap/vid/model/probe/ExternalComponentStatus.java +++ b/vid-automation/src/test/java/org/onap/vid/model/probe/ExternalComponentStatus.java @@ -1,7 +1,7 @@ package org.onap.vid.model.probe; public class ExternalComponentStatus { - public enum Component {AAI, MSO} + public enum Component {AAI, MSO, SCHEDULER} private Component component; private boolean available; private HttpRequestMetadata metadata; diff --git a/vid-automation/src/test/java/org/onap/vid/more/LoggerFormatTest.java b/vid-automation/src/test/java/org/onap/vid/more/LoggerFormatTest.java index 6656a6c6..fd8f4827 100644 --- a/vid-automation/src/test/java/org/onap/vid/more/LoggerFormatTest.java +++ b/vid-automation/src/test/java/org/onap/vid/more/LoggerFormatTest.java @@ -14,9 +14,9 @@ import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertThat; public class LoggerFormatTest extends BaseApiTest { diff --git a/vid-automation/src/test/java/org/onap/vid/more/RequestIdFilterInstalled.java b/vid-automation/src/test/java/org/onap/vid/more/RequestIdFilterInstalled.java index 5a0a0f84..56053873 100644 --- a/vid-automation/src/test/java/org/onap/vid/more/RequestIdFilterInstalled.java +++ b/vid-automation/src/test/java/org/onap/vid/more/RequestIdFilterInstalled.java @@ -4,8 +4,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; -import org.onap.vid.api.OperationalEnvironmentControllerApiTest; import org.onap.vid.api.BaseApiTest; +import org.onap.vid.api.OperationalEnvironmentControllerApiTest; import org.onap.vid.api.ServiceInstanceMsoApiTest; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -18,9 +18,9 @@ import vid.automation.test.services.SimulatorApi; import java.util.UUID; import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; import static org.onap.vid.api.CategoryParametersApiTest.GET_CATEGORY_PARAMETER_PROPERTIES; import static org.onap.vid.api.pProbeMsoApiTest.MSO_CREATE_CONFIGURATION; import static org.springframework.http.HttpHeaders.AUTHORIZATION; diff --git a/vid-automation/src/test/resources/test_config.properties b/vid-automation/src/test/resources/test_config.properties index ce4ce6a7..db876b7d 100644 --- a/vid-automation/src/test/resources/test_config.properties +++ b/vid-automation/src/test/resources/test_config.properties @@ -1,3 +1,3 @@ -test.loginId=ab2222 -test.loginPassword=ab2222 +test.loginId=vid1 +test.loginPassword=Kp8bJ4SXszM0WX diff --git a/vid-ext-services-simulator/pom.xml b/vid-ext-services-simulator/pom.xml index 42c411cc..165ae576 100644 --- a/vid-ext-services-simulator/pom.xml +++ b/vid-ext-services-simulator/pom.xml @@ -13,7 +13,7 @@ UTF-8 1.3.0 - 4.2.0.RELEASE + 4.3.4.RELEASE 4.3.11.Final true @@ -109,12 +109,12 @@ org.springframework spring-web - 4.3.4.RELEASE + ${springframework.version} org.springframework spring-webmvc - 4.3.4.RELEASE + ${springframework.version} com.fasterxml.jackson.core -- cgit 1.2.3-korg